Skip to content
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
node_modules
.env
75 changes: 75 additions & 0 deletions controllers/person.controller.js
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 });
}
Comment on lines +4 to +15
Copy link
Copy Markdown

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, and hobbies.

Currently, there is no validation for the input data. Consider adding validation to ensure that name is a string, age is a number, and hobbies is an array.

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" });
}

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.

try {
  // existing code
} catch (error) {
  if (error instanceof ValidationError) {
    res.status(400).json({ message: error.message });
  } else {
    res.status(500).json({ message: "Internal server error" });
  }
}

};

// 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
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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
Copy link
Copy Markdown

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, and hobbies.

Currently, there is no validation for the input data. Consider adding validation to ensure that name is a string, age is a number, and hobbies is an array.

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
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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" });
  }
}

};
52 changes: 45 additions & 7 deletions index.js
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;
37 changes: 37 additions & 0 deletions models/person.model.js
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);
}
};
11 changes: 11 additions & 0 deletions routes/person.router.js
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;