fets
Version:
TypeScript HTTP Framework focusing on e2e type-safety, easy setup, performance & great developer experience
50 lines (49 loc) • 1.74 kB
JavaScript
import { promises as fsPromises } from 'node:fs';
import { isAbsolute, join } from 'node:path';
import { parseArgs } from 'node:util';
import { load as yamlLoad } from 'js-yaml';
import { fetch } from '@whatwg-node/fetch';
const options = {
'openapi-url': {
type: 'string',
},
'output-file': {
type: 'string',
},
};
export async function cli(argv = process.argv.slice(2)) {
const args = [...argv];
while (args[0]?.startsWith('/') || args[0] === '--') {
args.shift();
}
const { values: { 'openapi-url': openapiUrl, 'output-file': outputFile = 'oas.ts' }, } = parseArgs({ args, options, allowPositionals: true });
if (!openapiUrl) {
throw new Error('You have to run with --openapi-url <url>');
}
if (!outputFile.endsWith('.ts')) {
throw new Error('output-file must be ts file like `--output-file oas.ts`');
}
console.log(`Fetching ${openapiUrl}`);
let rawData;
if (openapiUrl.startsWith('http')) {
const res = await fetch(openapiUrl);
rawData = await res.text();
if (!res.ok) {
throw new Error(`Failed to fetch ${openapiUrl}: ${rawData}`);
}
}
else {
rawData = await fsPromises.readFile(openapiUrl, 'utf-8');
}
const jsonData = yamlLoad(rawData);
const oas = JSON.stringify(jsonData, null, 2);
const content = `// This file is generated by fets-cli
// Do not edit this file directly
// @eslint-ignore
// prettier-ignore
export default ${oas} as const
`;
const absoluteOutputFile = isAbsolute(outputFile) ? outputFile : join(process.cwd(), outputFile);
console.log(`Writing to ${absoluteOutputFile}`);
await fsPromises.writeFile(outputFile, content);
}