231 lines
6.4 KiB
JavaScript
231 lines
6.4 KiB
JavaScript
require('dotenv').config();
|
|
const express = require('express');
|
|
const mongoose = require('mongoose');
|
|
const app = express();
|
|
const cors = require('cors');
|
|
|
|
app.use(cors(), express.json());
|
|
|
|
const port = process.env.PORT || 5000;
|
|
|
|
const DB_HOST = process.env.DB_HOST || 'server';
|
|
const DB_PORT = process.env.DB_PORT || 27017;
|
|
const DB_USERNAME = process.env.DB_USERNAME;
|
|
const DB_PASSWORD = process.env.DB_PASSWORD;
|
|
|
|
const connectionString = `mongodb://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}?authMechanism=DEFAULT`;
|
|
mongoose.connect(connectionString);
|
|
const db = mongoose.connection;
|
|
|
|
db.on('error', console.error.bind(console, 'connection error:'));
|
|
db.once('open', function () {
|
|
console.log(`connected to mongodb: ${DB_HOST}`);
|
|
});
|
|
/*------------MODELS------------*/
|
|
//create schema
|
|
var itemSchema = new mongoose.Schema({
|
|
name: String,
|
|
description: String,
|
|
quantity: Number
|
|
});
|
|
|
|
var boxSchema = new mongoose.Schema({
|
|
name: String,
|
|
description: String,
|
|
items: [itemSchema],
|
|
sort: Number,
|
|
color: String,
|
|
});
|
|
|
|
//compile schema into model
|
|
var Box = mongoose.model('box', boxSchema, 'box');
|
|
var Item = mongoose.model('item', itemSchema, 'item');
|
|
/*------------/MODELS------------*/
|
|
|
|
/*------------CONTROLLER------------*/
|
|
app.listen(port, () => console.log(`Listening on port ${port}`));
|
|
|
|
// get all boxes
|
|
app.get('/boxes', async (request, response) => {
|
|
const boxes = await getAllBoxes();
|
|
response.send(boxes);
|
|
});
|
|
|
|
// create box
|
|
app.post('/boxes', async (request, response) => {
|
|
try {
|
|
const numBoxes = await Box.countDocuments();
|
|
const newBox = await Box.create({
|
|
...request.body,
|
|
sort: numBoxes,
|
|
});
|
|
|
|
response.status(201).json(newBox);
|
|
}
|
|
catch (error) {
|
|
console.error('Error creating box:', error);
|
|
response.status(500).json({ error: 'Failed to create box' });
|
|
}
|
|
});
|
|
|
|
// update box
|
|
app.put('/boxes/:boxId', async (request, response) => {
|
|
try {
|
|
const { boxId } = request.params;
|
|
const updatedBox = await Box.findByIdAndUpdate(
|
|
boxId,
|
|
{ ...request.body },
|
|
{ new: true, runValidators: true }
|
|
);
|
|
|
|
if (!updatedBox) {
|
|
return response.status(404).json({ error: 'Box not found' });
|
|
}
|
|
|
|
response.status(200).json(updatedBox);
|
|
}
|
|
catch (error) {
|
|
console.error('Error updating box:', error);
|
|
response.status(500).json({ error: 'Failed to update box' });
|
|
}
|
|
});
|
|
|
|
|
|
// delete box
|
|
app.delete('/boxes/:boxId', async (request, response) => {
|
|
try {
|
|
const { boxId } = request.params;
|
|
const result = await Box.findByIdAndDelete(boxId);
|
|
|
|
if (!result) {
|
|
return response.status(404).json({ success: false, message: 'Box not found' });
|
|
}
|
|
|
|
response.status(200).json({ success: true, message: 'Box deleted', data: result });
|
|
}
|
|
catch (error) {
|
|
console.error('Error deleting box:', error);
|
|
response.status(500).json({ success: false, error: 'Failed to delete box' });
|
|
}
|
|
});
|
|
|
|
// create item
|
|
app.post('/boxes/:boxId/items', async (request, response) => {
|
|
try {
|
|
const item = new Item(request.body);
|
|
const savedItem = await item.save();
|
|
const box = await Box.findById(request.params.boxId);
|
|
if (!box) {
|
|
throw new Error('Box not found');
|
|
}
|
|
|
|
box.items.push(savedItem);
|
|
await box.save();
|
|
response.send(item);
|
|
} catch (error) {
|
|
console.error('Error adding item to Box:', error);
|
|
throw error;
|
|
}
|
|
|
|
});
|
|
// edit item
|
|
app.put('/boxes/:boxId/items/:itemId', async (request, response) => {
|
|
const { boxId, itemId } = request.params;
|
|
const { name, description, quantity } = request.body;
|
|
try {
|
|
const updatedBox = await Box.findOneAndUpdate(
|
|
{ _id: boxId, 'items._id': itemId },
|
|
{
|
|
$set: {
|
|
'items.$.name': name,
|
|
'items.$.description': description,
|
|
'items.$.quantity': quantity,
|
|
},
|
|
},
|
|
{ new: true }
|
|
);
|
|
const updatedItem = updatedBox.items.find(item => item._id.toString() === itemId);
|
|
|
|
if (!updatedItem) {
|
|
return response.status(404).json({ error: 'Box or item not found' });
|
|
}
|
|
|
|
response.status(200).json(updatedItem);
|
|
}
|
|
catch (error) {
|
|
console.error('Error updating item:', error);
|
|
response.status(500).json({ error: 'Failed to update item' });
|
|
}
|
|
});
|
|
|
|
// delete item from box
|
|
app.delete('/boxes/:boxId/items/:itemId', async (request, response) => {
|
|
const { boxId, itemId } = request.params;
|
|
|
|
try {
|
|
const updatedBox = await Box.findByIdAndUpdate(
|
|
boxId,
|
|
{
|
|
$pull: { items: { _id: itemId } }
|
|
},
|
|
{ new: true }
|
|
);
|
|
|
|
if (!updatedBox) {
|
|
return response.status(404).json({ error: 'Box not found' });
|
|
}
|
|
|
|
response.json(updatedBox);
|
|
}
|
|
catch (error) {
|
|
console.error('Error deleting item:', error);
|
|
response.status(500).json({ error: 'Failed to delete item' });
|
|
}
|
|
});
|
|
|
|
//move item
|
|
app.patch('/items/:itemId', async (req, res) => {
|
|
const { itemId } = req.params;
|
|
const { boxId: targetBoxId } = req.body;
|
|
|
|
if (!targetBoxId) return res.status(400).json({ error: 'Target boxId is required' });
|
|
|
|
const item = await Item.findById(itemId);
|
|
if (!item) return res.status(404).json({ error: 'Item not found' });
|
|
console.log(item);
|
|
|
|
const sourceBox = await Box.findOne({ "items._id": item._id });
|
|
const targetBox = await Box.findById(targetBoxId);
|
|
if (!targetBox) return res.status(404).json({ error: 'Target box not found' });
|
|
if (!sourceBox) return res.status(404).json({ error: 'Source box not found' });
|
|
|
|
|
|
await Box.updateOne(
|
|
{ _id: sourceBox._id },
|
|
{ $pull: { items: item } }
|
|
);
|
|
|
|
await Box.updateOne(
|
|
{ _id: targetBoxId },
|
|
{ $push: { items: item } }
|
|
);
|
|
|
|
res.status(204).send();
|
|
});
|
|
|
|
/*--------/CONTROLLER------------*/
|
|
|
|
const getAllBoxes = async (queryParameters) => {
|
|
queryParameters = queryParameters ?? {};
|
|
const data = await Box.find(queryParameters).sort({ sort: 1 });
|
|
return data;
|
|
}
|
|
|
|
const getBox = async (id) => {
|
|
const data = await Box.findById(id);
|
|
return data;
|
|
}
|
|
const getItem = async (id) => {
|
|
const data = await Item.findById(id);
|
|
return data;
|
|
} |