Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hw02 express #5495

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 47 additions & 7 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,59 @@
// const fs = require('fs/promises')
const fs = require("fs/promises");
const path = require("path");
const nanoid = require("nanoid");

const listContacts = async () => {}
const contactsPath = path.join(__dirname, "./contacts.json");

const getContactById = async (contactId) => {}
const readContacts = async () => {
const data = await fs.readFile(contactsPath, "utf8");
return JSON.parse(data);
};

const removeContact = async (contactId) => {}
const writeContacts = async (contacts) => {
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
};

const addContact = async (body) => {}
const listContacts = async () => {
return await readContacts();
};

const updateContact = async (contactId, body) => {}
const getContactById = async (contactId) => {
const contacts = await readContacts();
return contacts.find((contact) => contact.id === contactId) || null;
};

const removeContact = async (contactId) => {
const contacts = await readContacts();
const index = contacts.findIndex((contact) => contact.id === contactId);
if (index === -1) return null;

const [removedContact] = contacts.splice(index, 1);
await writeContacts(contacts);
return removedContact;
};

const addContact = async ({ name, email, phone }) => {
const contacts = await readContacts();
const newContact = { id: nanoid(), name, email, phone };
contacts.push(newContact);
await writeContacts(contacts);
return newContact;
};

const updateContact = async (contactId, { name, email, phone }) => {
const contacts = await readContacts();
const index = contacts.findIndex((contact) => contact.id === contactId);
if (index === -1) return null;

contacts[index] = { ...contacts[index], name, email, phone };
await writeContacts(contacts);
return contacts[index];
};

module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
}
};
112 changes: 111 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"cors": "2.8.5",
"cross-env": "7.0.3",
"express": "4.17.1",
"morgan": "1.10.0"
"joi": "^17.13.3",
"morgan": "1.10.0",
"nanoid": "^5.0.8"
},
"devDependencies": {
"eslint": "7.19.0",
Expand Down
112 changes: 94 additions & 18 deletions routes/api/contacts.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,101 @@
const express = require('express')
const express = require("express");
const joi = require("joi");

const router = express.Router()
const router = express.Router();

router.get('/', async (req, res, next) => {
res.json({ message: 'template message' })
})
const {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
} = require("../../models/contacts");

router.get('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
router.get("/", async (req, res, next) => {
try {
const contacts = await listContacts();
res.status(200).json(contacts);
} catch (error) {
next(error);
}
});

router.post('/', async (req, res, next) => {
res.json({ message: 'template message' })
})
router.get("/:id", async (req, res, next) => {
try {
const { id } = req.params;
const contact = await getContactById(id);
if (!contact) {
return res.status(404).json({ message: "Not found" });
}
res.status(200).json(contact);
} catch (error) {
next(error);
}
});

router.delete('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
router.post("/", async (req, res, next) => {
try {
const { error } = joi
.object({
name: joi.string().required(),
email: joi.string().email().required(),
phone: joi
.string()
.pattern(/^[0-9]+$/)
.required(),
})
.validate(req.body);

router.put('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
if (error) {
return res.status(400).json({ message: error.details[0].message });
}

module.exports = router
const { name, email, phone } = req.body;
const newContact = await addContact({ name, email, phone });
res.status(201).json(newContact);
} catch (error) {
next(error);
}
});

router.delete("/:id", async (req, res, next) => {
try {
const { id } = req.params;
const contact = await removeContact(id);
if (!contact) {
return res.status(404).json({ message: "Not found" });
}
res.status(200).json({ message: "contact deleted" });
} catch (error) {
next(error);
}
});

router.put("/:id", async (req, res, next) => {
try {
const { error } = joi
.object({
name: joi.string(),
email: joi.string().email(),
phone: joi.string().pattern(/^[0-9]+$/),
})
.min(1)
.validate(req.body);

if (error) {
return res.status(400).json({ message: error.details[0].message });
}

const { id } = req.params;
const { name, email, phone } = req.body;
const updatedContact = await updateContact(id, { name, email, phone });
if (!updatedContact) {
return res.status(404).json({ message: "Not found" });
}
res.status(200).json(updatedContact);
} catch (error) {
next(error);
}
});

module.exports = router;