-
Notifications
You must be signed in to change notification settings - Fork 6
/
mergePrisma.js
79 lines (70 loc) · 2.84 KB
/
mergePrisma.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
/**************************************************************************
* (C) Copyright Mojaloop Foundation 2020 *
* *
* This file is made available under the terms of the license agreement *
* specified in the corresponding source code repository. *
* *
* ORIGINAL AUTHOR: *
* Yevhen Kyriukha <[email protected]> *
**************************************************************************/
const fs = require('fs');
const path = require('path');
const prismaDir = path.join(__dirname, 'prisma');
const baseDir = path.join(prismaDir, 'base');
const overlayDir = path.join(prismaDir, 'overlays');
const outDir = path.join(__dirname, 'src/generated');
const parseSchema = (path) => {
const schema = {};
let currentBlock;
let currentKey;
fs.readFileSync(path, 'utf-8').split(/\r?\n/).forEach((line) => {
const components = line.trim().split(/\s+/);
if (components[2] === '{') {
const def = components.slice(0, 2).join(' ');
schema[def] = {};
currentBlock = def;
} else if (currentBlock && !['}', ''].includes(components[0])) {
const block = schema[currentBlock];
// const key = /(?<!@)@(?!@)/.test(components[0]) ? currentKey : components[0];
let key;
if (components[0].startsWith('@@')) {
key = components.join(' ');
} else if (components[0].startsWith('@')) {
key = currentKey;
} else {
key = components[0];
}
block[key] = (block[key] || []).concat(...components);
currentKey = key;
}
});
return schema;
}
const mergeSchema = (name) => {
const baseSchema = parseSchema(path.join(baseDir, name));
const overlaySchema = fs.existsSync(path.join(overlayDir, name)) ?
parseSchema(path.join(overlayDir, name)) : {};
let data = [];
const blockDefs = [...new Set(Object.keys(baseSchema).concat(Object.keys(overlaySchema)))];
for (const blockDef of blockDefs) {
data.push(`${blockDef} {`);
const blockKeys = Object.keys(overlaySchema[blockDef] || {}).concat(Object.keys(baseSchema[blockDef] || {}))
const seen = new Set();
for (const key of blockKeys) {
if (seen.has(key)) continue;
data.push((overlaySchema[blockDef]?.[key] || baseSchema[blockDef]?.[key]).join(' '))
seen.add(key);
}
data.push('}');
}
fs.writeFileSync(path.join(outDir, name), data.join('\n'));
}
fs.mkdirSync(outDir, { recursive: true });
const dir = fs.opendirSync(baseDir);
let dirent
while ((dirent = dir.readSync()) !== null) {
console.log(`Processing ${dirent.name} ...`);
const schema = path.basename(dirent.name);
mergeSchema(schema);
}
dir.closeSync()