Created
November 30, 2020 16:56
-
-
Save bdombro/3ee44a838c1f564f600ac44de0717156 to your computer and use it in GitHub Desktop.
prismaSchemaGen.ts - an approach to prisma modularization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fs from 'fs' | |
import * as glob from 'glob' | |
const datasource = fs.readFileSync('prisma/datasource.prisma') | |
const moduleFiles = glob.sync('src/**/*.prisma', {}) | |
const modules = moduleFiles.reduce((a,f) => { | |
const module = fs.readFileSync(f) | |
return a + module | |
}, '') | |
const schemaRaw = datasource + modules | |
const schemaMerged = '// This file was generated by schemaGen.ts\n' + prismaSchemaMergeExtends(schemaRaw) | |
fs.writeFileSync('prisma/schema.prisma', schemaMerged) | |
console.log('schemaGen.ts: Prisma Schema Generated') | |
function prismaSchemaMergeExtends(schema: string) { | |
const noExtends = schema.replace(/extends [^{]*[^}]*\}/sg, '') | |
const onlyExtends = schema.match(/extends [^{]*[^}]*\}/sg) || [] | |
let merged = noExtends | |
onlyExtends.forEach(extension => { | |
const [_, extendsTo, extendsWith] = extension.match(/extends ([^ ]* [^ ]*) \{([^}]*)/) as string[] | |
const extendsToRegExp = new RegExp(`${extendsTo}[^}]*}`) | |
const extendsToNext = merged.match(extendsToRegExp)![0].replace('}', extendsWith + '}') | |
// process.stdout.write(JSON.stringify(test, null, 2).replace(/\\n/g, '\n')) | |
merged = merged.replace(extendsToRegExp, extendsToNext) | |
}) | |
return merged | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment