Skip to content

Instantly share code, notes, and snippets.

View simonrenoult's full-sized avatar
🏠
Working from home

Simon Renoult simonrenoult

🏠
Working from home
View GitHub Profile
if (totalAmount > 1000) {
totalAmount = totalAmount * 0.95;
}
const errorMessage = error.details.map(({ message, context }) =>
Object.assign({ message, context })
);
// API route to create an order
app.post("/orders", async (req, res) => {
// HTTP request payload validation
// abortEarly is false in order to retrieve all the errors at once
const { error } = Joi.validate(req.body, orderSchema, {
abortEarly: false
});
if (error) {
const errorMessage = error.details.map(({ message, context }) =>
app.post("/products", async (req, res) => {
const { error } = Joi.validate(req.body, productSchema, { abortEarly: false });
if (error) {
const errorMessage = error.details.map(({ message, context }) =>
Object.assign({ message, context })
);
return res.status(400).send({ data: errorMessage });
}
it("returns the product location", async () => {
const data = { name: "tshirt", price: 20, weight: 0.1 };
const { headers } = await queryApi("POST", "/products", {body: data});
expect(headers.location).to.match(/products\/.+/);
});
app.post("/products", async (req, res) => {
const { error } = Joi.validate(req.body, productSchema, { abortEarly: false });
if (error) {
const errorMessage = error.details.map(({ message, context }) =>
Object.assign({ message, context })
);
return res.status(400).send({ data: errorMessage });
}
it("returns 201", async () => {
const product = { name: "tshirt", price: 20, weight: 0.1 };
const { statusCode } = await queryApi("POST", "/products", {body: data});
expect(statusCode).to.equal(201);
});
const productSchema = Joi.object().keys({
name: Joi.required(),
price: Joi.required(),
weight: Joi.required()
});
// …
app.post("/products", async (req, res) => {
const { error } = Joi.validate(req.body, productSchema, { abortEarly: false });
it("returns the keys in error", async () => {
const { body, statusCode } = await queryApi("POST", "/products", { body: {} });
const contextList = body.data.map(item => item.context.key);
expect(statusCode).to.equal(400);
expect(contextList).to.contain("name", "price", "weight");
});
app.post("/products", async (req, res) => {
if (Object.keys(req.body).length === 0) {
return res.status(400).send();
}
});