Skip to content

Instantly share code, notes, and snippets.

@jmporchet
Last active August 27, 2017 17:23
Show Gist options
  • Save jmporchet/2dda5fa8f31ba824cb5409ad23a99d44 to your computer and use it in GitHub Desktop.
Save jmporchet/2dda5fa8f31ba824cb5409ad23a99d44 to your computer and use it in GitHub Desktop.

Express and Sequelize

Install

$ mkdir myapp
$ cd myapp
$ npm init #follow instructions - wizard app
$ git init
$ npm i express

Entry point

Create an index.js file, this will contain the bootstrap of your app.

const express = require('express')
const app = express()

// here will go the routing

app.listen(3000, () => {
  console.log('App started and listening on port 3000')
})

Setting up commands and running

Add start and dev commands to your package.json file so you can run your app executing npm start and npm run dev in your terminal.

// package.json

"scripts": {
  "start": "node index.js",
  "dev": "nodemon index.js"
}

Routing

Now its time to define your routes. Go to the index.js file before the listen command. It's time to define our routes:

app.get('/', (req, res, next) => {
  res.send('Hello World')
})

You can run get, post, put and delete functions for defining your methods. Also, you can pass a function reference so you write the function in another file.

const entitiesController = require('./controllers/entities.controller')

app.get('/entities', entitiesController.getEntities)
app.post('/entities', entitiesController.createEntity)
app.get('/entities/:id', entitiesController.getEntity)
// req.params.id will be available on entitiesController.getEntity call

Pay attention, this function is referenced, not executed. The router will execute it when our app receives a request.

Express routing is very powerful, you have a full guide in here

The Controller

The controller is the object or class that contains our middlewares (business logic).

const getEntities = (req, res) => {
  // Retrieve data from the database
  res.send(/*response content*/)
}

const createEntity = (req, res) => {
  // Write data to the database
  res.send(/*response content*/)
}

modules.exports = {
  getEntities: getEntities,
  createEntity: createEntity
}

// OR using ES6 construction
// modules.exports = {
//   getEntities,
//   createEntity
// }

The Model

In here we're going full opinionated, we're deciding to work with SQLite and sequelize (totally outside the express domain).

npm i sequelize

Create a db.js file in the root folder and connect to the db in it. You only have to import it from the index.js (require('db'))

// ./utils/db.js

const Sequelize = require('sequelize');

const sequelize = new Sequelize('entity', null, null, {
  host: 'localhost',
  dialect: 'sqlite',
  storage: './myDB.sqlite'
});

sequelize
  .authenticate()
  .then(() => {
    console.log('Database connection established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

module.exports = sequelize;

Then you can create your model file in models/entity.js and create the schema in it.

// models/entity.js
const Sequelize = require('sequelize');
const sequelize = require('../utils/db');
const Console = console;

const Entity = sequelize.define('entity', {
  info: {
    type: Sequelize.STRING
  }
});

module.exports.getEntities = async () => {
  try {
    return await this.entity.findAll();
  } catch (error) {
    Console.error(error);
  }
};

module.exports.getNextEntity = async () => {
  try {
    return await this.entity.findOne({ order: [ ['date', 'ASC']]});
  } catch (error) {
    Console.error(error);
  }
};

module.exports.createEntity = async (info) => {
  const date = new Date();
  try {
    return await this.entity.create({info: info, date});
  } catch (error) {
    Console.error(error);
  }
};

module.exports.deleteEntity = async (id) => {
  try {
    return await this.entity.destroy({ where: { id: id } });
  } catch (error) {
    Console.error(error);
  }
};

Finally, require it in your controller and start working with the db data!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment