-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathrequest-validator.middleware.ts
45 lines (40 loc) · 1.15 KB
/
request-validator.middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import {
validate,
ValidationErrors,
ValidationRules,
} from "https://deno.land/x/validasaur@v0.7.0/src/mod.ts";
import { httpErrors } from "https://deno.land/x/oak@v5.0.0/mod.ts";
import { Context } from "./../types.ts";
/**
* get single error message from errors
*/
const getErrorMessage = (
errors: ValidationErrors,
): string | undefined => {
for (let attr in errors) {
const attrErrors = errors[attr];
for (let rule in attrErrors) {
return attrErrors[rule] as string;
}
}
};
/**
* request validation middleware
* validate request body with given validation rules
*/
const requestValidator = ({ bodyRules }: { bodyRules: ValidationRules }) => {
return async (ctx: Context, next: () => Promise<void>) => {
/** get request body */
const request = ctx.request;
const body = (await request.body()).value;
/** check rules */
const [isValid, errors] = await validate(body, bodyRules);
if (!isValid) {
/** if error found, throw bad request error */
const message = getErrorMessage(errors);
throw new httpErrors.BadRequest(message);
}
await next();
};
};
export { requestValidator };