Last active
April 3, 2020 03:48
-
-
Save railsstudent/4a48e97f02d2bcc77eb1d81bf2292d73 to your computer and use it in GitHub Desktop.
Generate file to export TypeORM entities in an ts file
This file contains hidden or 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
// https://medium.com/@p3rf/solving-issue-with-entities-loading-for-a-nx-dev-monorepo-setup-with-nest-js-and-typeorm-282d4491f0bc | |
// npm install --save-dev fast-glob | |
// ... | |
// "scripts": { | |
// ... | |
// "create-entities-index": "ts-node --pretty --project=tools/tsconfig.tools.json tools/create-entities-index.ts", | |
// ... | |
// } | |
// ... | |
// import * as entities from '../database/entities-index'; | |
// ... | |
// @Module({ | |
// imports: [TypeOrmModule.forRoot({ | |
// ... | |
// entities: Object.values(entities), | |
// ... | |
// })], | |
// ... | |
// }) | |
// ... | |
import * as fg from 'fast-glob'; | |
import * as fs from 'fs'; | |
import * as path from 'path'; | |
function createEntitiesIndex() { | |
console.log('Creating entity-index.ts for api app'); | |
const src = `${path.dirname(__dirname)}/apps/api/src`; | |
if (!fs.existsSync(src)) { | |
console.log(`App api cannot be found. Path not exist: ${src}`); | |
process.exit(1); | |
} | |
const outDir = `${src}/database`; | |
const tmpFile = `${outDir}/tmp-entities-index.ts`; | |
const outFile = `${outDir}/entities-index.ts`; | |
if (!fs.existsSync(outDir)) { | |
fs.mkdirSync(outDir); | |
} | |
for (const item of fg.sync(`${src}/**/*.entity.ts`)) { | |
const filePath = path.relative(outDir, item).replace(/\.ts$/, ''); | |
const data = `export * from '${filePath}'\n`; | |
fs.writeFileSync(tmpFile, data, { flag: 'a+' }); | |
} | |
if (fs.existsSync(outFile) && fs.existsSync(tmpFile)) { | |
fs.unlinkSync(outFile); | |
console.log(`Old file '${outFile}' removed`); | |
} | |
if (fs.existsSync(tmpFile)) { | |
fs.renameSync(tmpFile, outFile); | |
console.log(`New file ${outFile} saved`); | |
} | |
} | |
createEntitiesIndex(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment