UNPKG

unleash-server

Version:

Unleash is an enterprise ready feature flag service. It provides different strategies for handling feature flags.

68 lines (66 loc) 2.84 kB
import openapi from '@wesleytodd/openapi'; import { createOpenApiSchema, removeJsonSchemaProps, } from '../openapi/index.js'; import { validateSchema } from '../openapi/validate.js'; export class OpenApiService { constructor(config) { this.config = config; this.flagResolver = config.flagResolver; this.logger = config.getLogger('openapi-service.ts'); this.api = openapi(this.docsPath(), createOpenApiSchema(config.server), { coerce: true, extendRefs: true, basePath: config.server.baseUriPath, }); } validPath(op) { const { beta, enterpriseOnly, ...rest } = op; const { baseUriPath = '' } = this.config.server ?? {}; const openapiStaticAssets = `${baseUriPath}/openapi-static`; const betaBadge = beta ? `![Beta](${openapiStaticAssets}/Beta.svg) This is a beta endpoint and it may change or be removed in the future. ` : ''; const enterpriseBadge = enterpriseOnly ? `![Unleash Enterprise](${openapiStaticAssets}/Enterprise.svg) **Enterprise feature** ` : ''; const failDeprecated = (op.deprecated ?? false) && process.env.NODE_ENV === 'development'; if (failDeprecated) { return (req, res, next) => { this.logger.warn(`Deprecated endpoint: ${op.operationId} at ${req.path}`); return res.status(410).json({ message: `The endpoint ${op.operationId} at ${req.path} is deprecated and should not be used.`, }); }; } return this.api.validPath({ ...rest, description: `${enterpriseBadge}${betaBadge}${op.description}`.replaceAll(/\n\s*/g, '\n\n'), }); } useDocs(app) { app.use(this.api); app.use(this.docsPath(), this.api.swaggerui()); } docsPath() { const { baseUriPath = '' } = this.config.server ?? {}; return `${baseUriPath}/docs/openapi`; } registerCustomSchemas(schemas) { Object.entries(schemas).forEach(([name, schema]) => { this.api.schema(name, removeJsonSchemaProps(schema)); }); } respondWithValidation(status, res, schema, data, headers = {}) { const errors = validateSchema(schema, data); if (errors) { this.logger.debug(`Invalid response for ${res.req?.originalUrl || ''}:`, errors); if (this.flagResolver.isEnabled('strictSchemaValidation')) { throw new Error(JSON.stringify(errors, null, 4)); } } Object.entries(headers).forEach(([header, value]) => res.header(header, value)); res.status(status).json(data); } } //# sourceMappingURL=openapi-service.js.map