Skip to content

Instantly share code, notes, and snippets.

@philippeauriach
Created December 4, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philippeauriach/a79ff8bb17cd44647cf7 to your computer and use it in GitHub Desktop.
Save philippeauriach/a79ff8bb17cd44647cf7 to your computer and use it in GitHub Desktop.
Generate CRUD from sequelize models (missing validators, auth, etc... just for the idea)
'use strict';
module.exports = function(sequelize, DataTypes) {
var Fish = sequelize.define('Fish', {
scientificName: DataTypes.STRING,
bio: DataTypes.TEXT
}, {
classMethods: {
/*associate: function(models) {
// associations can be defined here
},*/
rest: {
path: 'fishes',
creationProperties: ['scientificName', 'bio']
}
}
});
return Fish;
};
var express = require('express');
var app = express();
//generate CRUD paths from a model. The model must have a rest property giving its path
module.exports = function(model) {
app.get('/', function(req, res){
model.findAll().then(function(entities){
return res.json(entities);
}).catch(function(err){
// TODO: error plus jolie
console.error(err);
return res.status(500).send();
});
});
app.get('/:id', function(req, res){
model.findById(req.params.id).then(function(entity){
if (entity) {
return res.json(entity);
}
return res.status(404).send();
}).catch(function(err){
// TODO: better error returning
console.error(err);
return res.status(500).send();
});
});
app.post('/', function(req, res){
model
.create(req.body, model.rest.creationProperties)
.then(function(entity){
// TODO: custom middleware to returned a correct code like created ?
return res.json(entity);
}).catch(function(err){
// TODO: better error handling
console.error(err);
return res.status(500).send();
});
});
// TODO: PUT
return app;
};
var _ = require('underscore');
var express = require('express');
var dbModels = require('../db/models');
var modelRoutesCreator = require('./model-routes-creator.jsx');
var models = dbModels.sequelize.models;
var app = module.exports = express();
_.values(models).forEach(function(model){
if(model.rest) {
if(model.rest.path){
var modelRoutes = modelRoutesCreator(model);
app.use(model.rest.path, modelRoutes);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment