Skip to content

Commit

Permalink
Safer api generation
Browse files Browse the repository at this point in the history
  • Loading branch information
Samuel-Therrien-Beslogic committed Nov 28, 2024
1 parent 26f5606 commit 1238296
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions canopeum_frontend/apiSchemaGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })

0 comments on commit 1238296

Please sign in to comment.