add add/find query parameters in controller/routes

This commit is contained in:
Francesco Esposito 2019-02-20 09:39:54 +01:00
parent 88d8f40ee3
commit 721e72c460
2 changed files with 32 additions and 8 deletions

View File

@ -5,7 +5,8 @@ const router = express.Router();
router
.route('/devices')
.get(deviceController.index);
.get(deviceController.index)
.post(deviceController.add);
router
.route('/devices/:deviceId')

View File

@ -1,14 +1,24 @@
const Device = require('../models/deviceModel');
function index(req, res) {
if (req.query.name) {
console.log(req.query.name);
Device.findOne({ name: req.query.name }, (err, device) => {
if (!device) {
res.status(404).send();
} else {
res.json(device);
}
});
} else {
Device.get((err, devices) => {
if (err) {
res.status(500).send();
}
res.json(devices);
});
}
}
function view(req, res) {
Device.findById(req.params.deviceId)
@ -29,6 +39,18 @@ function update(req, res) {
});
}
function add(req, res) {
const device = new Device(req.body);
device
.save()
.then((item) => {
res.status(201).json(item);
})
.catch((err) => {
res.status(500).send();
});
}
function remove(req, res) {
Device.deleteOne({ _id: req.params.deviceId }, (err) => {
if (err) {
@ -41,4 +63,5 @@ function remove(req, res) {
module.exports.index = index;
module.exports.view = view;
module.exports.update = update;
module.exports.add = add;
module.exports.remove = remove;