Here is a controller endpoint code for which I'm trying to make use of tsoa
for the generation of swagger documentation. tsoa
works for endpoints' class methods with simple query/path parameters, however, this approach is pretty different.
In the controller.ts
file, there are no class methods but RequestHandler
s.
const createValidationChain = [
body('name').notEmpty().withMessage(errorMessages.required('name')),
body('description').optional(),
body('subcategories')
.custom((subcategories) => Array.isArray(subcategories))
.optional()
];
const createCategoryHandler: RequestHandler<
CreateCategoryParams,
ResponseOrError<CreateCategoryResponse>,
CreateCategoryRequest
> = async (req, res) => {
try {
let getCategoryByName;
if (req.body.name) {
getCategoryByName = await CategoryModel.findOne({
name: req.body.name
}).exec()
}
if (getCategoryByName) {
return res.status(StatusCodes.CONFLICT).send({
fieldErrors: [{
field: "name",
message: `Category with name '${req.body.name}' already exists!`
}
]
})
}
const newCategory = await CategoryModel.create(req.body);
return res.status(StatusCodes.CREATED).send(newCategory);
} catch (error) {
console.error(error);
return res.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR);
}
};
export const createCategory = [
validateMiddleware(createValidationChain),
createCategoryHandler,
];
The CategoryModel
= model('Category', categorySchema); is just a simple schema with a few properties.
export const categorySchema = new Schema<Category>({
name: { type: String, required: true},
description: { type: String },
subcategories: [{ type: Schema.Types.ObjectId, ref: 'SubCategory' }]
}, {
timestamps: true
}
)
Next, I have a router that is finally injected into the express app.
import express, { Router } from 'express';
import * as controller from './controller';
const router: Router = express.Router();
...
router.post('/', controller.createCategory);
...
export default router;
I'm trying to find a way how to 'easily' auto-generate swagger documentation for the endpoints. I've seen the options here tsoa docs but can't catch something useful for my endpoints. Any suggestions or recommendations?
Or, someone to recommend other than tsoa
packages that could help with this case?