Adding API for notes

This commit is contained in:
Selim Mustafaev 2021-09-10 01:23:52 +03:00
parent e9838a72e9
commit 686c6aba40
2 changed files with 72 additions and 0 deletions

View File

@ -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) => {

70
routes/notes.js Normal file
View File

@ -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;