powr-sdk-api
Version:
Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.
117 lines (113 loc) • 3.31 kB
JavaScript
;
/**
* Swagger configuration for Express applications
*/
const swaggerJsdoc = require('swagger-jsdoc');
const createSwaggerSpec = (options = {}) => {
const defaultOptions = {
definition: {
openapi: '3.0.0',
info: {
title: options.title || 'API Documentation',
version: options.version || '1.0.0',
description: options.description || 'API documentation'
},
servers: [{
url: options.serverUrl || 'http://localhost:3000',
description: process.env.NODE_ENV === 'production' ? 'Production server' : 'Development server'
}],
components: {
schemas: {
Error: {
type: 'object',
properties: {
success: {
type: 'boolean',
example: false
},
message: {
type: 'string',
example: 'Error message'
},
details: {
type: 'object',
example: null
}
}
},
Success: {
type: 'object',
properties: {
success: {
type: 'boolean',
example: true
},
message: {
type: 'string',
example: 'Operation successful'
},
data: {
type: 'object',
example: null
}
}
}
},
responses: {
UnauthorizedError: {
description: 'Access token is missing or invalid',
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/Error'
}
}
}
},
NotFoundError: {
description: 'The specified resource was not found',
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/Error'
}
}
}
}
}
}
},
apis: options.apis || ['./routes/*.js'] // Path to the API routes
};
const swaggerSpec = swaggerJsdoc(defaultOptions);
// Remove sensitive information in production
if (process.env.NODE_ENV === 'production') {
// Remove server URLs in production
swaggerSpec.servers = [];
// Remove any sensitive examples or descriptions
if (swaggerSpec.paths) {
Object.keys(swaggerSpec.paths).forEach(path => {
Object.keys(swaggerSpec.paths[path]).forEach(method => {
const operation = swaggerSpec.paths[path][method];
if (operation.responses) {
Object.keys(operation.responses).forEach(statusCode => {
const response = operation.responses[statusCode];
if (response.content) {
Object.keys(response.content).forEach(contentType => {
const content = response.content[contentType];
if (content.examples) {
delete content.examples;
}
});
}
});
}
});
});
}
}
return swaggerSpec;
};
module.exports = {
createSwaggerSpec
};