|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | + |
| 4 | +const fileContentPrefix = `/* tslint:disable */ |
| 5 | +/* |
| 6 | + * --------------------------------------------------------------- |
| 7 | + * ## THIS FILE WAS GENERATED ## |
| 8 | + * ## ## |
| 9 | + * ## See extract-constants.ts for more details ## |
| 10 | + * --------------------------------------------------------------- |
| 11 | + */ |
| 12 | +`; |
| 13 | + |
| 14 | +const inputPath = path.resolve(process.cwd(), 'spec/openapi.json'); |
| 15 | +const outputPath = path.resolve(process.cwd(), 'src/constants.ts'); |
| 16 | + |
| 17 | +const file = await fs.promises.readFile(inputPath, 'utf-8'); |
| 18 | +const api = JSON.parse(file); |
| 19 | +const constants: Record<string, number | string | string[] | number[]> = {}; |
| 20 | +for (const [schemaName, schema] of Object.entries(api.components.schemas)) { |
| 21 | + if ( |
| 22 | + schema && |
| 23 | + typeof schema === 'object' && |
| 24 | + 'maxLength' in schema && |
| 25 | + typeof schema.maxLength === 'number' |
| 26 | + ) { |
| 27 | + constants[formatKey(schemaName, 'maxLength')] = schema.maxLength; |
| 28 | + } |
| 29 | + |
| 30 | + if ( |
| 31 | + schema && |
| 32 | + typeof schema === 'object' && |
| 33 | + 'minLength' in schema && |
| 34 | + typeof schema.minLength === 'number' |
| 35 | + ) { |
| 36 | + constants[formatKey(schemaName, 'minLength')] = schema.minLength; |
| 37 | + } |
| 38 | + |
| 39 | + if ( |
| 40 | + schema && |
| 41 | + typeof schema === 'object' && |
| 42 | + 'pattern' in schema && |
| 43 | + typeof schema.pattern === 'string' |
| 44 | + ) { |
| 45 | + constants[formatKey(schemaName, 'pattern')] = schema.pattern; |
| 46 | + } |
| 47 | + |
| 48 | + if ( |
| 49 | + schema && |
| 50 | + typeof schema === 'object' && |
| 51 | + 'enum' in schema && |
| 52 | + Array.isArray(schema.enum) && |
| 53 | + (schema.enum.every((item) => typeof item === 'string') || |
| 54 | + schema.enum.every((item) => typeof item === 'number')) |
| 55 | + ) { |
| 56 | + constants[formatKey(schemaName, 'enum')] = schema.enum; |
| 57 | + } |
| 58 | +} |
| 59 | +const constantLines = Object.entries(constants) |
| 60 | + .map(([key, value]) => { |
| 61 | + if (Array.isArray(value)) { |
| 62 | + return `export const ${key}:${JSON.stringify(value)} = ${JSON.stringify(value)};`; |
| 63 | + } |
| 64 | + return `export const ${key} = ${JSON.stringify(value)};`; |
| 65 | + }) |
| 66 | + .join('\n'); |
| 67 | + |
| 68 | +await fs.promises.writeFile(outputPath, `${fileContentPrefix}\n${constantLines}`); |
| 69 | + |
| 70 | +function formatKey(schemaName: string, key: string) { |
| 71 | + return convertCamelToSnake(`${schemaName}_${key}`); |
| 72 | +} |
| 73 | + |
| 74 | +function convertCamelToSnake(str: string) { |
| 75 | + return str.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase(); |
| 76 | +} |
0 commit comments