Skip to content

Instantly share code, notes, and snippets.

@bdombro
Created November 30, 2020 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdombro/3ee44a838c1f564f600ac44de0717156 to your computer and use it in GitHub Desktop.
Save bdombro/3ee44a838c1f564f600ac44de0717156 to your computer and use it in GitHub Desktop.
prismaSchemaGen.ts - an approach to prisma modularization
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