1const joi = require("joi");
2
3const createPost = (req, res, next) => {
4 const schema = joi.object({
5 content: joi.string().required(),
6 name: joi.string().required(),
7 });
8
9 const { error, value } = schema.validate(req.body);
10
11 if (error) {
12 console.log(error.details);
13 req.flash(
14 "error",
15 error.details.map((err) => err.message),
16 );
17 res.render("new_post", {
18 title: "New Post",
19 body: req.body,
20 flashes: req.flash(),
21 });
22 return;
23 } else {
24 req.xop = {
25 content: value.content,
26 name: value.name,
27 };
28 next();
29 }
30};
31
32const updatePost = (req, res, next) => {
33 const schema = joi.object({
34 name: joi.string(), // will not be used in the update
35 content: joi.string().required(),
36 });
37
38 const post = {
39 id: req.params.post_id,
40 content: req.body.content,
41 };
42
43 const { error, value } = schema.validate(req.body);
44
45 if (error) {
46 console.log(error.details);
47 req.flash(
48 "error",
49 error.details.map((err) => err.message),
50 );
51 res.render("edit_post", { title: "Edit Post", post, flashes: req.flash() });
52 return;
53 } else {
54 req.xop = {
55 content: value.content,
56 };
57 next();
58 }
59};
60
61module.exports = {
62 createPost,
63 updatePost,
64};
65