31 lines
1.1 KiB
JavaScript
31 lines
1.1 KiB
JavaScript
import openapiTS, { astToString } from 'openapi-typescript'
|
|
import prettier from 'prettier'
|
|
import path from 'path'
|
|
import fs from 'node:fs/promises'
|
|
import { fileURLToPath } from 'url'
|
|
|
|
const { format, resolveConfig } = prettier
|
|
/**
|
|
* @param openapiUrl {string}
|
|
* @param outputFilePath {string}
|
|
* @param pathToPrettierRc {string}
|
|
*/
|
|
export async function generateApiSchema(openapiUrl, outputFilePath, pathToPrettierRc) {
|
|
const request = new Request(openapiUrl)
|
|
const response = await fetch(request)
|
|
const json = await response.text()
|
|
const ast = await openapiTS(json, {
|
|
pathParamsAsTypes: true,
|
|
})
|
|
const prettierConfig = await resolveConfig(pathToPrettierRc, {
|
|
useCache: true,
|
|
})
|
|
let schemaCode = astToString(ast)
|
|
schemaCode = await format(schemaCode, { parser: 'typescript', ...prettierConfig })
|
|
await fs.writeFile(path.join(outputFilePath), schemaCode)
|
|
}
|
|
|
|
if (fileURLToPath(import.meta.url) === process.argv[1]) {
|
|
if (!process.env.OPENAPI_URL) throw new Error('OPENAPI_URL is not defined')
|
|
await generateApiSchema(process.env.OPENAPI_URL, './src/app/api/schema.ts', './.prettierrc')
|
|
}
|