UNPKG

swaxios

Version:

Swagger API client generator based on axios and TypeScript.

223 lines 9.11 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MethodGenerator = exports.HttpMethod = void 0; const StringUtil = __importStar(require("../util/StringUtil")); const InterfaceGenerator_1 = require("./InterfaceGenerator"); var HttpMethod; (function (HttpMethod) { HttpMethod["DELETE"] = "delete"; HttpMethod["GET"] = "get"; HttpMethod["HEAD"] = "head"; HttpMethod["PATCH"] = "patch"; HttpMethod["POST"] = "post"; HttpMethod["PUT"] = "put"; HttpMethod["REQUEST"] = "request"; })(HttpMethod || (exports.HttpMethod = HttpMethod = {})); class MethodGenerator { responses; spec; url; operation; bodyParameters; descriptions; formattedUrl; imports; requiresBearerAuthorization; method; needsDataObj; normalizedUrl; parameterMethod; pathParameters; queryParameters; returnType; constructor(url, method, operation, spec) { this.url = url; this.operation = operation; this.method = method; this.normalizedUrl = StringUtil.normalizeUrl(url); this.formattedUrl = `'${url}'`; this.spec = spec; this.responses = operation.responses; this.bodyParameters = []; this.imports = []; this.pathParameters = []; this.queryParameters = []; this.buildParameters(this.operation.parameters); this.descriptions = this.buildDescriptions(); const parameterMatch = url.match(/\{([^}]+)\}/); if (parameterMatch) { if (!this.pathParameters.length) { this.pathParameters.push({ name: parameterMatch[1], type: InterfaceGenerator_1.TypeScriptType.ANY, }); } this.formattedUrl = this.formattedUrl.replace(/\{/g, '${').replace(/'/g, '`'); } const postFix = parameterMatch ? `By${StringUtil.camelCase(parameterMatch.splice(1), true)}` : 'All'; this.parameterMethod = this.operation.operationId || `${this.method}${postFix}`; if (this.includesSuccessResponse(this.responses)) { this.returnType = this.buildResponseSchema(); } else { this.returnType = 'void'; } this.needsDataObj = !(this.method === HttpMethod.PATCH || this.method === HttpMethod.POST || this.method === HttpMethod.PUT); this.requiresBearerAuthorization = !!this.operation.security && this.operation.security.some(obj => Object.keys(obj).includes('Bearer')); } includesSuccessResponse(responses) { for (const [successCode, response] of Object.entries(responses)) { if (successCode.startsWith('2') && response.hasOwnProperty('schema')) { return true; } } return false; } buildDescriptions() { if (this.operation.parameters) { const parameters = this.operation.parameters.filter(parameter => !this.parameterIsReference(parameter)); const extractDescription = (parameter) => { if (parameter.description) { return { name: parameter.name, text: StringUtil.addStarsToNewline(parameter.description), }; } return; }; return parameters.map(extractDescription).filter(Boolean); } return undefined; } parameterIsReference(parameter) { return !!parameter.$ref; } getSchemaFromRef(ref) { if (!ref.startsWith('#/definitions')) { console.warn(`Invalid reference "${ref}".`); return; } if (!this.spec.definitions) { console.warn(`No reference found for "${ref}".`); return; } const definitionString = ref.replace('#/definitions/', ''); const definition = this.spec.definitions[definitionString]; return definition?.$ref ? this.getSchemaFromRef(definition?.$ref) : definition; } buildParameters(parameters) { if (!parameters || !parameters.length) { return; } for (const parameter of parameters) { if (this.parameterIsReference(parameter)) { const definition = this.getSchemaFromRef(parameter.$ref); if (definition) { return this.buildParameters([definition]); } return; } if (parameter.in === 'path' && parameter.type) { const type = this.buildSimpleType(parameter.type); this.pathParameters.push({ name: parameter.name, type, }); } if (parameter.in === 'body') { let type = InterfaceGenerator_1.TypeScriptType.EMPTY_OBJECT; if (parameter.schema) { const builtInterface = InterfaceGenerator_1.InterfaceGenerator.buildInterface(this.spec, parameter.schema, parameter.name); type = builtInterface.type; for (const interfaceImport of builtInterface.imports) { if (!this.imports.includes(interfaceImport)) { this.imports.push(interfaceImport); } } } this.bodyParameters.push({ name: parameter.name, required: parameter.required, type, }); } if (parameter.in === 'query' && parameter.type) { const type = this.buildSimpleType(parameter.type); this.queryParameters.push({ name: parameter.name, required: parameter.required, type, }); } } } buildSimpleType(schemaType) { switch (schemaType.toLowerCase()) { case InterfaceGenerator_1.SwaggerType.STRING: { return InterfaceGenerator_1.TypeScriptType.STRING; } case InterfaceGenerator_1.SwaggerType.BOOLEAN: { return InterfaceGenerator_1.TypeScriptType.BOOLEAN; } case InterfaceGenerator_1.SwaggerType.NUMBER: case InterfaceGenerator_1.SwaggerType.INTEGER: { return InterfaceGenerator_1.TypeScriptType.NUMBER; } default: { return InterfaceGenerator_1.TypeScriptType.EMPTY_OBJECT; } } } buildResponseSchema() { const response200 = this.responses['200']; const response201 = this.responses['201']; let response200Schema = ''; if (response200 && response200.schema) { const response200Interface = InterfaceGenerator_1.InterfaceGenerator.buildInterface(this.spec, response200.schema, `${this.url}/${this.method}/200`); response200Schema = response200Interface.type; this.imports.push(...response200Interface.imports); } let response201Schema = ''; if (response201 && response201.schema) { const response201Interface = InterfaceGenerator_1.InterfaceGenerator.buildInterface(this.spec, response201.schema, `${this.url}/${this.method}/201`); response201Schema = response201Interface.type; this.imports.push(...response201Interface.imports); } const responseSchema = response200Schema && response201Schema ? `${response200Schema} | ${response201Schema}` : response200Schema || response201Schema; if (!responseSchema) { console.warn(`No schema for code 200/201 on URL "${this.url}" or schema has no definitions.`); return InterfaceGenerator_1.TypeScriptType.EMPTY_OBJECT; } return responseSchema; } } exports.MethodGenerator = MethodGenerator; //# sourceMappingURL=MethodGenerator.js.map