🧑🎓 With express.js
Verifica can be easily used with Express to verify user inputs into the API:
const express = require("express");
const bodyParser = require("body-parser");
const { asVerificable, all, isStringLength, isRegexMatch, ensure, isObject, isString } = require("verifica");
// Custom Predicates:
const isEmail = all(
isStringLength({ min: 3, max: 256 }),
isRegexMatch(/^[^@]+@[^@]+$/),
);
const isPassword = isStringLength({ min: 8, max: 256 });
function isNewUser(verificable) {
ensure(verificable, isObject);
ensure(verificable.email, isEmail);
ensure(verificable.password, isPassword);
}
// The server app:
const app = express();
app.use(bodyParser.json());
app.post("/users/:userId", (req, res) => {
const vreq = asVerificable(req);
const userId = ensure(vreq.params.userId, isString);
const newUser = ensure(vreq.body, isNewUser);
res.send(`New user created: userId = ${userId}, email = ${newUser.email}!`);
});
app.listen(5000, () => console.log("Listening on http://localhost:5000"));
Last updated