trackmyd-api/controllers/deviceController.js

73 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-02-19 19:21:19 +01:00
const Device = require('../models/deviceModel');
2019-02-20 11:09:57 +01:00
const logger = require('../logger');
2019-02-19 19:21:19 +01:00
function index(req, res) {
if (req.query.name) {
Device.findOne({ name: req.query.name }, (err, device) => {
if (!device) {
2019-02-20 11:09:57 +01:00
logger.logError(`index: ${err}`);
return res.status(404).send();
}
2019-02-20 11:09:57 +01:00
return res.json(device);
});
} else {
2019-02-22 10:09:38 +01:00
Device.find({}, (err, devices) => {
if (err) {
2019-02-20 11:09:57 +01:00
logger.logError(`index: ${err}`);
return res.status(500).send();
}
2019-02-22 10:09:38 +01:00
if (devices.length === 0) {
return res.status(404).send();
}
2019-02-20 11:09:57 +01:00
return res.json(devices);
});
}
2019-02-19 19:21:19 +01:00
}
function view(req, res) {
Device.findById(req.params.deviceId)
2019-02-20 11:09:57 +01:00
.then(device => res.json(device))
.catch((err) => {
2019-02-20 11:09:57 +01:00
logger.logError(`view: ${err}`);
return res.status(500).send();
});
}
function update(req, res) {
Device.findOneAndUpdate({ _id: req.params.deviceId }, req.body, (err) => {
if (err) {
2019-02-20 11:09:57 +01:00
logger.logError(`update: ${err}`);
return res.status(500).send();
}
2019-02-20 11:09:57 +01:00
return res.status(200).send();
});
}
function add(req, res) {
const device = new Device(req.body);
device
.save()
2019-02-20 11:09:57 +01:00
.then(item => res.status(201).json(item))
.catch((err) => {
2019-02-20 11:09:57 +01:00
logger.logError(`add: ${err}`);
return res.status(500).send();
});
}
function remove(req, res) {
Device.deleteOne({ _id: req.params.deviceId }, (err) => {
if (err) {
2019-02-20 11:09:57 +01:00
logger.logError(`delete: ${err}`);
return res.status(500).send();
}
2019-02-20 11:09:57 +01:00
return res.status(200).send();
});
}
2019-02-19 19:21:19 +01:00
module.exports.index = index;
module.exports.view = view;
module.exports.update = update;
module.exports.add = add;
module.exports.remove = remove;