-
Notifications
You must be signed in to change notification settings - Fork 35
Complete Challenge: Implement Node CRUD Operations #6
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| node_modules | ||
| node_modules | ||
| .env |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| const Person = require("../models/person.model.js"); | ||
|
|
||
| // to create a new person | ||
| exports.createPerson = (req, res) => { | ||
| try { | ||
| const { name, age, hobbies } = req.body; | ||
| const persons = req.app.get("db"); | ||
| const newPerson = Person.createPerson(persons, name, age, hobbies); | ||
| res.status(200).json({ | ||
| message: "Person created successfully", | ||
| data: newPerson, | ||
| }); | ||
| } catch (error) { | ||
| res.status(400).json({ message: error.message }); | ||
| } | ||
| }; | ||
|
|
||
| // to get all persons or a person by id | ||
| exports.getPersons = (req, res) => { | ||
| const { id } = req.params; | ||
| const persons = req.app.get("db"); | ||
|
|
||
| if (id) { | ||
| const person = Person.getPersonById(persons, id); | ||
| if (person) { | ||
| res.status(200).json(person); | ||
| } else { | ||
| res.status(404).json({ message: "Person with such Id is not found" }); | ||
| } | ||
| } else { | ||
| res.status(200).json(persons); | ||
| } | ||
| }; | ||
|
Comment on lines
+19
to
+33
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Handle invalid IDs. Currently, there is no validation for the ID parameter. Consider adding validation to ensure that the ID is a valid format (e.g., a number or a UUID). const { id } = req.params;
if (id && !isValidId(id)) {
return res.status(400).json({ message: "Invalid ID format" });
}Improve error handling. The current error handling returns a 404 status code for all errors when retrieving a person by ID. Consider differentiating between different types of errors, such as invalid ID format, person not found, etc. try {
// existing code
} catch (error) {
if (error instanceof NotFoundError) {
res.status(404).json({ message: error.message });
} else {
res.status(500).json({ message: "Internal server error" });
}
} |
||
|
|
||
| // to update an existing person by id | ||
| exports.updatePerson = (req, res) => { | ||
| const { id } = req.params; | ||
| const { name, age, hobbies } = req.body; | ||
| const persons = req.app.get("db"); | ||
|
|
||
| try { | ||
| const updatedPerson = Person.updatePersonById(persons, id, { | ||
| name, | ||
| age, | ||
| hobbies, | ||
| }); | ||
| res.status(200).json({ | ||
| message: "Person updated successfully", | ||
| data: updatedPerson, | ||
| }); | ||
| } catch (error) { | ||
| res.status(404).json({ message: error.message }); | ||
| } | ||
|
Comment on lines
+36
to
+53
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add input validation for Currently, there is no validation for the input data. Consider adding validation to ensure that const { name, age, hobbies } = req.body;
if (typeof name !== 'string' || typeof age !== 'number' || !Array.isArray(hobbies)) {
return res.status(400).json({ message: "Invalid input data" });
}Handle invalid IDs. Currently, there is no validation for the ID parameter. Consider adding validation to ensure that the ID is a valid format (e.g., a number or a UUID). const { id } = req.params;
if (!isValidId(id)) {
return res.status(400).json({ message: "Invalid ID format" });
}Improve error handling. The current error handling returns a 404 status code for all errors. Consider differentiating between different types of errors, such as validation errors, person not found, database errors, etc. try {
// existing code
} catch (error) {
if (error instanceof ValidationError) {
res.status(400).json({ message: error.message });
} else if (error instanceof NotFoundError) {
res.status(404).json({ message: error.message });
} else {
res.status(500).json({ message: "Internal server error" });
}
} |
||
| }; | ||
|
|
||
| // to delete a person by id | ||
|
|
||
| exports.deletePerson = (req, res) => { | ||
| const { id } = req.params; | ||
| const persons = req.app.get("db"); | ||
| try { | ||
| const person = Person.getPersonById(persons, id); | ||
| if (!person) { | ||
| return res | ||
| .status(404) | ||
| .json({ message: "Person with such Id is not found" }); | ||
| } | ||
| Person.deletePersonById(persons, id); | ||
| res.status(200).json({ message: "Person deleted successfully" }); | ||
| } catch (error) { | ||
| res | ||
| .status(500) | ||
| .json({ message: "An error occurred while deleting the person" }); | ||
| } | ||
|
Comment on lines
+58
to
+74
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Handle invalid IDs. Currently, there is no validation for the ID parameter. Consider adding validation to ensure that the ID is a valid format (e.g., a number or a UUID). const { id } = req.params;
if (!isValidId(id)) {
return res.status(400).json({ message: "Invalid ID format" });
}Improve error handling. The current error handling returns a 500 status code for all errors. Consider differentiating between different types of errors, such as person not found, database errors, etc. try {
// existing code
} catch (error) {
if (error instanceof NotFoundError) {
res.status(404).json({ message: error.message });
} else {
res.status(500).json({ message: "Internal server error" });
}
} |
||
| }; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,55 @@ | ||
| const express = require('express') | ||
| const app = express() | ||
| const express = require("express"); | ||
| const bodyParser = require("body-parser"); | ||
| const cors = require("cors"); | ||
| require("dotenv").config(); | ||
| const personRoutes = require("./routes/person.router"); | ||
|
|
||
| const app = express(); | ||
| const port = process.env.PORT || 3000; | ||
|
|
||
| let persons = [{ | ||
| id: '1', | ||
| name: 'Sam', | ||
| age: '26', | ||
| hobbies: [] | ||
| id: '1', | ||
| name: 'Sam', | ||
| age: '26', | ||
| hobbies: [] | ||
| }] //This is your in memory database | ||
|
|
||
| app.set('db', persons) | ||
|
|
||
| //TODO: Implement crud of person | ||
|
|
||
| // Middlewares | ||
| app.use(bodyParser.json()); | ||
| app.use(cors()); | ||
|
|
||
| app.get("/", (req, res) => { | ||
| res.send("Welcome to the Node-CRUD-challenge"); | ||
| }); | ||
|
|
||
| // person routes | ||
| app.use("/person", personRoutes); | ||
|
|
||
| // Handle non-existing endpoints | ||
| app.use((req, res) => { | ||
| res.status(404).send({ message: "Oops! Endpoint not found" }); | ||
| }); | ||
|
|
||
| // Error handling middleware | ||
| app.use((err, req, res, next) => { | ||
| console.error(err.stack); | ||
| const statusCode = err.statusCode || 500; | ||
| const message = err.message || "Internal Server Error"; | ||
| return res.status(statusCode).json({ | ||
| success: false, | ||
| statusCode, | ||
| message, | ||
| }); | ||
| }); | ||
|
|
||
| if (require.main === module) { | ||
| app.listen(3000) | ||
| app.listen(port, () => { | ||
| console.log(`Server is running on http://localhost:${port}`); | ||
| }); | ||
| } | ||
|
|
||
| module.exports = app; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| const { v4: uuidv4 } = require("uuid"); | ||
|
|
||
| exports.createPerson = (persons, name, age, hobbies) => { | ||
| if (!name || typeof name !== "string") { | ||
| throw new Error("Invalid name"); | ||
| } | ||
| if (!age || typeof age !== "number") { | ||
| throw new Error("Invalid age"); | ||
| } | ||
| if (!hobbies || !Array.isArray(hobbies)) { | ||
| throw new Error("Invalid hobbies"); | ||
| } | ||
|
|
||
| const newPerson = { id: uuidv4(), name, age, hobbies }; | ||
| persons.push(newPerson); | ||
| return newPerson; | ||
| }; | ||
|
|
||
| exports.getAllPersons = (persons) => persons; | ||
|
|
||
| exports.getPersonById = (persons, id) => persons.find((p) => p.id === id); | ||
|
|
||
| exports.updatePersonById = (persons, id, updatedPerson) => { | ||
| const person = exports.getPersonById(persons, id); | ||
| if (!person) { | ||
| throw new Error("Person with such Id is not found"); | ||
| } | ||
| Object.assign(person, updatedPerson); | ||
| return person; | ||
| }; | ||
|
|
||
| exports.deletePersonById = (persons, id) => { | ||
| const index = persons.findIndex((p) => p.id === id); | ||
| if (index !== -1) { | ||
| persons.splice(index, 1); | ||
| } | ||
| }; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| const express = require("express"); | ||
| const router = express.Router(); | ||
| const personController = require("../controllers/person.controller.js"); | ||
|
|
||
| router | ||
| .post("/", personController.createPerson) | ||
| .get("/:id?", personController.getPersons) | ||
| .put("/:id", personController.updatePerson) | ||
| .delete("/:id", personController.deletePerson); | ||
|
|
||
| module.exports = router; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add input validation for
name,age, andhobbies.Currently, there is no validation for the input data. Consider adding validation to ensure that
nameis a string,ageis a number, andhobbiesis an array.Improve error handling.
The current error handling returns a 400 status code for all errors. Consider differentiating between different types of errors, such as validation errors, database errors, etc.