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 #5520

Open
wants to merge 8 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
36 changes: 21 additions & 15 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
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 contactsRouter = require('./routes/api/contacts')
require("dotenv").config();

const app = express()
const contactsRouter = require("./routes/api/contacts");
const connectDB = require("./data-db");

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((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 })
})
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode).json({ message: err.message });
});

connectDB();

module.exports = app
module.exports = app;
16 changes: 16 additions & 0 deletions data-db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
require("dotenv").config();

const mongoose = require("mongoose");

async function connectDB() {
const MONGO_URI = process.env.MONGO_URI;

await mongoose
.connect(MONGO_URI)
.then(() => console.log("Database connection successful"))
.catch((error) => {
console.error("Database connection error:", error.message);
process.exit(1);
});
}
module.exports = connectDB;
22 changes: 22 additions & 0 deletions models/contactSchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require("mongoose");

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

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

module.exports = Contact;
97 changes: 85 additions & 12 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,92 @@
// const fs = require('fs/promises')
const Contact = require("./contactSchema.js");

const listContacts = async () => {}
async function listContacts() {
try {
const contacts = await Contact.find();
return contacts;
} catch (error) {
console.error("Błąd podczas pobierania kontaktów:", error.message);
throw error;
}
}

async function getContactById(id) {
try {
const contact = await Contact.findById(id);
if (!contact) {
return null;
}
return contact;
} catch (error) {
console.error("Błąd podczas pobierania kontaktu:", error.message);
}
}

async function removeContact(id) {
try {
const deleted = await Contact.findByIdAndDelete(id);
if (!deleted) {
return null;
}
return `Usunięto kontakt: ${deleted}`;
} catch (error) {
console.error("Błąd podczas usuwania kontaktu:", error.message);
}
}

const getContactById = async (contactId) => {}
async function addContact(newContactData) {
try {
const newContact = await Contact.create(newContactData);
return `Dodano nowy kontakt: ${newContact}`;
} catch (error) {
console.error("Błąd podczas tworzenia kontaktu:", error.message);
}
}

const removeContact = async (contactId) => {}
async function updateContact(id, updateFields) {
try {
const contactExists = await Contact.findById(id);
if (!contactExists) {
return null;
}
const updatedContact = await Contact.findByIdAndUpdate(
id,
updateFields,
{ new: true, runValidators: true }
);
return `Zaktualizowano kontakt: ${updatedContact}`;
} catch (error) {
console.error("Błąd podczas aktualizacji kontaktu:", error.message);
}
}

const addContact = async (body) => {}
async function updateStatusContact(id, favorite) {
try {
const contactExists = await Contact.findById(id);
if (!contactExists) {
return null;
}

const updateContact = async (contactId, body) => {}
const updatedContact = await Contact.findByIdAndUpdate(
id,
{ favorite },
{ new: true, runValidators: true }
);

module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
return `Zaktualizowano status kontaktu: ${updatedContact}`;
} catch (error) {
console.error(
"Błąd podczas aktualizacji statusu kontaktu:",
error.message
);
}
}

module.exports = {
addContact,
listContacts,
getContactById,
updateContact,
removeContact,
updateStatusContact,
};
62 changes: 0 additions & 62 deletions models/contacts.json

This file was deleted.

9 changes: 9 additions & 0 deletions models/validation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const Joi = require("joi");

const contactSchema = Joi.object({
name: Joi.string().min(3).max(30).required(),
email: Joi.string().email().required(),
phone: Joi.string().min(10).max(15).required(),
});

module.exports = { contactSchema };
Loading