1
0
Fork 0
mirror of https://github.com/mmumshad/ansible-playable.git synced 2025-02-15 04:42:05 +00:00
ansible-playable/server/api/thing/thing.controller.js
Mumshad Mannambeth c92f737237 Initial Commit
2017-06-07 13:36:45 -04:00

118 lines
2.8 KiB
JavaScript

/**
* Using Rails-like standard naming convention for endpoints.
* GET /api/things -> index
* POST /api/things -> create
* GET /api/things/:id -> show
* PUT /api/things/:id -> upsert
* PATCH /api/things/:id -> patch
* DELETE /api/things/:id -> destroy
*/
'use strict';
import jsonpatch from 'fast-json-patch';
import Thing from './thing.model';
function respondWithResult(res, statusCode) {
statusCode = statusCode || 200;
return function(entity) {
if(entity) {
return res.status(statusCode).json(entity);
}
return null;
};
}
function patchUpdates(patches) {
return function(entity) {
try {
// eslint-disable-next-line prefer-reflect
jsonpatch.apply(entity, patches, /*validate*/ true);
} catch(err) {
return Promise.reject(err);
}
return entity.save();
};
}
function removeEntity(res) {
return function(entity) {
if(entity) {
return entity.remove()
.then(() => {
res.status(204).end();
});
}
};
}
function handleEntityNotFound(res) {
return function(entity) {
if(!entity) {
res.status(404).end();
return null;
}
return entity;
};
}
function handleError(res, statusCode) {
statusCode = statusCode || 500;
return function(err) {
res.status(statusCode).send(err);
};
}
// Gets a list of Things
export function index(req, res) {
return Thing.find().exec()
.then(respondWithResult(res))
.catch(handleError(res));
}
// Gets a single Thing from the DB
export function show(req, res) {
return Thing.findById(req.params.id).exec()
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
}
// Creates a new Thing in the DB
export function create(req, res) {
return Thing.create(req.body)
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
// Upserts the given Thing in the DB at the specified ID
export function upsert(req, res) {
if(req.body._id) {
Reflect.deleteProperty(req.body, '_id');
}
return Thing.findOneAndUpdate({_id: req.params.id}, req.body, {new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true}).exec()
.then(respondWithResult(res))
.catch(handleError(res));
}
// Updates an existing Thing in the DB
export function patch(req, res) {
if(req.body._id) {
Reflect.deleteProperty(req.body, '_id');
}
return Thing.findById(req.params.id).exec()
.then(handleEntityNotFound(res))
.then(patchUpdates(req.body))
.then(respondWithResult(res))
.catch(handleError(res));
}
// Deletes a Thing from the DB
export function destroy(req, res) {
return Thing.findById(req.params.id).exec()
.then(handleEntityNotFound(res))
.then(removeEntity(res))
.catch(handleError(res));
}