-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cds-plugin.js
340 lines (319 loc) · 9.52 KB
/
cds-plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
'use strict';
const {access, writeFile, mkdir} = require('node:fs/promises');
const {resolve, join, relative} = require('node:path');
const {faker} = require('@faker-js/faker');
const {json2csv} = require('json-2-csv');
const cds = require('@sap/cds');
const logger = cds.log('mockdata-plugin');
const regxpAnnotationTag = new RegExp(`^@Mockdata.`);
const TOTAL_ROWS = 50;
let mockdataPlugin = null;
if (cds?.add?.Plugin && cds.add?.register) {
mockdataPlugin = class MockdataTemplate extends cds.add.Plugin {
async run() {
const csn = await getCsn();
const csnSQL = cds.compile.for.sql(csn, {names: cds.env.sql.names}); // CSN with persistence information
for (const entity of csn.entities) {
if (!isEntitySupported(entity)) {
continue;
}
await processEntity(entity, csnSQL);
}
}
};
cds.add.register('mockdata', mockdataPlugin);
module.exports = mockdataPlugin;
}
/**
* Get CSN
* @returns {object}
*/
async function getCsn() {
let csn = await cds.compile(cds.env.roots, {min: true});
csn = includeExternalEntities(csn);
return cds.reflect(csn); // reflected model (adds additional helper functions)
}
/**
* Determine whether the entity is supported or not
* @param {cds.entity} entity
* @returns {boolean}
*/
function isEntitySupported(entity) {
if (entity.query) { // Only database tables
return false;
}
if (entity.name === 'DRAFT.DraftAdministrativeData' && entity.name.endsWith('.drafts')) { // No drafts
return false;
}
if (entity.drafts) { // No drafts
return false;
}
if (entity.name.endsWith('.texts')) { // No localized texts
return false;
}
return true;
}
/**
* Determine whether the entity element is supported or not
* @param {cds.entity} element
* @param {cds.entity} elementSql
* @returns {boolean}
*/
function isElementSupported(element, elementSql) {
if (!element) { // No empty elements
return false;
}
if (!elementSql?.['@cds.persistence.name']) { // Only fields persisted in database tables
return false;
}
if (element.type === 'cds.Association' || element.type === 'cds.Composition') { // No Association nor Composition fields
return false;
// entityElement = entityElement.foreignKeys[element.keys[0]['as']];
}
return true;
}
/**
* Check whether file/folder can be accessed
* @param {string} path
* @returns {boolean}
*/
async function hasAccess(path) {
try {
await access(path);
return true;
} catch (err) {
return false;
}
}
/**
* Check whether property is a valid annotation
* @param {string} property
* @returns {boolean}
*/
function isValidAnnotation(property) {
return regxpAnnotationTag.test(property);
}
/**
* Get the Faker method to be used
* @param {cds.entity} element
* @returns {any}
*/
function getFakerMethod(element) {
const method = buildFakerMethodByAnnotation(element);
return method ? method() : buildFakerMethodByType(element.type, element.length);
}
/**
* Build the Faker method using CDS annotations
* @param {string} cdsType
* @param {number} length
* @returns {any}
*/
function buildFakerMethodByType(cdsType, length) {
const maxLength = length || 255;
switch (cdsType) {
case 'cds.UUID':
return faker.string.uuid();
case 'cds.Boolean':
return faker.datatype.boolean();
case 'cds.UInt8':
return faker.number.int({min: 0, max: 255});
case 'cds.Int16':
return faker.number.int({min: -32768, max: 32767});
case 'cds.Int32':
return faker.number.int();
case 'cds.Integer':
return faker.number.int();
case 'cds.Int64':
return faker.number.bigInt();
case 'cds.Integer64':
return faker.number.bigInt();
case 'cds.Decimal':
return faker.number.float();
case 'cds.Double':
return faker.number.float();
case 'cds.Date':
return faker.date.anytime();
case 'cds.Time':
return faker.date.anytime();
case 'cds.DateTime':
return faker.date.anytime();
case 'cds.Timestamp':
return faker.date.anytime();
case 'cds.String':
return faker.lorem.words().substring(0, maxLength - 1);
case 'cds.Binary':
return faker.string.binary({length: {max: maxLength}});
case 'cds.LargeBinary':
return faker.string.binary({length: {max: maxLength}});
case 'cds.LargeString':
return faker.lorem.words(20).substring(0, maxLength - 1);
case 'User':
return faker.internet.userName().substring(0, maxLength - 1);
default:
return faker.lorem.words().substring(0, maxLength - 1);
}
}
/**
* Build the Faker method using CDS annotations
* @param {cds.entity} element
* @returns {object}
*/
function buildFakerMethodByAnnotation(element) {
let obj = '';
let method = '';
const properties = Object.entries(element);
for (const [key, value] of properties) {
if (isValidAnnotation(key)) {
obj = key.split('.')[1];
method = value;
break;
}
}
return faker[obj]?.[method];
}
/**
* Include extenal entities
* @param {object} csn
* @returns {object}
*/
function includeExternalEntities(csn) {
for (const [key, definition] of Object.entries(csn.definitions)) {
if (definition['@cds.persistence.skip'] === true) {
logger.info('Including skipped entity ' + key);
delete definition['@cds.persistence.skip'];
}
}
return csn;
}
/**
* Process CDS Entity to generate mock data
* @param {cds.entity} entity
* @param {cds.link} csnSQL
*/
async function processEntity(entity, csnSQL) {
const namespace = getNamespace(csnSQL, entity.name);
const path = await getDefaultTargetFolder(cds.env);
const dataFilePath = getFilename(entity, namespace, path);
const data = prepareDataFileContent(entity, csnSQL.definitions[entity.name]);
await createDataFile(dataFilePath, path, data);
}
/**
* Get the default folder to save the generated files
* @param {cds.env} env
* @returns {string}
*/
async function getDefaultTargetFolder(env) {
const {db} = env.folders;
// csv files should be located in the 'db/data' folder unless a 'db/csv' folder already exists
const path = join(db, await hasAccess(join(db, 'csv')) ? 'csv' : 'data');
return resolve(cds.root, path);
}
/**
* Create CSV files with mock data
* @param {string} filename
* @param {string} path
* @param {string} dataFileContent
*/
async function createDataFile(filename, path, dataFileContent) {
let relativeFilePath = filename;
const isFileExists = await hasAccess(filename);
const {force} = cds.cli.options;
if (filename.indexOf(cds.root) === 0) {
// use relative path in log (for readability), only when data files are added within the project
// (potentially can be located anywhere using the --out parameter)
relativeFilePath = relative(cds.root, filename);
}
if (isFileExists && !force) {
logger.info(`Skipping ${relativeFilePath}`);
} else { // continue only if file not already exists, or '--force' option provided
if (dataFileContent && dataFileContent.length) {
if (!await hasAccess(path)) {
await mkdir(path, {recursive: true});
}
await writeFile(filename, dataFileContent);
isFileExists ? logger.info(`Overwriting ${relativeFilePath}`) : logger.info(`Creating ${relativeFilePath}`);
}
}
}
/**
* Generate mock data to populate CSV file
* @param {cds.entity} entity
* @param {cds.entity} entitySql
* @returns {string}
*/
function prepareDataFileContent(entity, entitySql) {
const data = [];
for (const [key, element] of Object.entries(entity.elements)) {
if (!isElementSupported(element, entitySql.elements[key])) {
continue;
}
const localdata = generateData(element);
for (let i = 0; i < TOTAL_ROWS; i++) {
if (!data[i]) {
data[i] = {};
}
data[i][key] = localdata[i];
}
}
return json2csv(data);
}
/**
* Generate mock data for entity
* @param {object} entityElement
* @returns {object[]}
*/
function generateData(entityElement) {
let localdata = [];
if (entityElement.key) {
localdata = faker.helpers.uniqueArray(() => getFakerMethod(entityElement), TOTAL_ROWS);
} else {
localdata = faker.helpers.multiple(() => getFakerMethod(entityElement), {count: TOTAL_ROWS});
}
return localdata;
}
/**
* Get entity namespace
* @param {object} csn
* @param {string} artifactName
* @returns {string}
*/
function getNamespace(csn, artifactName) {
const parts = artifactName.split('.');
let seen = parts[0];
const art = csn.definitions[seen];
// First step is not a namespace (we faked those in the CSN)
// No subsequent step can be a namespace then
if (art && art.kind !== 'namespace' && art.kind !== 'context') {
return null;
}
const length = parts.length;
for (let i = 1; i < length; i++) {
// This was definitely a namespace so far
const previousArtifactName = seen;
seen = `${seen}.${parts[i]}`;
// This might not be - if it isn't, return the result.
const currentArtifact = csn.definitions[seen];
if (currentArtifact && currentArtifact.kind !== 'namespace' && currentArtifact.kind !== 'context') {
return previousArtifactName;
}
}
// We came till here - so the full artifactName is a namespace
return artifactName;
}
/**
* Get filename
* @param {cds.entity} entity
* @param {string} namespace
* @param {string} path
* @returns {string}
*/
function getFilename(entity, namespace, path) {
let filename = '';
if (!namespace || namespace === entity.name) {
filename = `${entity.name}.csv`;
} else {
const entityName = entity.name.replace(namespace + '.', '');
filename = `${namespace}-${entityName}.csv`;
}
return join(path, filename);
}