Skip to content

Commit e74b73b

Browse files
committed
feat: added middlewares. added patch method. improve validation. added hooks for Contact schema
1 parent 969dbc9 commit e74b73b

File tree

11 files changed

+180
-177
lines changed

11 files changed

+180
-177
lines changed

1/contacts.js

-92
This file was deleted.

app.js

-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import express from "express";
22
import logger from "morgan";
33
import cors from "cors";
44
import "dotenv/config";
5-
65
import contactsRouter from "./routes/api/contacts.js";
76

87
const app = express();

controllers/contacts-controller.js

+69-58
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,89 @@
11
import { HttpError } from "../helpers/index.js";
22
import { ctrlWrapper } from "../decorators/index.js";
33
import Contact from "../models/Contact.js";
4-
// import {
5-
// newContactValidation,
6-
// contactsEditValidation,
7-
// } from "../schemas/contacts-validation.js";
8-
// import {
9-
// addContact,
10-
// getContactById,
11-
// listContacts,
12-
// removeContact,
13-
// updateContact,
14-
// } from "../models/contacts.js";
4+
import {
5+
newContactValidation,
6+
contactsEditValidation,
7+
contactsFavoriteValidation,
8+
} from "../schemas/contacts-validation.js";
159

1610
async function getAllContacts(req, res, next) {
1711
const contacts = await Contact.find();
18-
console.log(contacts);
19-
// const contacts = await listContacts();
2012
if (contacts) {
2113
res.json(contacts);
2214
} else {
2315
throw HttpError(404, "No contacts found");
2416
}
2517
}
2618

27-
// async function getContactsById(req, res, next) {
28-
// const id = req.params.contactId;
29-
// const contactById = await getContactById(id);
30-
// if (contactById) {
31-
// res.json(contactById);
32-
// } else {
33-
// throw HttpError(404, "Contact not found");
34-
// }
35-
// }
19+
async function getContactsById(req, res, next) {
20+
const id = req.params.contactId;
21+
const contactById = await Contact.findById(id);
22+
if (contactById) {
23+
res.json(contactById);
24+
} else {
25+
throw HttpError(404, "Contact not found");
26+
}
27+
}
3628

37-
// async function addNewContact(req, res, next) {
38-
// const { error } = newContactValidation.validate(req.body);
39-
// if (error) {
40-
// throw HttpError(400, error.message);
41-
// }
42-
// const newContact = await addContact(req.body);
43-
// res.status(201).json(newContact);
44-
// }
29+
async function addNewContact(req, res, next) {
30+
const { error } = newContactValidation.validate(req.body);
31+
if (error) {
32+
throw HttpError(400, error.message);
33+
}
34+
const newContact = await Contact.create(req.body);
35+
console.log(newContact);
36+
res.status(201).json(newContact);
37+
}
4538

46-
// async function deleteContact(req, res, next) {
47-
// const id = req.params.contactId;
48-
// const deleteContact = await removeContact(id);
49-
// if (deleteContact) {
50-
// res.json({ message: "contact deleted", status: 200 });
51-
// } else {
52-
// throw HttpError(404);
53-
// }
54-
// }
39+
async function deleteContact(req, res, next) {
40+
const id = req.params.contactId;
41+
const deleteContact = await Contact.findByIdAndDelete(id);
42+
console.log(deleteContact);
43+
if (deleteContact) {
44+
res.json({ message: "contact deleted", status: 200 });
45+
} else {
46+
throw HttpError(404);
47+
}
48+
}
5549

56-
// async function editContact(req, res, next) {
57-
// const { error } = contactsEditValidation.validate(req.body);
58-
// if (error) {
59-
// throw HttpError(400, error.message);
60-
// }
61-
// const id = req.params.contactId;
62-
// const updatedContact = await updateContact(id, req.body);
63-
// if (Object.keys(req.body).length === 0) {
64-
// throw HttpError(404, "missing fields");
65-
// }
66-
// if (!updatedContact) {
67-
// throw HttpError(404, "Not found");
68-
// }
69-
// res.status(201).json(updatedContact);
70-
// }
50+
async function editContact(req, res, next) {
51+
const { error } = contactsEditValidation.validate(req.body);
52+
if (error) {
53+
throw HttpError(400, error.message);
54+
}
55+
const id = req.params.contactId;
56+
const updatedContact = await Contact.findByIdAndUpdate(id, req.body, {
57+
new: true,
58+
});
59+
if (!updatedContact) {
60+
throw HttpError(404, "Not found");
61+
}
62+
res.json(updatedContact);
63+
}
64+
65+
async function updateContact(req, res, next) {
66+
const { error } = contactsFavoriteValidation.validate(req.body);
67+
if (error) {
68+
throw HttpError(400, error.message);
69+
}
70+
const id = req.params.contactId;
71+
const updatedContact = await Contact.findByIdAndUpdate(id, req.body, {
72+
new: true,
73+
});
74+
75+
if (!updatedContact) {
76+
throw HttpError(404, "Not found");
77+
}
78+
79+
res.json(updatedContact);
80+
}
7181

7282
export default {
7383
getAllContacts: ctrlWrapper(getAllContacts),
74-
// getContactsById: ctrlWrapper(getContactsById),
75-
// addNewContact: ctrlWrapper(addNewContact),
76-
// deleteContact: ctrlWrapper(deleteContact),
77-
// editContact: ctrlWrapper(editContact),
84+
getContactsById: ctrlWrapper(getContactsById),
85+
addNewContact: ctrlWrapper(addNewContact),
86+
deleteContact: ctrlWrapper(deleteContact),
87+
editContact: ctrlWrapper(editContact),
88+
updateContact: ctrlWrapper(updateContact),
7889
};

middleware/index.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export { default as isValidId } from "./isValidId.js";
2+
export { default as isEmptyBody } from "./isEmptyBody.js";
3+
export { isEmptyBodyFavorite } from "./isEmptyBody.js";

middleware/isEmptyBody.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { HttpError } from "../helpers/index.js";
2+
3+
export default function isEmptyBody(req, res, next) {
4+
const { length } = Object.keys(req.body);
5+
if (!length) {
6+
return next(HttpError(400, "Body must have fields"));
7+
}
8+
next();
9+
}
10+
11+
export function isEmptyBodyFavorite(req, res, next) {
12+
const { length } = Object.keys(req.body);
13+
if (!length) {
14+
return next(HttpError(400, "missing field favorite"));
15+
}
16+
next();
17+
}

middleware/isValidId.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { isValidObjectId } from "mongoose";
2+
import { HttpError } from "../helpers/index.js";
3+
4+
export function isValidId(req, res, next) {
5+
const id = req.params.contactId;
6+
if (!isValidObjectId(id)) {
7+
return next(HttpError(404, `${id} not valid id`));
8+
}
9+
next();
10+
}
11+
12+
export default isValidId;

models/Contact.js

+25-15
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,31 @@
11
import { Schema, model } from "mongoose";
2+
import { handleSaveError, addUpdateSettings } from "./hooks.js";
23

3-
const contactSchema = new Schema({
4-
name: {
5-
type: String,
6-
required: [true, "Set name for contact"],
4+
const contactSchema = new Schema(
5+
{
6+
name: {
7+
type: String,
8+
required: [true, "Set name for contact"],
9+
},
10+
email: {
11+
type: String,
12+
},
13+
phone: {
14+
type: String,
15+
},
16+
favorite: {
17+
type: Boolean,
18+
default: false,
19+
},
720
},
8-
email: {
9-
type: String,
10-
},
11-
phone: {
12-
type: String,
13-
},
14-
favorite: {
15-
type: Boolean,
16-
default: false,
17-
},
18-
});
21+
{ versionKey: false, timestamps: true }
22+
);
23+
24+
contactSchema.post("save", handleSaveError);
25+
26+
contactSchema.pre("findOneAndUpdate", addUpdateSettings);
27+
28+
contactSchema.post("findOneAndUpdate", handleSaveError);
1929

2030
const Contact = model("contact", contactSchema);
2131

models/hooks.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
export function handleSaveError(error, data, next) {
2+
error.status = 400;
3+
next();
4+
}
5+
6+
export function addUpdateSettings(next) {
7+
this.options.new = true;
8+
this.options.runValidators = true;
9+
next();
10+
}

routes/api/contacts.js

+16-5
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,28 @@
11
import express from "express";
2-
2+
import {
3+
isValidId,
4+
isEmptyBody,
5+
isEmptyBodyFavorite,
6+
} from "../../middleware/index.js";
37
import contactsRequests from "../../controllers/contacts-controller.js";
48

59
const router = express.Router();
610

711
router.get("/", contactsRequests.getAllContacts);
812

9-
// router.get("/:contactId", contactsRequests.getContactsById);
13+
router.get("/:contactId", isValidId, contactsRequests.getContactsById);
14+
15+
router.post("/", isEmptyBody, contactsRequests.addNewContact);
1016

11-
// router.post("/", contactsRequests.addNewContact);
17+
router.delete("/:contactId", isValidId, contactsRequests.deleteContact);
1218

13-
// router.delete("/:contactId", contactsRequests.deleteContact);
19+
router.put("/:contactId", isValidId, isEmptyBody, contactsRequests.editContact);
1420

15-
// router.put("/:contactId", contactsRequests.editContact);
21+
router.patch(
22+
"/:contactId/favorite",
23+
isValidId,
24+
isEmptyBodyFavorite,
25+
contactsRequests.updateContact
26+
);
1627

1728
export default router;

0 commit comments

Comments
 (0)