opt-cc/server/routes/account.js

97 lines
3.0 KiB
JavaScript
Raw Normal View History

2018-03-12 09:26:44 +01:00
'use strict';
2017-06-08 19:46:36 +02:00
// modules
const express = require('express');
// HTTP status codes by name
const codes = require('./http-codes');
const routerHandling = require('../middleware/router-handling');
// Mongoose Model using mongoDB
const AppUserModel = require('../models/app-user');
const account = new express.Router();
2017-06-08 19:46:36 +02:00
account.route('/')
2018-02-26 09:04:27 +01:00
.get((req, res, next) => {
AppUserModel.find({}, {}, {sort: {username: 1}})
.populate('squad')
.exec((err, items) => {
if (err) {
err.status = codes.servererror;
return next(err);
}
res.locals.items = items;
res.locals.processed = true;
next();
});
2018-02-26 09:04:27 +01:00
})
.all(
routerHandling.httpMethodNotAllowed
);
2017-06-08 19:46:36 +02:00
// routes **********************
account.route('/:id')
.get((req, res, next) => {
AppUserModel.findById(req.params.id)
.populate('squad')
.exec((err, item) => {
if (err) {
err.status = codes.servererror;
} else if (!item) {
err = new Error('item not found');
err.status = codes.notfound;
}
res.locals.items = item;
next(err);
});
})
2018-02-26 09:04:27 +01:00
.patch((req, res, next) => {
if (!req.body || (req.body._id && req.body._id !== req.params.id)) {
const err = new Error(
'id of PATCH resource and send JSON body are not equal ' + req.params.id + ' ' + req.body._id);
2018-02-26 09:04:27 +01:00
err.status = codes.notfound;
return next(err);
2018-02-26 09:04:27 +01:00
}
2017-06-08 19:46:36 +02:00
2018-02-26 09:04:27 +01:00
req.body.updatedAt = new Date();
req.body.$inc = {__v: 1};
2017-06-08 19:46:36 +02:00
AppUserModel.findByIdAndUpdate(req.params.id, req.body, {new: true})
.populate('squad')
.exec((err, item) => {
if (err) {
err.status = codes.wrongrequest;
} else if (!item) {
err = new Error('appUser not found');
err.status = codes.notfound;
} else {
res.locals.items = item;
}
next(err);
});
2018-02-26 09:04:27 +01:00
})
2017-06-08 19:46:36 +02:00
2018-02-26 09:04:27 +01:00
.delete((req, res, next) => {
AppUserModel.findByIdAndRemove(req.params.id, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
2018-03-12 09:26:44 +01:00
} else if (!item) {
err = new Error('item not found');
2018-02-26 09:04:27 +01:00
err.status = codes.notfound;
}
res.locals.processed = true;
next(err);
2018-02-26 09:04:27 +01:00
});
})
2017-06-08 19:46:36 +02:00
2018-02-26 09:04:27 +01:00
.all(
routerHandling.httpMethodNotAllowed
);
2017-06-08 19:46:36 +02:00
account.use(routerHandling.emptyResponse);
module.exports = account;