### With Response Examples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/responses-transformers.md Shows a GET endpoint for listing users, including a 200 OK success response with a detailed example. ```APIDOC ## GET /api/users ### Description Retrieves a list of all users. ### Method GET ### Endpoint /api/users ### Response #### Success Response (200) - **array** - Users list ### Response Example #### Success Response (200) [ { "id": "1", "name": "John", "email": "john@example.com" }, { "id": "2", "name": "Jane", "email": "jane@example.com" } ] ``` -------------------------------- ### Response with Examples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/responses-transformers.md Defines a GET request that returns a list of users and includes an example of the 200 OK response body. ```javascript /** * GET /api/users * @return {array} 200 - Users list * @example response - 200 * [ * { * "id": "1", * "name": "John", * "email": "john@example.com" * }, * { * "id": "2", * "name": "Jane", * "email": "jane@example.com" * } * ] */ app.get('/api/users', handler); ``` -------------------------------- ### Example GET /api/users Endpoint Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Demonstrates JSDoc tags for a GET request to /api/users, including query and header parameters. ```javascript /** * GET /api/users * @param {string} search.query - Search term * @param {string} role.query - Filter by role - enum:admin,user,guest * @param {integer} page.query - Page number * @param {integer} limit.query - Items per page * @param {string} X-Request-ID.header.required - Request tracking ID * @return {array} 200 - Users list */ app.get('/api/users', getUsers); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/CONTRIBUTING.md Run this command to install all necessary dependencies for developing the package. ```bash npm install ``` -------------------------------- ### OpenAPI Server Configuration Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/basic-info-security.md An example demonstrating how to configure servers with URL, description, and variables for different environments and ports. ```javascript const options = { servers: [ { url: 'https://{environment}.example.com:{port}', description: 'API server', variables: { environment: { default: 'api', enum: ['api', 'staging', 'beta'], description: 'Environment name', }, port: { default: '443', enum: ['443', '8443'], description: 'Server port', }, }, }, ], }; ``` -------------------------------- ### Run Specific Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/examples/README.md Executes a specific example by providing the folder and file name. For instance, 'npm run responses:simple' will run the simple responses example. After running, you can access the generated API documentation at http://localhost:3000/api-docs. ```bash npm run : npm run responses:simple ``` -------------------------------- ### @example Tag Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/jsdoc-syntax-reference.md Illustrates the `@example` tag for providing request and response examples, including multiple examples for different scenarios. ```APIDOC ### @example **Usage:** Provide usage examples **Request examples:** ```javascript /** * @example request - Simple request * { * "name": "John", * "email": "john@example.com" * } * * @example request - With additional fields * { * "name": "John", * "email": "john@example.com", * "role": "admin" * } */ ``` **Response examples:** ```javascript /** * @example response - 200 Success response * { * "id": "123", * "name": "John", * "email": "john@example.com" * } * * @example response - 404 Not found * { * "code": "NOT_FOUND", * "message": "User not found" * } */ ``` ``` -------------------------------- ### checkExamples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Converts an array of example objects into the OpenAPI examples format, returning undefined if the array is empty. ```APIDOC ## checkExamples ### Description Converts example array into OpenAPI examples format if examples exist. Returns undefined for empty arrays to omit from final object. ### Signature ```javascript function checkExamples(examples) -> Object or undefined ``` ### Parameters - **examples** (Array) - Required - Array of example objects ### Returns **Type:** `Object or undefined` Formatted examples object or undefined if array is empty. ``` -------------------------------- ### Install Dependencies Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/examples/ts-example/README.md Installs the necessary project dependencies using npm. ```bash npm i ``` -------------------------------- ### User Response Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/responses-transformers.md Defines a GET endpoint for retrieving user details with a concrete success response example. ```APIDOC ## GET /api/users/{id} ### Description Retrieves the details of a specific user. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - User ID ### Response #### Success Response (200) - **User** - User details ### Request Example ```json { "id": "123", "name": "John Doe", "email": "john@example.com", "active": true } ``` ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/configuration.md This example demonstrates a comprehensive configuration for express-jsdoc-swagger, including API metadata, server details, security schemes, and UI options. It shows how to initialize the swagger module with custom settings. ```javascript const expressJSDocSwagger = require('express-jsdoc-swagger'); const app = require('express')(); const options = { // File Configuration baseDir: __dirname, filesPattern: [ './api/**/*.js', './routes/**/*.js', ], // API Metadata info: { version: '2.1.0', title: 'Complete API Example', description: 'A fully configured API with all options', termsOfService: 'https://example.com/terms', contact: { name: 'API Support Team', url: 'https://example.com/support', email: 'api@example.com', }, license: { name: 'Apache-2.0', url: 'https://www.apache.org/licenses/LICENSE-2.0.html', }, }, // Server Configuration servers: [ { url: 'http://localhost:3000', description: 'Development server', }, { url: 'https://api.example.com', description: 'Production server', }, ], // Security Configuration security: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', }, apiKeyAuth: { type: 'apiKey', in: 'header', name: 'X-API-Key', }, }, // UI Configuration swaggerUIPath: '/api-docs', exposeSwaggerUI: true, exposeApiDocs: true, apiDocsPath: '/v3/api-docs', notRequiredAsNullable: false, multiple: false, swaggerUiOptions: { defaultModelsExpandDepth: 1, showRequestHeaders: true, }, }; expressJSDocSwagger(app)(options); app.listen(3000, () => { console.log('API available at http://localhost:3000'); console.log('Documentation at http://localhost:3000/api-docs'); console.log('OpenAPI spec at http://localhost:3000/v3/api-docs'); }); ``` -------------------------------- ### GET /api/v1/albums Endpoint with Response Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/README.md Defines a GET endpoint for '/api/v1/albums' that includes a detailed example of the success response body. ```javascript /** * GET /api/v1/albums * @summary This is the summary of the endpoint * @tags album * @return {array} 200 - success response - application/json * @example response - 200 - success response example * [ * { * "title": "Bury the light", * "artist": "Casey Edwards ft. Victor Borba", * "year": 2020 * } * ] */ app.get('/api/v1/albums', (req, res) => ( res.json([{ title: 'track 1', }]) )); ``` -------------------------------- ### Example GET /api/users/{id} Endpoint Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Demonstrates JSDoc tags for a GET request to /api/users/{id}, including a required path parameter. ```javascript /** * GET /api/users/{id} * @param {string} id.path.required - User ID * @return {User} 200 - User details */ app.get('/api/users/:id', getUser); ``` -------------------------------- ### Install express-jsdoc-swagger Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/README.md Install the express-jsdoc-swagger library using npm. ```bash npm install express-jsdoc-swagger ``` -------------------------------- ### JSDoc @example Tag for Requests Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/jsdoc-syntax-reference.md Provide example request bodies using the @example tag with the 'request' keyword. Supports multiple examples with different data. ```javascript /** * @example request - Simple request * { * "name": "John", * "email": "john@example.com" * } * * @example request - With additional fields * { * "name": "John", * "email": "john@example.com", * "role": "admin" * } */ ``` -------------------------------- ### Define a 200 OK Response Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/responses-transformers.md Use the `@example response` tag to provide a concrete JSON example for a successful API response. This example will be displayed in the Swagger UI and OpenAPI specification. ```javascript /** * GET /api/users/{id} * @param {string} id.path.required - User ID * @return {User} 200 - User details * @example response - 200 * { * "id": "123", * "name": "John Doe", * "email": "john@example.com", * "active": true * } */ ``` -------------------------------- ### Example Transformation for formatExamples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/responses-transformers.md Shows the input and output structure for the `formatExamples` function, demonstrating how flat example arrays are converted into a nested object organized by status code. ```javascript // Input [ { status: '200', summary: 'Success', value: {...} }, { status: '200', summary: 'Alternative', value: {...} }, { status: '400', summary: 'Validation error', value: {...} }, ] // Output { '200': { example1: { summary: 'Success', value: {...} }, example2: { summary: 'Alternative', value: {...} }, }, '400': { example1: { summary: 'Validation error', value: {...} }, }, } ``` -------------------------------- ### Convert Example Array to OpenAPI Format Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Converts an array of example objects into the OpenAPI examples format. Returns undefined if the input array is empty, which omits the examples from the final object. ```javascript function checkExamples(examples) -> Object or undefined ``` -------------------------------- ### JSDoc @example Tag for Responses Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/jsdoc-syntax-reference.md Provide example response bodies using the @example tag with the 'response' keyword, specifying the status code and a description. ```javascript /** * @example response - 200 Success response * { * "id": "123", * "name": "John", * "email": "john@example.com" * } * * @example response - 404 Not found * { * "code": "NOT_FOUND", * "message": "User not found" * } */ ``` -------------------------------- ### Multiple Request Body Examples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Demonstrates defining multiple request body examples for a single endpoint, showcasing different message formats. ```javascript /** * POST /api/messages * @param {Message} request.body.required - Message to send * @return {Message} 201 - Message sent * @example request - Simple message * { * "text": "Hello" * } * @example request - Message with attachments * { * "text": "Check this out", * "attachments": ["file1.pdf", "image.jpg"] * } * @example response - 201 * { * "id": "msg_123", * "text": "Hello", * "sentAt": "2024-01-15T10:30:00Z" * } */ ``` -------------------------------- ### Basic Express.js App with express-jsdoc-swagger Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/README.md This snippet shows a basic Express.js application setup with express-jsdoc-swagger. It includes configuration options for API documentation and a sample GET endpoint. ```javascript // index.js file const express = require('express'); const expressJSDocSwagger = require('express-jsdoc-swagger'); const options = { info: { version: '1.0.0', title: 'Albums store', license: { name: 'MIT', }, }, security: { BasicAuth: { type: 'http', scheme: 'basic', }, }, // Base directory which we use to locate your JSDOC files baseDir: __dirname, // Glob pattern to find your jsdoc files (multiple patterns can be added in an array) filesPattern: './**/*.js', // URL where SwaggerUI will be rendered swaggerUIPath: '/api-docs', // Expose OpenAPI UI exposeSwaggerUI: true, // Expose Open API JSON Docs documentation in `apiDocsPath` path. exposeApiDocs: false, // Open API JSON Docs endpoint. apiDocsPath: '/v3/api-docs', // Set non-required fields as nullable by default notRequiredAsNullable: false, // You can customize your UI options. // you can extend swagger-ui-express config. You can checkout an example of this // in the `example/configuration/swaggerOptions.js` swaggerUiOptions: {}, // multiple option in case you want more that one instance multiple: true, }; const app = express(); const PORT = 3000; expressJSDocSwagger(app)(options); /** * GET /api/v1 * @summary This is the summary of the endpoint * @return {object} 200 - success response */ app.get('/api/v1', (req, res) => res.json({ success: true, })); app.listen(PORT, () => console.log(`Example app listening at http://localhost:${PORT}`)); ``` -------------------------------- ### GET /api/v1 Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/README.md This endpoint serves as a basic example of an API operation documented using JSDoc tags. It returns a success response. ```APIDOC ## GET /api/v1 ### Description This is the summary of the endpoint. ### Method GET ### Endpoint /api/v1 ### Response #### Success Response (200) - success (boolean) - Indicates if the operation was successful. ``` -------------------------------- ### Header Parameters Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Defines header parameters for authentication and custom headers. ```javascript /** * GET /api/secure * @param {string} Authorization.header.required - Bearer token * @param {string} X-Custom-Header.header - Custom header value * @return {object} 200 - Response */ ``` -------------------------------- ### Multiple Body Examples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Demonstrates an endpoint that can accept different structures for its JSON request body, providing multiple examples. ```APIDOC ## POST /api/messages ### Description Sends a message, which can optionally include attachments. ### Method POST ### Endpoint /api/messages ### Parameters #### Request Body - **Message** (object) - Required - The message content - **text** (string) - Required - The main text of the message - **attachments** (array) - Optional - A list of file names for attachments ### Request Example - Simple message ```json { "text": "Hello" } ``` ### Request Example - Message with attachments ```json { "text": "Check this out", "attachments": ["file1.pdf", "image.jpg"] } ``` ### Response #### Success Response (201) - **Message** (object) - The sent message confirmation - **id** (string) - Unique identifier for the message - **text** (string) - The text of the sent message - **sentAt** (string) - ISO 8601 timestamp of when the message was sent #### Response Example ```json { "id": "msg_123", "text": "Hello", "sentAt": "2024-01-15T10:30:00Z" } ``` ``` -------------------------------- ### Search Products Endpoint Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/tutorial-endpoints.md Defines a GET endpoint for searching products with query parameters for search terms, category, price range, brands, sorting, and pagination. Includes an example response. ```javascript /** * Search products * @summary Search products * @tags products - Product catalog * @param {string} q.query.required - Search query * @param {string} category.query - Category filter * @param {number} minPrice.query - Minimum price * @param {number} maxPrice.query - Maximum price * @param {array} brands.query - Filter by brands - explode * @param {string} sort.query - Sort field - enum:relevance,price,rating,newest * @param {integer} page.query - Page number * @param {integer} limit.query - Results per page * @return {SearchResults} 200 - Search results * @example response - 200 * { * "query": "laptop", * "results": [ * { * "id": "product_123", * "name": "Laptop Model X", * "price": 999.99, * "rating": 4.5 * } * ], * "total": 42, * "page": 1 * } */ app.get('/api/products/search', searchProducts); /** * @typedef {object} SearchResults * @property {string} query.required - Search query * @property {array} results.required - Matching products * @property {number} total.required - Total matches * @property {number} page.required - Current page */ ``` -------------------------------- ### Query Parameters Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Demonstrates how to define query parameters for an API endpoint, including their types, whether they are required, and descriptions. ```APIDOC ## GET /api/products ### Description Retrieves a list of products with filtering, sorting, and pagination options. ### Method GET ### Endpoint /api/products ### Parameters #### Query Parameters - **category** (string) - Optional - Product category - **search** (string) - Optional - Search keywords - **minPrice** (integer) - Optional - Minimum price - **maxPrice** (integer) - Optional - Maximum price - **sortBy** (string) - Optional - Sort field - enum:name,price,date - **order** (string) - Optional - Sort order - enum:asc,desc - **page** (integer) - Optional - Page number - **limit** (integer) - Optional - Results per page ### Response #### Success Response (200) - **Product** (array) - Product list ``` -------------------------------- ### Path Parameters Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Defines path parameters for identifying specific resources in a URL. ```javascript /** * DELETE /api/users/{userId}/posts/{postId} * @param {string} userId.path.required - User identifier * @param {string} postId.path.required - Post identifier * @return {object} 204 - Deleted successfully */ ``` -------------------------------- ### Example with Multiple Tags and Descriptions Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/basic-info-security.md Demonstrates how to apply multiple tags with descriptions to different API endpoints. This helps in organizing endpoints by functionality and access level. ```javascript /** * GET /api/users * @summary List all users * @tags users - User management operations * @tags public - Public endpoints * @return {array} 200 - Users list */ app.get('/api/users', listUsers); /** * POST /api/users * @summary Create new user * @tags users - User management operations * @tags admin - Admin only operations * @return {User} 201 - User created * @security adminAuth */ app.post('/api/users', createUser); /** * GET /api/posts * @summary List posts * @tags posts - Blog post management * @tags public - Public endpoints * @return {array} 200 - Posts list */ app.get('/api/posts', listPosts); ``` -------------------------------- ### Install express-oas-validator Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/README.md Install the express-oas-validator package using npm. This is the first step to enable API validation. ```bash npm install --save express-oas-validator ``` -------------------------------- ### Basic Event Listening Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/event-emitter.md Demonstrates how to listen for 'error', 'process', and 'finish' events from the Event Emitter instance. This is useful for logging and reacting to the Swagger generation lifecycle. ```javascript const expressJSDocSwagger = require('express-jsdoc-swagger'); const app = require('express')(); const instance = expressJSDocSwagger(app)({ info: { version: '1.0.0', title: 'My API', }, baseDir: __dirname, filesPattern: './**/*.js', }); // Listen for errors instance.on('error', (error) => { console.error('Swagger generation error:', error); process.exit(1); }); // Listen for processing events instance.on('process', ({ entity, swaggerObject }) => { console.log(`Processing: ${entity}`); }); // Listen for completion instance.on('finish', (swaggerObject, methods) => { console.log('Swagger generation complete'); console.log('Paths:', Object.keys(swaggerObject.paths || {})); console.log('Components:', Object.keys(swaggerObject.components?.schemas || {})); }); ``` -------------------------------- ### Header Parameters Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Shows how to define header parameters, including required ones like authorization tokens and optional custom headers. ```APIDOC ## GET /api/secure ### Description Accesses a secure resource that requires authentication and custom headers. ### Method GET ### Endpoint /api/secure ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token - **X-Custom-Header** (string) - Optional - Custom header value ### Response #### Success Response (200) - **(object)** - Response ``` -------------------------------- ### JSON Request Body Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Defines a JSON request body for creating a new user, including example request and response payloads. ```javascript /** * POST /api/users * @param {User} request.body.required - User information * @return {User} 201 - Created user * @example request * { * "name": "John Doe", * "email": "john@example.com", * "role": "user" * } * @example response - 201 * { * "id": "123", * "name": "John Doe", * "email": "john@example.com", * "role": "user", * "createdAt": "2024-01-15T10:30:00Z" * } */ ``` -------------------------------- ### formatExamples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/responses-transformers.md Converts a flat array of example objects into a nested structure organized by status code. It also generates unique example names (e.g., example1, example2) for each status code. ```APIDOC ## formatExamples ### Description Converts flat example array into nested structure organized by status code. Generates unique example names (example1, example2, etc.). ### Signature ```javascript function formatExamples(exampleValues = []) -> Object ``` ### Parameters #### Parameters - **exampleValues** (Array) - No - Array of example objects with status property ### Returns **Type:** `Object` Object mapping status codes to example maps. ### Example Transformation ```javascript // Input [ { status: '200', summary: 'Success', value: {...} }, { status: '200', summary: 'Alternative', value: {...} }, { status: '400', summary: 'Validation error', value: {...} }, ] // Output { '200': { example1: { summary: 'Success', value: {...} }, example2: { summary: 'Alternative', value: {...} }, }, '400': { example1: { summary: 'Validation error', value: {...} }, }, } ``` ``` -------------------------------- ### Execute Commands Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/examples/ts-example/README.md Provides commands for executing the TypeScript example in different modes: development, build, and production. ```bash // Execute dev mode npm run dev ``` ```bash // Build TS file in build/simple.js npm run tsc:build ``` ```bash // Execute ts-node app npm run start ``` ```bash // execute build app npm run start:prod ``` -------------------------------- ### Path Parameters Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Illustrates the definition of path parameters, which are essential parts of the URL path for identifying specific resources. ```APIDOC ## DELETE /api/users/{userId}/posts/{postId} ### Description Deletes a specific post belonging to a user. ### Method DELETE ### Endpoint /api/users/{userId}/posts/{postId} ### Parameters #### Path Parameters - **userId** (string) - Required - User identifier - **postId** (string) - Required - Post identifier ### Response #### Success Response (204) - **(empty)** - Deleted successfully ``` -------------------------------- ### Query Parameters Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Defines query parameters for filtering and pagination of product data. ```javascript /** * GET /api/products * @param {string} category.query - Product category * @param {string} search.query - Search keywords * @param {integer} minPrice.query - Minimum price * @param {integer} maxPrice.query - Maximum price * @param {string} sortBy.query - Sort field - enum:name,price,date * @param {string} order.query - Sort order - enum:asc,desc * @param {integer} page.query - Page number * @param {integer} limit.query - Results per page * @return {array} 200 - Product list */ ``` -------------------------------- ### Format Properties Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/components-transformers.md Demonstrates how to use the `formatProperties` function to transform an array of property tag objects into a structured object suitable for OpenAPI schema definitions. This example shows the conversion of basic types, enums, and array types. ```javascript const properties = [ { name: 'userId.required', type: { name: 'string' }, description: 'User unique identifier', }, { name: 'status', type: { name: 'string' }, description: 'Status - enum:active,inactive,pending', }, { name: 'tags', type: { name: 'array', expression: { name: 'array' }, applications: [{ name: 'string' }], }, description: 'Array of tags', }, ]; const formatted = formatProperties(properties); // Output: // { // userId: { type: 'string', description: 'User unique identifier' }, // status: { type: 'string', enum: ['active', 'inactive', 'pending'] }, // tags: { type: 'array', items: { type: 'string' } }, // } ``` -------------------------------- ### Example: Define a User Type with @typedef Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/jsdoc-syntax-reference.md An example demonstrating how to define a 'User' object type using the @typedef tag, specifying required properties like id, name, and email. ```javascript /** * A user account * @typedef {object} User * @property {string} id.required - User ID * @property {string} name.required - Full name * @property {string} email.required - Email address */ ``` -------------------------------- ### List Users with Pagination (GET) Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/tutorial-endpoints.md Document a GET endpoint for listing users with pagination and filtering capabilities. Defines the structure for paginated responses. ```javascript /** * List all users with pagination * @summary List users * @tags users - User management * @param {integer} page.query - Page number (1-based) - json:{"minimum":1} * @param {integer} pageSize.query - Items per page - json:{"minimum":1,"maximum":100} * @param {string} search.query - Search by name or email * @param {string} role.query - Filter by role - enum:admin,moderator,user * @param {string} sortBy.query - Sort field - enum:name,email,createdAt * @param {string} order.query - Sort order - enum:asc,desc * @return {PaginatedUsers} 200 - Users list with pagination * @example response - 200 * { * "data": [ * { * "id": "user_123", * "email": "user@example.com", * "name": "John Doe", * "role": "user" * } * ], * "pagination": { * "page": 1, * "pageSize": 10, * "total": 50, * "totalPages": 5 * } * } * @security bearerAuth */ app.get('/api/users', listUsers); ``` ```javascript /** * Paginated users response * @typedef {object} PaginatedUsers * @property {array} data.required - Array of users * @property {Pagination} pagination.required - Pagination metadata */ ``` ```javascript /** * Pagination info * @typedef {object} Pagination * @property {number} page.required - Current page number * @property {number} pageSize.required - Items per page * @property {number} total.required - Total items * @property {number} totalPages.required - Total pages */ ``` -------------------------------- ### Example Usage of processSwagger Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/swagger-processor.md Demonstrates how to use the `processSwagger` function with configuration options and a logger callback. Includes handling the promise resolution and potential errors. ```javascript const processSwagger = require('./processSwagger'); const options = { baseDir: __dirname, filesPattern: './**/*.js', info: { version: '1.0.0', title: 'My API', description: 'API Documentation', }, servers: [ { url: 'http://localhost:3000', description: 'Development' }, ], security: { bearerAuth: { type: 'http', scheme: 'bearer', }, }, }; const logger = ({ entity, swaggerObject }) => { console.log(`Processing: ${entity}`); console.log(`Current paths: ${Object.keys(swaggerObject.paths || {}).length}`); }; processSwagger(options, logger) .then(result => { console.log('Complete Swagger Object:'); console.log(JSON.stringify(result.swaggerObject, null, 2)); // Access transformer functions for additional processing const { jsdocInfo, getPaths, getComponents, getTags } = result; }) .catch(error => { console.error('Error generating swagger:', error); }); ``` -------------------------------- ### Create User (POST) Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/tutorial-endpoints.md Document a POST endpoint for creating a new user. Includes request and response examples, and defines the request body structure. ```javascript /** * Create a new user account * @summary Create user * @tags users - User management * @param {CreateUserRequest} request.body.required - User registration data * @return {User} 201 - User created successfully * @example request * { * "email": "user@example.com", * "name": "John Doe", * "password": "secure123" * } * @example response - 201 * { * "id": "user_123", * "email": "user@example.com", * "name": "John Doe", * "createdAt": "2024-01-15T10:30:00Z" * } * @return {object} 400 - Validation error * @example response - 400 * { * "code": "VALIDATION_ERROR", * "message": "Email is required", * "field": "email" * } * @return {object} 409 - Email already registered */ app.post('/api/users', createUser); ``` ```javascript /** * User registration data * @typedef {object} CreateUserRequest * @property {string} email.required - Email address - json:{"format":"email"} * @property {string} name.required - Full name * @property {string} password.required - Password (min 8 chars) - json:{"minLength":8} * @property {string} phone - Phone number */ ``` -------------------------------- ### JSON Request Body Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Defines a POST endpoint that accepts a JSON object as the request body, including example request and response payloads. ```APIDOC ## POST /api/users ### Description Creates a new user with the provided information. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **User** (object) - Required - User information - **name** (string) - Required - User's full name - **email** (string) - Required - User's email address - **role** (string) - Required - User's role (e.g., user, admin) ### Request Example ```json { "name": "John Doe", "email": "john@example.com", "role": "user" } ``` ### Response #### Success Response (201) - **User** (object) - The created user object, including an ID and creation timestamp - **id** (string) - Unique identifier for the user - **name** (string) - User's full name - **email** (string) - User's email address - **role** (string) - User's role - **createdAt** (string) - ISO 8601 timestamp of when the user was created #### Response Example ```json { "id": "123", "name": "John Doe", "email": "john@example.com", "role": "user", "createdAt": "2024-01-15T10:30:00Z" } ``` ``` -------------------------------- ### Error Responses with Examples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/responses-transformers.md Defines a DELETE request with various error responses (404, 401, 500) and provides an example for the 404 Not Found error. ```javascript /** * DELETE /api/users/{id} * @param {string} id.path.required - User ID * @return {object} 204 - User deleted * @return {object} 404 - User not found * @return {object} 401 - Unauthorized * @return {object} 500 - Server error * @example response - 404 * { * "code": "USER_NOT_FOUND", * "message": "User with ID 123 not found" * } */ app.delete('/api/users/:id', handler); ``` -------------------------------- ### Example Usage of jsdocInfo Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/consumers.md Demonstrates how to use the jsdocInfo consumer to parse an array of JSDoc comments and log the resulting parsed object. ```javascript const jsdocInfo = require('./consumers/jsdocInfo'); const comments = [ `/** * Get user by ID * @param {string} id.query - User ID * @return {User} 200 - User found */`, ]; const parser = jsdocInfo(); const parsed = parser(comments); console.log(parsed[0]); // Output: // { // description: 'Get user by ID', // tags: [ // { // name: 'param', // type: { name: 'string', ... }, // description: 'User ID', // ... // }, // { // name: 'return', // type: { name: 'User', ... }, // description: '200 - User found', // ... // } // ] // } ``` -------------------------------- ### GET /api/v1/album Endpoint with Auth and Params Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/README.md Defines a GET endpoint for '/api/v1/album' with basic authentication, tags, a required query parameter, and success/error response definitions. ```javascript /** * GET /api/v1/album * @summary This is the summary of the endpoint * @security BasicAuth * @tags album * @param {string} name.query.required - name param description * @return {object} 200 - success response - application/json * @return {object} 400 - Bad request response */ app.get('/api/v1/album', (req, res) => ( res.json({ title: 'abum 1', }) )); ``` -------------------------------- ### List Users (GET) Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/tutorial-endpoints.md Lists all users with support for pagination, searching, filtering by role, and sorting. ```APIDOC ## GET /api/users ### Description List all users with pagination. ### Method GET ### Endpoint /api/users ### Parameters #### Query Parameters - **page** (integer) - Optional - Page number (1-based) - **pageSize** (integer) - Optional - Items per page - **search** (string) - Optional - Search by name or email - **role** (string) - Optional - Filter by role - enum:admin,moderator,user - **sortBy** (string) - Optional - Sort field - enum:name,email,createdAt - **order** (string) - Optional - Sort order - enum:asc,desc ### Response #### Success Response (200) - **PaginatedUsers** - Users list with pagination #### Response Example ```json { "data": [ { "id": "user_123", "email": "user@example.com", "name": "John Doe", "role": "user" } ], "pagination": { "page": 1, "pageSize": 10, "total": 50, "totalPages": 5 } } ``` ### Security bearerAuth ``` -------------------------------- ### Complete Parameter Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Illustrates how JSDoc `@param` tags are used to define query, path, and header parameters for API endpoints, which are then transformed into OpenAPI specifications. ```APIDOC ## Example Usage ### GET /api/users ```javascript /** * GET /api/users * @param {string} search.query - Search term * @param {string} role.query - Filter by role - enum:admin,user,guest * @param {integer} page.query - Page number * @param {integer} limit.query - Items per page * @param {string} X-Request-ID.header.required - Request tracking ID * @return {array} 200 - Users list */ app.get('/api/users', getUsers); ``` ### GET /api/users/{id} ```javascript /** * GET /api/users/{id} * @param {string} id.path.required - User ID * @return {User} 200 - User details */ app.get('/api/users/:id', getUser); ``` ``` -------------------------------- ### Body Parameter Format Examples Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Illustrates the format for defining request bodies, including JSON and form data, with optional and required modifiers. ```APIDOC ### Body Parameter Format Body parameters use the format: `request.body[.modifiers]` - **request.body** - Marks parameter as request body - **modifiers** - Optional: `required`, `form` #### Examples ```javascript // JSON request body (required) /** * POST /api/users * @param {User} request.body.required - New user data * @return {User} 201 - Created user */ // Optional JSON body /** * PATCH /api/config * @param {object} request.body - Configuration updates * @return {object} 200 - Updated config */ // Form data /** * POST /api/upload * @param {file} request.body.form.required - File to upload * @param {string} description.form - File description * @return {object} 200 - Upload result */ ``` ``` -------------------------------- ### Form Data Body Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Defines a form data request body for file uploads with optional description and tags. ```javascript /** * POST /api/upload * @param {string} file.form.required - File to upload * @param {string} description.form - File description * @param {string} tags.form - Comma-separated tags * @return {object} 200 - Upload result */ ``` -------------------------------- ### Example with notRequiredAsNullable Option Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/components-transformers.md Demonstrates how to use the `notRequiredAsNullable` option during component parsing. When set to true, non-required properties in the generated schema will be marked as nullable. ```javascript parseComponents( {}, [componentData], { notRequiredAsNullable: true } ); // Non-required properties will have: nullable: true ``` -------------------------------- ### Form Data Body Example Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/request-body-parameters.md Details an endpoint that handles file uploads using form data, specifying required and optional fields. ```APIDOC ## POST /api/upload ### Description Uploads a file to the server with optional description and tags. ### Method POST ### Endpoint /api/upload ### Parameters #### Request Body - **file** (string) - Required - The file to upload (multipart/form-data) - **description** (string) - Optional - A description for the file - **tags** (string) - Optional - Comma-separated tags for the file ### Response #### Success Response (200) - **(object)** - Upload result details ``` -------------------------------- ### Example Usage of Array Utilities Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/schema-utilities.md Demonstrates the usage of flatArray to flatten a nested array and getIndexBy to find an element's index by a specific property. ```javascript const { flatArray, getIndexBy } = require('./transforms/utils/arrays'); flatArray([[1, 2], [3, 4]]); // Output: [1, 2, 3, 4] getIndexBy( [{ id: 'a' }, { id: 'b' }, { id: 'a' }], 'id', 'a' ); // Output: 0 (first occurrence) ``` -------------------------------- ### responsesGenerator Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/responses-transformers.md Generates OpenAPI responses object from @return tags and examples. Each status code gets its own response entry with schema, description, and optional examples. ```APIDOC ## responsesGenerator ### Description Generates OpenAPI responses object from @return tags and examples. Each status code gets its own response entry with schema, description, and optional examples. ### Signature ```javascript function responsesGenerator(returnValues = [], exampleValues = []) -> Object ``` ### Parameters #### Parameters - **returnValues** (Array) - Optional - Array of @return tag objects - **exampleValues** (Array) - Optional - Array of response example objects ### Returns **Type:** `Object` Object mapping HTTP status codes to response objects. ### Returned Object Structure ```javascript { '[statusCode]': { description: String, content?: { '[contentType]': { schema: Object, examples?: Object, }, }, }, // ... more status codes } ``` ### Example Usage ```javascript const returnTags = [ { type: { name: 'User' }, description: '200 - User found - application/json', }, { type: { name: 'object' }, description: '404 - User not found', }, { type: null, description: '500 - Server error', }, ]; const examples = { '200': [ { summary: 'Success example', value: { id: '123', name: 'John' }, }, ], }; const responses = responsesGenerator(returnTags, []); // Result: // { // '200': { // description: 'User found', // content: { // 'application/json': { // schema: { $ref: '#/components/schemas/User' }, // }, // }, // }, // '404': { // description: 'User not found', // }, // '500': { // description: 'Server error', // }, // } ``` ``` -------------------------------- ### Start Data Export Job Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/tutorial-endpoints.md Initiates an asynchronous job to export data based on specified options. Returns a job ID for status tracking. ```APIDOC ## POST /api/export ### Description Start an asynchronous data export job. Accepts export options and returns a job ID. ### Method POST ### Endpoint /api/export ### Parameters #### Request Body - **request** (ExportRequest) - Required - Export options ### Response #### Success Response (202) - **jobId** (string) - Required - Job ID - **status** (string) - Required - Job status - enum:pending,running,completed,failed - **createdAt** (string) - Required - Creation timestamp #### Response Example { "jobId": "job_abc123", "status": "pending", "createdAt": "2024-01-15T10:30:00Z" } ``` -------------------------------- ### Get Basic OpenAPI Info Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/api-reference/basic-info-security.md Applies formatting to the info and servers sections of the OpenAPI specification. Ensures these sections are properly structured according to OpenAPI 3.0 standards. ```javascript function getBasicInfo(swaggerObject = {}) { return Object; } ``` -------------------------------- ### Example: Define a Product Type with Detailed Properties Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/_autodocs/jsdoc-syntax-reference.md Demonstrates defining a 'Product' type with various property types, including required fields, enums, arrays, optional references, and custom JSON schema constraints. ```javascript /** * @typedef {object} Product * @property {string} id.required - Product ID * @property {string} name.required - Product name * @property {number} price.required - Price in cents * @property {string} category - Product category - enum:electronics,clothing,books * @property {boolean} inStock - In stock status * @property {array} tags - Product tags * @property {User|null} manufacturer - Manufacturer (optional) * @property {string} description - Long description - json:{"minLength":10} */ ``` -------------------------------- ### Run Project Tests Source: https://github.com/brikev/express-jsdoc-swagger/blob/master/CONTRIBUTING.md Execute this command to run the project's test suite. ```bash npm test ```