// Copyright Abridged, Inc. 2021,2024. All Rights Reserved. // Node module: @collabland/sdk // This file is licensed under the MIT License. // License text available at https://opensource.org/license/mit/ import fetch from 'cross-fetch'; import camelCase from 'lodash.camelcase'; import type { OpenAPIObject, OperationObject, ParameterObject, RequestBodyObject, } from 'openapi3-ts'; import type {RestDataSource} from '../datasources/index.js'; import type {AnyObject} from '../types.js'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore let SwaggerClient = await import('swagger-client'); // FIXME: A workaround for webpack generated code that uses `swagger-client` // as an ES module if (typeof SwaggerClient === 'object') { SwaggerClient = SwaggerClient.default; } /** * Initialize a data source * @param {DataSource} dataSource The dataSource object */ export function initialize(dataSource: RestDataSource) { const settings = dataSource.settings || {}; const connector = new OpenApiConnector(settings); return connector.connect(); } /** * The OpenApiConnector constructor * @param {Object} settings The connector settings * @constructor */ export class OpenApiConnector { readonly url: string; private spec: OpenAPIObject; private client: AnyObject; private serviceProxies?: AnyObject; constructor(readonly settings: AnyObject = {}) { if (settings.transformResponse === true) { settings.transformResponse = transformResponse; } this.url = settings.url; this.spec = settings.spec; /* if (debug.enabled) { debug('Settings: %j', settings); } */ } /** * Parse swagger specification, setup client and export service proxies */ async connect() { const req = { url: this.url, spec: this.spec, userFetch: this.settings.userFetch ?? fetch, authorizations: this.settings.authorizations ?? {}, }; this.client = await SwaggerClient(req); /* if (debug.enabled) { debug('swagger loaded: %s', this.spec, this.client); } */ return this.setupServiceProxies(); } async setupServiceProxies() { if (this.serviceProxies != null) { return this.serviceProxies; } this.serviceProxies = {}; const getMethodNames: typeof mapToMethods = this.settings.mapToMethods || mapToMethods; const existingNames = Object.keys(this.serviceProxies); // eslint-disable-next-line @typescript-eslint/no-explicit-any const apis: Record = {}; for (const tag in this.client.apis) { const operationsForTag = this.client.apis[tag]; apis[tag] = {}; for (const operationId in operationsForTag) { const opSpec = this.getOperationSpec(operationId); const method = operationsForTag[operationId]; if (opSpec.operationId == null) { opSpec.operationId = operationId; } let methodNames = getMethodNames(tag, opSpec, existingNames); methodNames = normalizeMethods(methodNames); /* if (debug.enabled) { debug( 'Adding methods for operation %s as %s', operationId, methodNames, ); } */ const swaggerMethod = this.createWrapper(method, opSpec); // const swaggerMethod = wrapper.bind(operationsForTag); for (const m of methodNames) { this.serviceProxies[m] = swaggerMethod; } let methodNamesWithinTag = getMethodNames(undefined, opSpec); methodNamesWithinTag = normalizeMethods(methodNamesWithinTag); /* if (debug.enabled) { debug( 'Adding apis[%s] for operation %s as %s', tag, operationId, methodNamesWithinTag, ); } */ for (const m of methodNamesWithinTag) { // Set apis.TodoController.findTodos apis[tag][m] = swaggerMethod; } } // Expose apis this.serviceProxies.apis = apis; } this.serviceProxies.execute = ( operationId: string, parameters: unknown[], options: object, ) => { const request = { operationId, parameters, }; Object.assign(request, options); return this.client.execute(request); }; return this.serviceProxies; } createWrapper( method: (...args: unknown[]) => Promise, operation: OperationObject, ) { const options = this.settings; if (options.transformResponse === true) { options.transformResponse = transformResponse; } const opParams: ParameterObject[] = (operation.parameters as ParameterObject[]) ?? []; // Arg names without body const argNames = opParams.map(p => p.name); if (operation.requestBody) { argNames.push('requestBody'); } return (...args: unknown[]) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let params: any = args[0] || {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any let opts: any = args[1] || {}; if (options.positional) { params = {}; // We allow an optional `options` argument for // https://github.com/swagger-api/swagger-js/blob/master/docs/usage/try-it-out-executor.md // https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md // Especially `requestContentType`, `responseContentType`, `authorizations` opts = {...(args[argNames.length] as object)}; for (let i = 0; i < argNames.length; i++) { const name = argNames[i]; if (!name || (i === argNames.length - 1 && name === 'requestBody')) continue; params[name] = args[i]; } // `node-fetch` does not support JSON object directly. We have to // call `JSON.stringify` to force it. if (operation.requestBody) { opts.requestBody = args[argNames.length - 1]; if (typeof opts.requestBody != null) { if ( opts.requestContentType === 'application/json' || (operation.requestBody as RequestBodyObject).content?.[ 'application/json' ] ) { opts.requestBody = JSON.stringify(opts.requestBody); } } } } const resolve = (res: unknown) => { if (typeof options.transformResponse !== 'function') return res; return options.transformResponse(res, operation); }; return method(params, opts).then(resolve); }; } /** * Match the method name from SwaggerClient interfaces to corresponding * Operation spec object */ getOperationSpec(methodName: string) { const spec = this.client.spec ?? this.spec; for (const p in spec.paths) { for (const v in spec.paths[p]) { const op = spec.paths[p][v]; const id = SwaggerClient.helpers.opId(op, p, v); if (id === methodName) return op; } } } } /** * Get the method name for an operation * @param {string} tag - The tag. It will be undefined for tagged interfaces. * @param {object} operationSpec - Operation spec * @param {string[]} existingNames - Optional array to track used names * * @returns A method name or an array of method names. Return undefined to * skip the operation. */ function mapToMethods( tag: string | undefined, operationSpec: OperationObject, existingNames: string[] = [], ) { const methods: string[] = []; const addMethods = (...names: string[]) => { for (const name of names) { if (!name) break; if (methods.includes(name)) break; methods.push(name); } }; const opName = operationSpec['x-operation-name']; const opId = operationSpec.operationId; // Add simple names addMethods(opName, camelCase(opName)); addMethods(opId!, camelCase(opId)); // Add full names if (tag && opName) { const name = `${tag}_${opName}`; addMethods(name, camelCase(name)); } if (tag && opId) { const name = `${tag}_${opId}`; addMethods(name, camelCase(opId)); } if (existingNames == null) return methods; return methods.filter(m => { if (existingNames.includes(m)) return false; existingNames.push(m); return true; }); } function normalizeMethods(methodNames: string | string[]) { if (typeof methodNames === 'string') { methodNames = [methodNames]; } if (!Array.isArray(methodNames)) { methodNames = []; } return methodNames; } async function transformResponse( res: Response, operationSpec: OperationObject, ) { if (res.status < 400) { return res.body; } const err = new Error(`${res.status} ${res.statusText}`); const body = await res.json(); const errObj = err as unknown as Record; errObj.statusCode = res.status; errObj.details = body; throw err; }