Skip to content

Instantly share code, notes, and snippets.

@matt-winzer
Last active July 25, 2018 16:33
Show Gist options
  • Save matt-winzer/df84252f9ba070428b41fcb1117f21b1 to your computer and use it in GitHub Desktop.
Save matt-winzer/df84252f9ba070428b41fcb1117f21b1 to your computer and use it in GitHub Desktop.

Server & Database Master Setup (express-generator)

Dependencies

You will need express-generator installed globally to have access to the 'express' cli command

npm install -g express-generator

Initial Setup

  • Create a GitHub repo
  • Clone the repo and cd into it

Console:

express --view=hbs --git
npm install pg knex dotenv
knex init
createdb *database-name*
touch .env

In .gitignore file:

node_modules
.env

Knex: Environment Configuration

In knexfile.js

require('dotenv').config();

module.exports = {
  development: {
    client: 'pg',
    connection: 'postgres://localhost/*database-name*'
  },

  production: {
    client: 'pg',
    connection: process.env.DATABASE_URL + '?ssl=true'
  }
};

Console:

mkdir db
cd db
touch connection.js

In connection.js

// Set our environment
const environment = process.env.NODE_ENV || 'development'

// Use connection info from knexfile
const config = require('../knexfile')

// Coordinate the two above
const configEnv = config[environment]

// Bring in knex as a library
const knex = require('knex')

// Put it all together
const connection = knex(configEnv)

// Export so we can use it in our routes
module.exports = connection

Knex: Migrations

Console:

knex migrate:make 01_migration_name

Migration file should look something like:

exports.up = function(knex, Promise) {
  return knex.schema.createTable('member', (table) =>{
  table.increments();
  table.text('username').notNullable().unique();
  table.text('email').notNullable().unique();
  table.text('password').notNullable();
  table.date('dateCreated').notNullable().defaultTo(new Date);
  table.boolean('isActive').notNullable().defaultTo(true);
  table.text('bio');
  })
};

// express knex 4 lyfe

exports.down = function(knex, Promise) {
  return knex.schema.dropTableIfExists('member');
};

Foreign Key relationships are handled as such:

table.integer('memberID').references('member.id').unsigned().onDelete('cascade')

Run migration

knex migrate:latest
  • Continue making migrations for all the tables in your database

Knex: Seeds

Console:

knex seed:make 01_seed_name

Seed file should look something like:

var bcrypt = require('bcrypt');

exports.seed = function(knex, Promise) {
  // Deletes ALL existing entries
  return knex.raw('DELETE FROM "user"; ALTER SEQUENCE user_id_seq RESTART WITH 3;')
    .then(function () {
      var users = [{
        id: 1,
        name: 'sam',
        email: 'sam@gmail.com',
        password: bcrypt.hashSync('sammyg21', 10)

      }, {
        id: 2,
        name: 'alex',
        email: 'alex@gmail.com',
        password: bcrypt.hashSync('alexmart05', 10)
      }];
      return knex('user').insert(users);
    });
};

Run seed

knex seed:run
  • Keep creating seeds and running them until your entire database is seeded

Require Knex

In your routes file make sure to require knex

const knex = require('../db/connection');

Do the same in your app.js file if you plan to write knex queries there:

const knex = require('../db/connection');

CORS

Install CORS module

npm install cors

In app.js

const cors = require('cors');

// Make sure the following line is above your routes
app.use(cors());

FIN

Fin.

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