UNPKG

tsdk

Version:

Type-safe API development and code share tool for TypeScript projects.

349 lines (343 loc) 13.4 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.replaceGenAPI = exports.copyPermissionsJSON = exports.syncAPI = exports.deleteSDKFolder = exports.baseDir = void 0; const fs_extra_1 = __importDefault(require("fs-extra")); const path_1 = __importDefault(require("path")); const config_1 = require("./config"); const symbols_1 = __importDefault(require("./symbols")); exports.baseDir = path_1.default.join(path_1.default.relative(path_1.default.dirname(__filename), process.cwd()), config_1.ensureDir); function deleteSDKFolder() { return fs_extra_1.default.remove(path_1.default.resolve(process.cwd(), config_1.config.packageDir, config_1.packageFolder)); } exports.deleteSDKFolder = deleteSDKFolder; function syncAPI() { return __awaiter(this, void 0, void 0, function* () { var _a, _b; console.log(symbols_1.default.bullet, 'generating APIs'); yield replaceGenAPI(); const pkgJSON = require(path_1.default.join(exports.baseDir, 'package.json')); const apiconfs = require(path_1.default.join(exports.baseDir, 'lib', `${config_1.config.apiconfExt}-refs`)); const keys = Object.keys(apiconfs); keys.sort(); const types = [...new Set(keys.map((k) => apiconfs[k].type))].filter((i) => !!i); if (!types.includes('common')) { types.push('common'); } types.sort(); const isSWR = ((_a = config_1.config.dataHookLib) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'swr'; const isReactQuery = ((_b = config_1.config.dataHookLib) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'reactquery'; types.forEach((apiType) => { const dataHookHeadStr = ` ${!isSWR ? '' : `import useSWR, { SWRConfiguration } from "swr"; import useSWRMutation, { SWRMutationConfiguration } from "swr/mutation"; ${config_1.config.httpLib !== 'xior' ? `import type { AxiosRequestConfig } from "axios";` : `import type { XiorRequestConfig as AxiosRequestConfig } from "xior";`} `} ${!isReactQuery ? '' : `import { useQuery, useMutation, QueryClient, UndefinedInitialDataOptions, UseMutationOptions, } from "@tanstack/react-query"; ${config_1.config.httpLib !== 'xior' ? `import type { AxiosRequestConfig } from "axios";` : `import type { XiorRequestConfig as AxiosRequestConfig } from "xior";`} `} import { Handler } from './gen-api'; `; let dataHookImportStr = ``; let dataHookBodyStr = isReactQuery ? ` let _queryClient: QueryClient; ${apiType === 'common' ? ` export function setQueryClientForCommon(queryClient: QueryClient) { _queryClient = queryClient; } ` : ` `} ` : ``; const headStr = ` /** * * api-${apiType}.ts * ${config_1.config.packageName}@${pkgJSON.version} * **/ import genApi, { Expand } from './gen-api'; `; let importStr = ``; let bodyStr = ``; const hasCommon = keys.find((k) => { const item = apiconfs[k]; return (item.type === 'common' || !item.type) && item.path; }); const exportStr = apiType === 'common' || !hasCommon ? `` : `\nexport * from './common-api';\n`; const dataHookExportStr = apiType === 'common' || !hasCommon ? `` : `\nexport * from './common-api-hooks'; ${isReactQuery ? ` import { setQueryClientForCommon } from './common-api-hooks'; export function setQueryClient(queryClient: QueryClient) { _queryClient = queryClient; setQueryClientForCommon(queryClient); } ` : `${isReactQuery ? ` export function setQueryClient(queryClient: QueryClient) { _queryClient = queryClient; } ` : ``}`} `; let hasContentCount = 0; keys.forEach((k, idx) => { const { name: _name, path, description, method, type: _type, category = 'others', } = apiconfs[k]; const name = _name || k.replace(/Config$/, ''); const type = _type === 'common' || !_type ? 'common' : _type; const isGET = !method || (method === null || method === void 0 ? void 0 : method.toLowerCase()) === 'get'; const likeGET = apiconfs[k].isGet === false ? false : apiconfs[k].isGet === true || isGET; if (type === apiType && path) { importStr += ` ${name}Config, type ${name}Req, type ${name}Res, `; bodyStr += ` /** * ${description} * * @category ${category} */ export const ${name} = genApi<Expand<${name}Req>${isGET ? '' : ' | FormData'}, Expand<${name}Res>>(${name}Config); `; dataHookImportStr += ` ${name}, `; if (isSWR) { dataHookBodyStr += ` ${likeGET ? ` /** * ${description} * * @category ${category} */ export function use${name}( payload?: ${name}Req, options?: SWRConfiguration<${name}Res | undefined>, requestConfig?: AxiosRequestConfig<${name}Req>, customHandler?: Handler, ) { return useSWR( () => ({ url: ${name}.config.path, arg: payload }), ({ arg }) => { if (typeof arg === 'undefined') return undefined; return ${name}(arg, requestConfig, customHandler); }, options ); } ` : ` /** * ${description} * * @category ${category} */ export function use${name}( options?: SWRMutationConfiguration< ${name}Res, Error, string, ${name}Req | FormData >, requestConfig?: AxiosRequestConfig<${name}Req | FormData>, customHandler?: Handler, ) { return useSWRMutation( ${name}.config.path, (url, { arg }: { arg: ${name}Req | FormData }) => { return ${name}(arg, requestConfig, customHandler); }, options ); }`} `; } else if (isReactQuery) { dataHookBodyStr += ` ${likeGET ? ` /** * ${description} * * @category ${category} */ export function use${name}( payload?: ${name}Req, options?: UndefinedInitialDataOptions<${name}Res | undefined, Error>, queryClient?: QueryClient, requestConfig?: AxiosRequestConfig<${name}Req>, customHandler?: Handler, ) { return useQuery( { ...(options || {}), queryKey: [${name}.config.path, payload], queryFn() { if (typeof payload === 'undefined') { return undefined; } return ${name}(payload, requestConfig, customHandler); }, }, queryClient || _queryClient ); }` : ` /** * ${description} * * @category ${category} */ export function use${name}( options?: UseMutationOptions< ${name}Res, Error, ${name}Req | FormData, unknown >, queryClient?: QueryClient, requestConfig?: AxiosRequestConfig<${name}Req | FormData>, customHandler?: Handler, ) { return useMutation( { ...(options || {}), mutationFn(payload) { return ${name}(payload, requestConfig, customHandler); }, }, queryClient || _queryClient ); } `} `; } hasContentCount++; } }); if (hasContentCount > 0) { const content = ` ${headStr} ${importStr ? `import { ${importStr} } from './${config_1.config.apiconfExt}-refs';` : ''} ${exportStr} ${bodyStr} `; fs_extra_1.default.writeFileSync(path_1.default.join(config_1.ensureDir, `src`, `${apiType}-api.ts`), content); const dataHookContent = ` ${dataHookHeadStr} ${importStr ? `import { ${importStr} } from './${config_1.config.apiconfExt}-refs';` : ''} ${dataHookImportStr ? `import { ${dataHookImportStr} } from './${apiType}-api';` : ''} ${dataHookExportStr} ${dataHookBodyStr} `; fs_extra_1.default.writeFileSync(path_1.default.join(config_1.ensureDir, `src`, `${apiType}-api-hooks.ts`), dataHookContent); } }); console.log(symbols_1.default.success, 'generated APIs'); const exportPermissions = {}; keys.forEach((k) => { const item = apiconfs[k]; if (typeof item !== 'object') return; item.name = item.name || k.replace(/Config$/, ''); if (!exportPermissions[item.type]) { exportPermissions[item.type] = []; } if (item.schema) { item.schema = {}; } exportPermissions[item.type].push(item); }); yield fs_extra_1.default.writeFile(path_1.default.join(config_1.ensureDir, 'src', `permissions.json`), JSON.stringify(exportPermissions, null, 2)); console.log(symbols_1.default.bullet, 'Docs config'); // sync APIs docs const links = []; types.forEach((apiType) => { if (apiType === 'common') return; links.push(`- [${apiType} APIs](/modules/${apiType}_api)`); }); const projectName = `%PROJECT NAME%`; try { let getStartedContent = yield fs_extra_1.default.readFile(path_1.default.join(__dirname, '..', 'fe-sdk-template', 'README.md'), 'utf-8'); getStartedContent = getStartedContent .replace(new RegExp(projectName, 'g'), config_1.config.packageName) .replace('%API_REFERENCE%', links.join('\n')); yield fs_extra_1.default.writeFile(path_1.default.join(config_1.ensureDir, 'README.md'), getStartedContent); console.log(symbols_1.default.success, 'Docs config'); } catch (e) { if (e instanceof Error) { console.log(symbols_1.default.error, 'Docs config error', e.message); } } }); } exports.syncAPI = syncAPI; function copyPermissionsJSON() { const dist = path_1.default.join(config_1.ensureDir, `lib`, `permissions.json`); console.log(symbols_1.default.info, `copy \`permission.json\` to \`${dist}\``); return fs_extra_1.default.copy(path_1.default.join(config_1.ensureDir, `src`, `permissions.json`), dist, { overwrite: true, }); } exports.copyPermissionsJSON = copyPermissionsJSON; function replaceGenAPI() { return __awaiter(this, void 0, void 0, function* () { if (config_1.config.httpLib === 'xior') { const genAPIfile = path_1.default.join(config_1.ensureDir, 'src', 'gen-api.ts'); const res = yield fs_extra_1.default.readFile(genAPIfile, 'utf-8'); return fs_extra_1.default.writeFile(genAPIfile, res .replace('= AxiosRequestConfig<T>', '= XiorRequestConfig<T>') .replace(`import type { RequestConfig as AxiosRequestConfig } from './axios';`, '')); } }); } exports.replaceGenAPI = replaceGenAPI;