Skip to content

Instantly share code, notes, and snippets.

@cyppan
Created December 7, 2018 14:19
Show Gist options
  • Save cyppan/aef96247930968536c0d5f03d91b354b to your computer and use it in GitHub Desktop.
Save cyppan/aef96247930968536c0d5f03d91b354b to your computer and use it in GitHub Desktop.
serve-sequelize
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const {
connect, syncDb, buildAndRegisterModel, setupAssociations, mapException, mapQueryParams
} = require('serve-sequelize');
const app = express();
const sequelize = connect({
database: "app",
username: "user",
password: "secret",
host: "127.0.0.1",
dialect: "postgres",
});
syncDb(sequelize);
const listResource = {
name: 'List',
path: '/lists',
schema: {
name: {
type: 'string',
allowNull: false,
validate: {
matches: ["^[a-z0-9 -_]+$",'i'],
len: [3, 80],
},
},
},
associations: {
hasMany: [{
resource: 'Todo',
}],
},
operations: ['get', 'post', 'put', 'patch', 'delete'],
};
const listModel = buildAndRegisterModel(listResource, sequelize);
const todoResource = {
name: 'Todo',
path: '/todos',
schema: {
title: {
type: 'string',
allowNull: false,
validate: {
is: ["^[a-zA-Z0-9]+$",'i'],
len: [2, 500],
},
},
completed: {
type: 'boolean',
allowNull: true,
},
},
associations: {
belongsTo: [{
resource: 'List'
}],
},
operations: ['get', 'post', 'put', 'patch', 'delete'],
};
const todoModel = buildAndRegisterModel(todoResource, sequelize);
setupAssociations([listResource, todoResource], sequelize);
app.use(bodyParser.json())
app.use('*', cors({
origin: (origin, callback) => callback(null, true)
}))
app.use(mapQueryParams)
app.resource(todoResource, sequelize)
app.resource(listResource, sequelize)
app.use(mapException)
app.listen(3000, () => {
console.log('Example app listening on port 3000!')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment