Skip to content

Commit

Permalink
Added Sequelize CLI. Created migrations, moved models based on defaul…
Browse files Browse the repository at this point in the history
…t used by Sequelize. Changed references. Added MODELS readme.
  • Loading branch information
bradf83 committed Oct 29, 2019
1 parent 9973e49 commit cd2c9d6
Show file tree
Hide file tree
Showing 16 changed files with 563 additions and 106 deletions.
37 changes: 37 additions & 0 deletions MODELS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Models

## Getting Started

- Ensure that sequelize-cli is installed (should be already due to yarn install)
```
yarn add sequelize-cli
npx sequelize-cli init
```

Creates a default project structure with a config, migrations, models and seeders directory.

## Generating a model

Generate the basic model. Associations will be done in a separate migration.

```
npx sequelize-cli model:generate --name Owner --attributes firstName:string,lastName:string
```

### Adding Associations

Generate a migration for an association.

```
npx sequelize-cli migration:generate --name add-some-assocation
```

Add the up and down portions of the migration. Check the association documentation for more details.

## Run Migrations

1. Run all your migrations using `npx sequelize-cli db:migrate`.
1. Revert a migration by using `npx sequelize-cli db:migrate:undo`.
1. Revert all migrations by using `npx sequelize-cli db:migrate:undo:all`


26 changes: 26 additions & 0 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"development": {
"username": "postgres",
"password": null,
"database": "postgres",
"host": "127.0.0.1",
"port": 5433,
"dialect": "postgres"
},
"test": {
"username": "postgres",
"password": null,
"database": "postgres",
"host": "127.0.0.1",
"port": 5433,
"dialect": "postgres"
},
"production": {
"username": "postgres",
"password": null,
"database": "postgres",
"host": "127.0.0.1",
"port": 5433,
"dialect": "postgres"
}
}
30 changes: 30 additions & 0 deletions migrations/20191029210043-create-owner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Owners', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Owners');
}
};
36 changes: 36 additions & 0 deletions migrations/20191029210201-create-company.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Companies', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
chargesGST: {
type: Sequelize.BOOLEAN
},
chargesPST: {
type: Sequelize.BOOLEAN
},
code: {
type: Sequelize.STRING
},
name: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Companies');
}
};
26 changes: 26 additions & 0 deletions migrations/20191029210549-add-owner-company-assoications.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.addColumn(
'Companies',
'OwnerId',
{
type: Sequelize.INTEGER,
references: {
model: 'Owners',
key: 'id'
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
}
)
},

down: (queryInterface, Sequelize) => {
return queryInterface.removeColumn(
'Companies',
'OwnerId'
)
}
};
13 changes: 13 additions & 0 deletions models/company.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const Company = sequelize.define('Company', {
chargesGST: DataTypes.BOOLEAN,
chargesPST: DataTypes.BOOLEAN,
code: DataTypes.STRING,
name: DataTypes.STRING
}, {});
Company.associate = function(models) {
Company.belongsTo(models.Owner);
};
return Company;
};
37 changes: 37 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
11 changes: 11 additions & 0 deletions models/owner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const Owner = sequelize.define('Owner', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING
}, {});
Owner.associate = function(models) {
Owner.hasMany(models.Company);
};
return Owner;
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"dotenv": "^8.2.0",
"express": "^4.17.1",
"pg": "^7.12.1",
"sequelize": "^5.21.1"
"sequelize": "^5.21.1",
"sequelize-cli": "^5.5.1"
},
"scripts": {
"start": "nodemon --exec babel-node src/index.js",
Expand Down
16 changes: 7 additions & 9 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import routes from "./routes";
import models, {sequelize} from "./models";
import db from '../models';

const app = express();

Expand All @@ -14,21 +14,19 @@ app.use(express.urlencoded({ extended: true })); // Sent via HTML Form
// Custom Middleware (TODO: Should this be done like this?)
app.use((req, res, next) => {
req.context = {
models,
db,
};
next();
});


// Routes
app.use('/companies', routes.company);
app.use('/owners', routes.owner);

// Sequelize and then start server
sequelize.sync().then(async () => {
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}.`)
);
});
// TODO: Consider checking the db to ensure we connect before starting the server.

app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}.`)
);


32 changes: 0 additions & 32 deletions src/models/company.js

This file was deleted.

23 changes: 0 additions & 23 deletions src/models/index.js

This file was deleted.

26 changes: 0 additions & 26 deletions src/models/owner.js

This file was deleted.

4 changes: 2 additions & 2 deletions src/routes/company.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { Router } from 'express';
const router = Router();

router.get('/', async (req, res) => {
const companies = await req.context.models.Company.findAll({include: [{model: req.context.models.Owner}]});
const companies = await req.context.db.Company.findAll({include: [{model: req.context.db.Owner}]});
return res.status(200).json(companies);
});

router.get('/:id', async (req, res) => {
//TODO: If nothing is found.
const company = await req.context.models.Company.findByPk(req.params.id);
const company = await req.context.db.Company.findByPk(req.params.id);
return res.status(200).json(company);
});

Expand Down
4 changes: 2 additions & 2 deletions src/routes/owner.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { Router } from 'express';
const router = Router();

router.get('/', async (req, res) => {
const owners = await req.context.models.Owner.findAll();
const owners = await req.context.db.Owner.findAll();
return res.status(200).json(owners);
});

router.get('/:id', async (req, res) => {
//TODO: If nothing is found.
const owner = await req.context.models.Owner.findByPk(req.params.id);
const owner = await req.context.db.Owner.findByPk(req.params.id);
return res.status(200).json(owner);
});

Expand Down
Loading

0 comments on commit cd2c9d6

Please sign in to comment.