Last active
November 17, 2021 22:58
-
-
Save svyatoslavratov/248e8bf5d9fab48a1e40712c55175d27 to your computer and use it in GitHub Desktop.
Simple input validation for Express with Joi and Celebrate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Joi, Segments } from "celebrate"; | |
import express from "express"; | |
import type { NextFunction, Request, Response } from "express"; | |
// import our validator | |
import { | |
contentTypeApplicationJsonValidator, | |
validator | |
} from "./validator"; | |
// For example | |
import { CreateUserDto } from "./dto/create-user.dto.ts"; | |
const router = express.Router(); | |
router.post( | |
"/", | |
contentTypeApplicationJsonValidator, | |
validator({ | |
[Segments.BODY]: Joi.object({ | |
login: Joi.string().required(), | |
password: Joi.string().required(), | |
email: Joi.string().email().required(), | |
type: Joi.string(), | |
difficultField: Joi.when("type", { | |
is: "cool", // For Example | |
then: Joi.string() | |
.valid("valid", "valid_2") | |
.required(), | |
otherwise: Joi.forbidden() | |
}) | |
}).required() | |
}), | |
async ( | |
req: Request<any, any, CreateUserDto>, | |
res: Response, | |
next: NextFunction | |
) => { | |
try { | |
res.sendStatus(200); | |
} catch (err) { | |
next(err); | |
} | |
} | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { SchemaOptions, CelebrateOptions } from "celebrate"; | |
import { celebrator, Modes } from "celebrate"; | |
import type { ValidationOptions } from "joi"; | |
import type { RequestHandler } from "express"; | |
import _ from "lodash"; | |
export function validator( | |
schema: SchemaOptions, | |
celebrateOptions?: CelebrateOptions, | |
joiOptions?: ValidationOptions | |
): RequestHandler { | |
return celebrator( | |
_.merge({ mode: Modes.FULL } as CelebrateOptions, celebrateOptions), | |
_.merge( | |
{ abortEarly: false, convert: true } as ValidationOptions, | |
joiOptions | |
), | |
schema | |
); | |
} | |
// Simple reusable validator | |
export const contentTypeApplicationJsonValidator = validator({ | |
[Segments.HEADERS]: Joi.object({ | |
"content-type": Joi.string().valid("application/json", "application/json; charset=utf-8").required() | |
}).unknown() | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment