sofa-api
Version:
Create REST APIs with GraphQL
62 lines (61 loc) • 2.06 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAPI = OpenAPI;
const graphql_1 = require("graphql");
const types_js_1 = require("./types.js");
const operations_js_1 = require("./operations.js");
const utils_js_1 = require("./utils.js");
function OpenAPI({ schema, info, servers, components, security, tags, customScalars = {}, }) {
const types = schema.getTypeMap();
const swagger = {
openapi: '3.0.0',
info,
servers,
tags: [],
paths: {},
components: {
schemas: {},
},
};
for (const typeName in types) {
const type = types[typeName];
if (((0, graphql_1.isObjectType)(type) || (0, graphql_1.isInputObjectType)(type)) &&
!(0, graphql_1.isIntrospectionType)(type)) {
swagger.components.schemas[typeName] = (0, types_js_1.buildSchemaObjectFromType)(type, {
customScalars,
});
}
}
if (components) {
swagger.components = { ...components, ...swagger.components };
}
if (security) {
swagger.security = security;
}
if (tags) {
swagger.tags = tags;
}
return {
addRoute(info, config) {
const basePath = config?.basePath || '';
const path = basePath + (0, utils_js_1.normalizePathParamForOpenAPI)(info.path);
if (!swagger.paths[path]) {
swagger.paths[path] = {};
}
const pathsObj = swagger.paths[path];
pathsObj[info.method.toLowerCase()] =
(0, operations_js_1.buildPathFromOperation)({
url: path,
operation: info.document,
schema,
useRequestBody: ['POST', 'PUT', 'PATCH'].includes(info.method),
tags: info.tags || [],
description: info.description || '',
customScalars,
});
},
get() {
return swagger;
},
};
}