Skip to content

Instantly share code, notes, and snippets.

@domachine
Last active December 11, 2015 15:40
Show Gist options
  • Save domachine/91bd7ea4137ff383cdae to your computer and use it in GitHub Desktop.
Save domachine/91bd7ea4137ff383cdae to your computer and use it in GitHub Desktop.
A simple POC for a generic mongo json API
var express = require('express');
var mongoose = require('mongoose');
var error = require('http-errors');
require('./posts');
var api = express();
api.get('/:collection', (req, res, next) => {
let Model = getModel(req);
Model.access({
user: req.user,
method: 'collection',
args: [req.query]
}, load);
function loadCollection(err) {
if (err) return next(err);
Model.find(JSON.parse(req.query.query), sendResult);
}
function sendResult(err, results) {
if (err) return next(err);
res.send(results);
}
});
api.get('/:collection/:id', (req, res, next) => {
let Model = getModel(req);
Model.access(req.user, 'object', [req.params.id], err => {
if (err) return next(err);
Model.findById(req.params.id, (err, result) => {
if (err) return next(err);
res.send(result);
});
});
});
api.post('/:collection', (req, res, next) => {
let Model = getModel(req);
let object = new Model(req.body);
Model.access(req.user, 'save', [], err => {
if (err) return next(err);
object.save((err, result) => {
if (err) return next(err);
res.send(result);
});
});
});
api.put('/:collection/:id', (req, res, next) => {
let Model = getModel(req);
Model.findById(req.params.id, (err, object) => {
if (err) return next(err);
if (!object) return next(error(404));
for (var key in req.body) {
if (!req.body.hasOwnProperty(key)) continue;
object[key] = req.body[key];
}
Model.access(req.user, 'save', [], err => {
if (err) return next(err);
object.save((err, result) => {
if (err) return next(err);
res.send(result);
})
});
});
});
function getModel(req) {
let Model = mongoose.model(req.params.collection);
if (typeof Model.access !== 'function') throw error(404);
return Model;
}
var mongoose = require('mongoose');
var error = require('http-errors');
var schema = new mongoose.Schema({
title: String,
content: String
});
schema.statics.access = function(user, action, args, next) {
switch (action) {
case 'save':
if (user.role !== 'admin') return next(error(403, 'Only admins can save.'));
case 'object':
if (user.role !== 'admin' && user.role !== 'author') {
return next(error(403, 'Only authors and admins can access details.'));
}
default:
next();
}
}
module.exports = mongoose.model('posts', schema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment