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

Hw03 mongodb #55

Open
wants to merge 25 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
33 changes: 18 additions & 15 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,28 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')
import express from "express";
import logger from "morgan";
import cors from "cors";

const contactsRouter = require('./routes/api/contacts')
import router from "./routes/api/contactsRouter.js"; // Import your routes correctly

const app = express()
const app = express();

const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short'
const formatsLogger = app.get("env") === "development" ? "dev" : "short";

app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())
app.use(logger(formatsLogger));
app.use(cors());
app.use(express.json());

app.use('/api/contacts', contactsRouter)
// Use proper route for contacts API
app.use("/api/contacts", router);

app.use((req, res) => {
res.status(404).json({ message: 'Not found' })
})
res.status(404).json({ message: "Not found" });
});

// Central error handler
app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
})
console.error(err.stack);
res.status(500).json({ message: err.message });
});

module.exports = app
export { app };
88 changes: 88 additions & 0 deletions controllers/contactsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { Contact } from "../models/contactsModel.js";
// prettier-ignore
import { contactValidation, favoriteValidation } from "../validations/validation.js";
import { httpError } from "../helpers/httpError.js";

const getAllContacts = async (_req, res) => {
const result = await Contact.find();
res.json(result);
};

const getContactById = async (req, res) => {
const { contactId } = req.params;

const result = await Contact.findById(contactId);

if (!result) {
throw httpError(404, "Contact ID Not Found");
}

res.json(result);
};

const addContact = async (req, res) => {
const { error } = contactValidation.validate(req.body);

if (error) {
throw httpError(400, "missing required field");
}

const result = await Contact.create(req.body);

res.status(201).json(result);
};

const deleteContactById = async (req, res) => {
const { contactId } = req.params;

const result = await Contact.findByIdAndDelete(contactId);

if (!result) {
throw httpError(404);
}

res.json({
message: "Contact deleted",
});
};

const updateContactById = async (req, res) => {
const { error } = contactValidation.validate(req.body);
if (error) {
throw httpError(400, "missing fields");
}

const { contactId } = req.params;

const result = await Contact.findByIdAndUpdate(contactId, req.body, {
new: true,
});

if (!result) {
throw httpError(404);
}

res.json(result);
};

const updateStatusContact = async (req, res) => {
const { error } = favoriteValidation.validate(req.body);
if (error) {
throw httpError(400, "missing field favorite");
}

const { contactId } = req.params;

const result = await Contact.findByIdAndUpdate(contactId, req.body, {
new: true,
});

if (!result) {
throw httpError(404);
}

res.json(result);
};

// prettier-ignore
export { getAllContacts, getContactById, addContact, deleteContactById, updateContactById, updateStatusContact};
12 changes: 12 additions & 0 deletions helpers/ctrlWrapper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const ctrlWrapper = (ctrl) => {
const func = async (req, res, next) => {
try {
await ctrl(req, res, next);
} catch (error) {
next(error);
}
};
return func;
};

export { ctrlWrapper };
15 changes: 15 additions & 0 deletions helpers/httpError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const messages = {
400: "Bad request",
401: "Unauthorized",
403: "Forbidden",
404: "Not found",
409: "Conflict",
};

const httpError = (status, message = messages[status]) => {
const error = new Error(message);
error.status = status;
return error;
};

export { httpError };
Binary file added images/DELETE.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/DELETE_mongodb.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/GET_all.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/GET_byid.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/PATCH.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/PATCH_mongodb1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/PATCH_mongodb2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/POST_mongodb.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/POST_postman.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/PUT.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/PUT_mongodb.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 0 additions & 19 deletions models/contacts.js

This file was deleted.

62 changes: 0 additions & 62 deletions models/contacts.json

This file was deleted.

27 changes: 27 additions & 0 deletions models/contactsModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Schema, model } from "mongoose";

const contactSchema = new Schema(
{
name: {
type: String,
required: [true, "Set name for contact"],
},
email: {
type: String,
required: [true, "Set email for contact"],
},
phone: {
type: String,
required: [true, "Set phone for contact"],
},
favorite: {
type: Boolean,
default: false,
},
},
{ versionKey: false }
);

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

export { Contact };
Loading