Skip to content

Instantly share code, notes, and snippets.

@fourestfire
Last active April 7, 2017 14:55
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 fourestfire/ce94741bf0b08ae069e04eac032b7297 to your computer and use it in GitHub Desktop.
Save fourestfire/ce94741bf0b08ae069e04eac032b7297 to your computer and use it in GitHub Desktop.
Common code patterns for express and sequelize

Sequelize Boilerplate (/models folder)

in db:
const Sequelize = require('sequelize');
const chalk = require('chalk');
console.log(chalk.yellow('Opening connection to PostgreSQL'));

// create the database instance
const db = new Sequelize('postgres://localhost:5432/name_of_database', {
  logging: false, // set to console.log to see the raw SQL queries
  native: true // lets Sequelize know we can use pg-native for ~30% more speed
});

module.exports = db;
to require database lookups in express routes

const Chapter = require('../models/chapter')

in index.js, do associations
const Book = require('./book');
const Chapter = require('./chapter');
const db = require('./db');

Book.hasMany(Chapter);
Chapter.belongsTo(Book);
Artist.belongsToMany(Song, { through: 'artistSong' });
Song.belongsToMany(Artist, { through: 'artistSong' });

module.exports = {
  Book,
  Chapter,
  Song,
  Artist,
  db
};
in book.js, do db.define
const Sequelize = require('sequelize');

const db = require('./_db');

const Book = db.define('book', {
  title: Sequelize.STRING
}, {
  timestamps: false
});

module.exports = Book;

Express Boilerplate

in app.js
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
module.exports = app;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(session({
  // this mandatory configuration ensures that session IDs are not predictable
  secret: 'omri-omri-omri', // or whatever you like
  // these options are recommended and reduce session concurrency issues
  resave: false,
  saveUninitialized: false
  })
);
// this is if you want to serve up index.html in files route. will look within current directory/public/static
app.use('/files', express.static(path.join(__dirname, 'public/static'))); 

// this will allow us to use a router, goes to index.js in routes folder
app.use('/api/books', require('./routes')); 
index.js in /routes folder
'use strict';
/* eslint-disable new-cap */

const router = require('express').Router();
module.exports = router;

const Book = require('../models/book')

router.use('/:bookId/chapters/', function (req, res, next) {
  req.bookId = req.params.bookId;  // allows us to pass req.bookId over to chapters
  next();
}, require('./chapters.js'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment