UNPKG

@25sprout/react-starter

Version:

25sprout web starter with React

59 lines (45 loc) 1.55 kB
import '@25sprout-frontend/dotenv'; import 'isomorphic-fetch'; import { generateApi } from 'swagger-typescript-api'; import fs from 'fs/promises'; import path from 'path'; import setting from './setting'; const PROJECT_PATH = path.join(process.cwd()); const SCHEMA_PATH = `${PROJECT_PATH}/src/util/api/apiSchema.json`; const fetchSchema = async url => { if (url === '' || !url) { const defaultSchema = await fs.readFile(SCHEMA_PATH, { encoding: 'utf8', }); return defaultSchema; } const headers = new Headers({ 'Content-Type': 'application/json', Accept: 'application/json', 'X-Bsx-Api-Doc-Key': process.env.SWAGGER_API_SCHEMA_KEY, }); // 有 url 才執行 fetch const res = await fetch(url, { headers }); const result = await res.json(); return JSON.stringify(result); }; const getSchemaAndPaste = async (str, targetStr, replaceStr) => { try { const result = str.replaceAll(targetStr, replaceStr); // opertionId 會造成 api 命名錯誤,所以全局替換 ref: https://github.com/acacode/swagger-typescript-api/issues/319 await fs.writeFile(SCHEMA_PATH, result); } catch (err) { console.log(err); } }; const init = async () => { try { const schema = await fetchSchema(process.env.SWAGGER_API_SCHEMA_URL); // step1: fetch swagger schema json,並 replaceAll operationId,並且放置在 'config/api-schema.json' await getSchemaAndPaste(schema, 'operationId', 'test'); // step2: 產生 api (call generateApi) await generateApi(setting); } catch (err) { console.log(err); } }; init();