From 12382966cdf541db83f540fb44b744c2de09871e Mon Sep 17 00:00:00 2001 From: Samuel Therrien Date: Wed, 27 Nov 2024 21:32:21 -0500 Subject: [PATCH] Safer api generation --- canopeum_frontend/apiSchemaGenerator.js | 27 +++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/canopeum_frontend/apiSchemaGenerator.js b/canopeum_frontend/apiSchemaGenerator.js index 7dd7e945..c6bf99d1 100644 --- a/canopeum_frontend/apiSchemaGenerator.js +++ b/canopeum_frontend/apiSchemaGenerator.js @@ -5,17 +5,36 @@ import * as url from 'node:url' const __dirname = url.fileURLToPath(new URL('.', import.meta.url)) const schemaUrl = 'http://127.0.0.1:8000/api/schema/' -const outputPath = path.join(__dirname, 'openapi.yaml') const nswagPath = path.join(__dirname, '..', 'docs', 'canopeum.nswag') +// eslint-disable-next-line unicorn/prefer-json-parse-buffer -- typescript disagrees +const nswagConfigJSON = JSON.parse(fs.readFileSync(nswagPath, 'utf8')) +const openAPIPath = path.join( + nswagPath, + '..', + nswagConfigJSON.documentGenerator.fromDocument.url, +) +const generatedAPIPath = path.join( + nswagPath, + '..', + nswagConfigJSON.codeGenerators.openApiToTypeScriptClient.output, +) + const response = await fetch(schemaUrl) if (!response.ok) { throw new Error('Failed to fetch schema, make sure the backend server is running') } -const text = await response.text() -fs.writeFileSync(outputPath, text) +fs.writeFileSync(openAPIPath, await response.text()) spawnSync('nswag', ['run', nswagPath], { stdio: 'inherit', shell: true }) console.info('Removing schema') -fs.unlinkSync(outputPath) +fs.unlinkSync(openAPIPath) + +console.info('Fixing unsafe type') +fs.writeFileSync( + generatedAPIPath, + fs.readFileSync(generatedAPIPath, 'utf8') + .replaceAll('[key: string]: any', '[key: string]: unknown'), +) + console.info('Running dprint formatter') spawnSync('dprint fmt', { stdio: 'inherit', shell: true })