opengenerals/server/middlewares/data-required.mjs
szdytom f2434a5953
...
Signed-off-by: szdytom <szdytom@qq.com>
2024-03-04 18:52:31 +08:00

31 lines
939 B
JavaScript

/** @typedef {import('koa').Context} Context */
/** @typedef {import('koa').Next} Next */
/** @typedef {import('koa').Middleware} Middleware */
/**
* Koa middleware generator for checking the presence and type of a field in the request body.
*
* @param {string} field_name - The name of the field to be checked.
* @param {string} field_type - The expected type of the field.
* @returns {Middleware} Koa middleware function.
*/
export function syllableRequired(field_name, field_type) {
/**
* @param {Context} ctx - Koa context object.
* @param {Next} next - Next middleware function.
*/
return async (ctx, next) => {
const fieldValue = ctx.request.body[field_name];
if (fieldValue === undefined || typeof fieldValue !== field_type) {
ctx.status = 400; // 400 Bad Request
ctx.body = {
error: `Field '${field_name}' is required and must be of type '${field_type}'.`,
};
return;
}
await next();
};
}