From d30260634dace16b39bbb231393627f37b7b23e7 Mon Sep 17 00:00:00 2001 From: Gao Sun Date: Sat, 3 Jul 2021 19:19:12 +0800 Subject: [PATCH] feat: conditional generate custom types file and export types in index --- packages/schemas/src/db-entries/index.ts | 1 + packages/schemas/src/gen/index.ts | 54 +++++++++++++----------- 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/packages/schemas/src/db-entries/index.ts b/packages/schemas/src/db-entries/index.ts index 9b3d837b7..d3678596b 100644 --- a/packages/schemas/src/db-entries/index.ts +++ b/packages/schemas/src/db-entries/index.ts @@ -1,4 +1,5 @@ // THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +export * from './custom-types'; export * from './oidc-model-instance'; export * from './user'; diff --git a/packages/schemas/src/gen/index.ts b/packages/schemas/src/gen/index.ts index 357ada298..74129e4a9 100644 --- a/packages/schemas/src/gen/index.ts +++ b/packages/schemas/src/gen/index.ts @@ -115,6 +115,7 @@ const generate = async () => { ); const generatedDir = 'src/db-entries'; + const generatedTypesFilename = 'custom-types'; const header = '// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n\n'; const getOutputFileName = (file: string) => pluralize(file.slice(0, -4).replace(/_/g, '-'), 1); @@ -127,21 +128,23 @@ const generate = async () => { tsName: camelcase(type.name, { pascalCase: true }), })); - // Generate custom types - await fs.writeFile( - path.join(generatedDir, 'custom-types.ts'), - header + - allTypes - .map(({ tsName, values }) => - [ - `export enum ${tsName} {`, - ...values.map((value) => ` ${value} = '${value}',`), - '}', - ].join('\n') - ) - .join('\n') + - '\n' - ); + if (allTypes.length > 0) { + // Generate custom types + await fs.writeFile( + path.join(generatedDir, `${generatedTypesFilename}.ts`), + header + + allTypes + .map(({ tsName, values }) => + [ + `export enum ${tsName} {`, + ...values.map((value) => ` ${value} = '${value}',`), + '}', + ].join('\n') + ) + .join('\n') + + '\n' + ); + } // Generate DB entry types await Promise.all( @@ -160,16 +163,16 @@ const generate = async () => { }), })); - const importTypes = - customTypes.length > 0 - ? [ - 'import {', - uniq(customTypes) - .map((value) => ` ${value}`) - .join(',\n'), - "} from './custom-types';", - ].join('\n') + '\n\n' - : ''; + const importTypes = conditionalString( + customTypes.length > 0 && + [ + 'import {', + uniq(customTypes) + .map((value) => ` ${value}`) + .join(',\n'), + `} from './${generatedTypesFilename}';`, + ].join('\n') + '\n\n' + ); const content = header + @@ -202,6 +205,7 @@ const generate = async () => { await fs.writeFile( path.join(generatedDir, 'index.ts'), header + + conditionalString(allTypes.length > 0 && `export * from './${generatedTypesFilename}';`) + generated.map(([file]) => `export * from './${getOutputFileName(file)}';`).join('\n') + '\n' );