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

const contactsRouter = require('./routes/api/contacts')

const app = express()

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

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

app.use('/api/contacts', contactsRouter)

// 1️⃣ Załaduj zmienne środowiskowe z pliku .env
require('dotenv').config();

const express = require('express');
const logger = require('morgan');
const cors = require('cors');
const mongoose = require('mongoose');

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

const app = express();

// 2️⃣ Połączenie z MongoDB
const DB_HOST = process.env.MONGO_URI;

if (!DB_HOST) {
console.error('❌ Brak zmiennej środowiskowej MONGO_URI w pliku .env');
process.exit(1);
}

mongoose.connect(DB_HOST)
.then(() => {
console.log('✅ Database connection successful');

// 3️⃣ Uruchomienie serwera po połączeniu z MongoDB
const PORT = process.env.PORT || 3001; // Użyj zmiennej środowiskowej lub domyślnie port 3001
app.listen(PORT, () => {
console.log(`🚀 Server running on http://localhost:${PORT}`);
});
})
.catch(error => {
console.error('❌ Database connection error:', error.message);
process.exit(1);
});

// 4️⃣ Middleware
const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short';
app.use(logger(formatsLogger));
app.use(cors());
app.use(express.json());

// 5️⃣ Routes
app.use('/api/contacts', contactsRouter);

// 6️⃣ Obsługa błędów
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 })
})
console.error('❌ Internal server error:', err); // Dodano logowanie błędu
res.status(500).json({ message: err.message });
});

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


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

const getContactById = async (req, res) => {
const { contactId } = req.params;
const contact = await Contact.findById(contactId);
if (!contact) {
return res.status(404).json({ message: 'Not found' });
}
res.json(contact);
};

const addContact = async (req, res) => {
const newContact = await Contact.create(req.body);
res.status(201).json(newContact);
};

const updateContact = async (req, res) => {
const { contactId } = req.params;
const updatedContact = await Contact.findByIdAndUpdate(contactId, req.body, { new: true });
if (!updatedContact) {
return res.status(404).json({ message: 'Not found' });
}
res.json(updatedContact);
};

const deleteContact = async (req, res) => {
const { contactId } = req.params;
const deletedContact = await Contact.findByIdAndDelete(contactId);
if (!deletedContact) {
return res.status(404).json({ message: 'Not found' });
}
res.json({ message: 'Contact deleted' });
};

const updateStatusContact = async (contactId, body) => {
return await Contact.findByIdAndUpdate(contactId, body, { new: true });
};

module.exports = {
getAllContacts,
getContactById,
addContact,
updateContact,
deleteContact,
updateStatusContact,
};
35 changes: 19 additions & 16 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
// const fs = require('fs/promises')
const { Schema, model } = require('mongoose');

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

const getContactById = async (contactId) => {}
const Contact = model('Contact', contactSchema);

const removeContact = async (contactId) => {}

const addContact = async (body) => {}

const updateContact = async (contactId, body) => {}

module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
}
module.exports = Contact;
Loading