diff --git a/index.js b/index.js index 043a956..cdd8a59 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ const expressMongoDb = require('./middleware/mongo'); const users = require('./routes/user'); const vehicles = require('./routes/vehicles'); const events = require('./routes/events'); +const notes = require('./routes/notes'); const app = express(); const bearerToken = require('express-bearer-token'); const jwt = require('./middleware/jwt'); @@ -33,6 +34,7 @@ app.use(jwt({ secret: process.env.JWT_SECRET_AUTH, exclude: ['/user/signup', '/u app.use('/user', users); app.use('/vehicles', vehicles); app.use('/events', events); +app.use('/notes', notes); // 404 for all unknown routes app.use((req, res) => { diff --git a/routes/notes.js b/routes/notes.js new file mode 100644 index 0000000..50a14f2 --- /dev/null +++ b/routes/notes.js @@ -0,0 +1,70 @@ +const express = require('express'); +const router = express.Router(); +const { makeError } = require('../utils/errors'); + +router.post('/', async (req, res) => { + const { number, notes } = req.body; + + try { + let collection = req.db.collection('vehicles'); + await collection.updateOne({ number }, { $push: { notes: { $each: notes } } }); + await collection.updateOne({ number }, { $set: { updatedDate: Date.now() } }); + let vehicle = await collection.findOne({ number }); + if(vehicle) { + res.send({ success: true, data: vehicle }); + } else { + res.send(makeError('There is no vehicle with such plate number')); + } + } catch(ex) { + res.send(makeError(ex.message)); + console.error(ex); + } +}); + +router.put('/', async (req, res) => { + const { note } = req.body; + + try { + let collection = req.db.collection('vehicles'); + let vehicle = await collection.findOne({ 'notes.id': note.id }); + if(vehicle) { + let index = vehicle.notes.findIndex(e => e.id == note.id); + if(index >= 0) { + vehicle.notes[index] = note; + await collection.updateOne({ number: vehicle.number }, { $set: { notes: vehicle.notes, updatedDate: Date.now() } }); + res.send({ success: true, data: vehicle }); + } else { + res.send(makeError('Note not found')); + } + } else { + res.send(makeError('There is no vehicle with such note')); + } + } catch(ex) { + res.send(makeError(ex.message)); + console.error(ex); + } +}); + +router.delete('/', async (req, res) => { + const { noteId } = req.body; + + try { + let collection = req.db.collection('vehicles'); + let vehicle = await collection.findOne({ 'notes.id': noteId }); + if(vehicle) { + let index = vehicle.notes.findIndex(e => e.id == noteId); + if(index >= 0) { + vehicle.notes.splice(index, 1); + await collection.updateOne({ number: vehicle.number }, { $set: { notes: vehicle.notes, updatedDate: Date.now() } }); + } + res.send({ success: true, data: vehicle }); + } else { + res.send(makeError('There is no vehicle with such note')); + } + } catch(ex) { + res.send(makeError(ex.message)); + console.error(ex); + } +}); + +module.exports = router; \ No newline at end of file