60 lines
1.8 KiB
JavaScript
60 lines
1.8 KiB
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 field_value = ctx.request.body[field_name];
|
|
|
|
if (field_value === undefined || typeof field_value !== 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();
|
|
};
|
|
}
|
|
|
|
/** @typedef {function(string): boolean} ParameterPredicate */
|
|
|
|
/**
|
|
* Koa middleware generator for checking the presence of a parameter in the request URL.
|
|
*
|
|
* @param {string} param_name - The name of the parameter to be checked.
|
|
* @param {ParameterPredicate?} predicate - The expected type of the field.
|
|
* @returns {Middleware} Koa middleware function.
|
|
*/
|
|
export function parameterRequired(param_name, predicate) {
|
|
/**
|
|
* @param {Context} ctx - Koa context object.
|
|
* @param {Next} next - Next middleware function.
|
|
*/
|
|
return async (ctx, next) => {
|
|
const param_value = ctx.params[param_name];
|
|
|
|
if (param_value === undefined || (predicate != null && !predicate(param_value))) {
|
|
ctx.status = 400; // 400 Bad Request
|
|
ctx.body = {
|
|
error: `URL Parameter '${param_name}' is missing or invalid.`,
|
|
};
|
|
return;
|
|
}
|
|
|
|
await next();
|
|
};
|
|
}
|