|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import { createOutputDir, writeFile, writeTypesIndex } from 'file-utils'; |
| 3 | +import path from 'node:path'; |
| 4 | +import { writeFileSync } from 'node:fs'; |
| 5 | +import { eventSchemasDir, listEventSchemas, loadSchema } from 'utils'; |
| 6 | + |
| 7 | +export async function generateGuardFunctions() { |
| 8 | + const eventSchemaFilenames = listEventSchemas(); |
| 9 | + const outputDir = createOutputDir('guard-functions'); |
| 10 | + console.log(`Output directory created at ${outputDir}`); |
| 11 | + |
| 12 | + console.group('Writing guard functions:'); |
| 13 | + const indexLines: string[] = []; |
| 14 | + for (const eventSchemaFilename of eventSchemaFilenames) { |
| 15 | + const eventSchemaPath = path.join(eventSchemasDir, eventSchemaFilename); |
| 16 | + const eventSchema = loadSchema(eventSchemaPath); |
| 17 | + const typeName = eventSchema.title; |
| 18 | + |
| 19 | + const validatorVariableName = `event${typeName}Validator`; |
| 20 | + |
| 21 | + let eventTs = `import ${validatorVariableName} from 'digital-letters-events/${typeName}.js'\n`; |
| 22 | + eventTs += `import type { ${typeName} } from 'digital-letters-events';\n`; |
| 23 | + eventTs += `import { Logger } from 'utils';\n\n`; |
| 24 | + |
| 25 | + eventTs += `export function validate${typeName}(\n`; |
| 26 | + eventTs += ` event: unknown,\n`; |
| 27 | + eventTs += ` logger: Logger,\n`; |
| 28 | + eventTs += `): ${typeName} | null {\n\n`; |
| 29 | + |
| 30 | + eventTs += ` const eventValidator = event${typeName}Validator as (d: unknown) => d is ${typeName};\n\n`; |
| 31 | + |
| 32 | + eventTs += ` if (!eventValidator(event)) {\n`; |
| 33 | + eventTs += ` logger.error({\n`; |
| 34 | + eventTs += ` err: ${validatorVariableName}.errors,\n`; |
| 35 | + eventTs += ` description: 'Error parsing ${typeName} event',\n`; |
| 36 | + eventTs += ` });\n`; |
| 37 | + eventTs += ` return null;\n`; |
| 38 | + eventTs += ` }\n\n`; |
| 39 | + |
| 40 | + eventTs += ` return event;\n`; |
| 41 | + eventTs += `}\n\n`; |
| 42 | + |
| 43 | + |
| 44 | + const typeDeclarationName = `${typeName}`; |
| 45 | + const typeDeclarationFilename = `${typeDeclarationName}.ts`; |
| 46 | + writeFile(outputDir, typeDeclarationFilename, eventTs); |
| 47 | + console.log(typeDeclarationFilename); |
| 48 | + |
| 49 | + indexLines.push(`export * from './${typeDeclarationName}';`); |
| 50 | + } |
| 51 | + console.groupEnd(); |
| 52 | + |
| 53 | + writeFileSync(path.join(outputDir, 'index.ts'), `${indexLines.join('\n')}\n`); |
| 54 | + console.log('index.ts file written'); |
| 55 | +} |
0 commit comments