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
51 changes: 35 additions & 16 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,44 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')
const express = require("express");
const logger = require("morgan");
const cors = require("cors");
const mongoose = require("mongoose");

const contactsRouter = require('./routes/api/contacts')
require("dotenv").config();

const app = express()
const contactsRouter = require("./routes/api/contacts");
const usersRouter = require("./routes/api/users");

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

app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())
const formatsLogger = app.get("env") === "development" ? "dev" : "short";

app.use('/api/contacts', contactsRouter)
app.use(logger(formatsLogger));
app.use(cors());
app.use(express.json());

app.use("/api/contacts", contactsRouter);
app.use("/api/users", usersRouter);

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

app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
})

module.exports = app
res.status(500).json({ message: err.message });
});

const { DB_HOST, PORT = 3000 } = process.env;

mongoose
.connect(DB_HOST)
.then(() => {
console.log("Database connection succesful^_^");
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
})
.catch((error) => {
console.error("Database connection error:", error.message);
});

module.exports = app;
19 changes: 19 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const jwt = require("jsonwebtoken");
const User = require("../models/user");

const authMiddleware = async (req, res, next) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ message: "Not authorized ^_^" });

try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.id);
if (!user || user.token !== token) return res.status(401).json({ message: "Not authorized ^_^" });
req.user = user;
next();
} catch (error) {
return res.status(401).json({ message: "Not authorized ^_^" });
}
};

module.exports = authMiddleware;
64 changes: 64 additions & 0 deletions controllers/contacts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const Contact = require("../models/contact");

//GET /api/contacts
const listContacts = async (page, limit, filter) => {
const contacts = await Contact.find({ ...filter })
.skip((page - 1) * limit)
.limit(limit)
.exec();
const totalContacts = await Contact.countDocuments({ ...filter });
return {
totalContacts,
totalPages: Math.ceil(totalContacts / limit),
page,
limit,
contacts,
};
};

//GET /api/contacts/:id
const getContactById = async (req, res) => {
const contact = await Contact.findById(req.params.id);
if (!contact) return res.status(404).json({ message: "Contact not found" });
res.status(200).json(contact);
};

//POST /api/contacts
const addContact = async (req, res) => {
const { name, email, phone, favorite } = req.body;
const contact = new Contact({ name, email, phone, favorite, owner: req.user._id });
await contact.save();
res.status(201).json(contact);
};

//DELETE /api/contacts/:id
const removeContact = async (req, res) => {
const contact = await Contact.findByIdAndDelete(req.params.id);
if (!contact) return res.status(404).json({ message: "Contact not found" });
res.status(200).json({ message: "Contact deleted" });
};

//PUT /api/contacts/:id
const updateContact = async (req, res) => {
const contact = await Contact.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!contact) return res.status(404).json({ message: "Contact not found" });
res.status(200).json(contact);
};

//PATCH /api/contacts/:id/favorite
const updateFavorite = async (req, res) => {
const contact = await Contact.findById(req.params.id);
if (!contact) return res.status(404).json({ message: "Contact not found" });
contact.favorite = !contact.favorite;
await contact.save();
res.status(200).json(contact);
};

module.exports = {
listContacts,
getContactById,
addContact,
removeContact,
updateContact,
updateFavorite,
};
25 changes: 25 additions & 0 deletions models/contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const mongoose = require("mongoose");

const contactSchema = new mongoose.Schema({
name: {
type: String,
},
email: {
type: String,
},
phone: {
type: String,
},
favorite: {
type: Boolean,
default: false,
},
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
});

const Contact = mongoose.model("Contact", contactSchema);

module.exports = Contact;
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.

34 changes: 34 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const userSchema = new mongoose.Schema({
password: {
type: String,
required: [true, "Password is required"],
},
email: {
type: String,
required: [true, "Email is required"],
unique: true,
},
subscription: {
type: String,
enum: ["starter", "pro", "business"],
default: "starter",
},
token: {
type: String,
default: null,
},
});

userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
next();
});

const User = mongoose.model("User", userSchema);

module.exports = User;
Loading