You are on page 1of 17

ORMs

ORMs

1 // $ npm install pg
2
3 const { Client } = require('pg');
4 const connection = require('./connection.json');
5 const client = new Client(connection);
6
7 client.connect();
8
9 const query = `SELECT
10 ingredient.*, item.name AS item_name, item.type AS item_type
11 FROM
12 ingredient
13 LEFT JOIN
14 item ON item.id = ingredient.item_id
15 WHERE
16 ingredient.dish_id = $1`;
17
18 client
19 .query(query, [1])
20 .then(res => {
21 console.log('Ingredients:');
22 for (let row of res.rows) {
23 console.log(`${row.item_name}: ${row.quantity} ${row.unit}`);
24 }
25
26 client.end();
27 });

PG: Non-blocking PostgreSQL client for Node.js. Pure JavaScript and optional native libpq
bindings.
ORMs
SEQUELIZE
SEQUELIZE

1 npm install --save sequelize


2 npm install --save pg pg-hstore # Postgres
SEQUELIZE

1 const Sequelize = require('sequelize');


2
3 // Option 1: Passing parameters separately
4 const sequelize = new Sequelize('database', 'username', 'password', {
5 host: 'localhost',
6 dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
7 });
8
9 // Option 2: Passing a connection URI
10 const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
SEQUELIZE - Models

1 const Model = Sequelize.Model;


2
3 class User extends Model {}
4 User.init({
5 // attributes
6 firstName: {
7 type: Sequelize.STRING,
8 allowNull: false
9 },
10 lastName: {
11 type: Sequelize.STRING
12 // allowNull defaults to true
13 }
14 }, {
15 sequelize,
16 modelName: 'user'
17 // options
18 });
SEQUELIZE - Models

1
2 const User = sequelize.define('user', {
3 // attributes
4 firstName: {
5 type: Sequelize.STRING,
6 allowNull: false
7 },
8 lastName: {
9 type: Sequelize.STRING
10 // allowNull defaults to true
11 }
12 }, {
13 // options
14 });
SEQUELIZE - Models

1 // Note: using `force: true` will drop the table if it already exists
2
3 User.sync({ force: true }).then(() => {
4 // Now the `users` table in the database corresponds to the model definition
5 return User.create({
6 firstName: 'John',
7 lastName: 'Hancock'
8 });
9 });
SEQUELIZE - Hooks

1 // Method 1 via the .init() method


2 class User extends Model {}
3 User.init({
4 username: DataTypes.STRING,
5 mood: {
6 type: DataTypes.ENUM,
7 values: ['happy', 'sad', 'neutral']
8 }
9 }, {
10 hooks: {
11 beforeValidate: (user, options) => {
12 user.mood = 'happy';
13 },
14 afterValidate: (user, options) => {
15 user.username = 'Toni';
16 }
17 },
18 sequelize
19 });
20
21 // Method 2 via the direct method
22 User.beforeCreate(async (user, options) => {
23 const hashedPassword = await hashPassword(user.password);
24 user.password = hashedPassword;
25 });
26
27 User.afterValidate('myHookAfter', (user, options) => {
28 user.username = 'Toni';
29 });// Note: using `force: true` will drop the table if it already exists
30
31 User.sync({ force: true }).then(() => {
32 // Now the `users` table in the database corresponds to the model definition
33 return User.create({
34 firstName: 'John',
35 lastName: 'Hancock'
36 });
37 });
SEQUELIZE - Getters

1 class Employee extends Model {}


2 Employee.init({
3 name: {
4 type: Sequelize.STRING,
5 allowNull: false,
6 get() {
7 const title = this.getDataValue('title');
8 // 'this' allows you to access attributes of the instance
9 return this.getDataValue('name') + ' (' + title + ')';
10 },
11 },
12 title: {
13 type: Sequelize.STRING,
14 allowNull: false,
15 set(val) {
16 this.setDataValue('title', val.toUpperCase());
17 }
18 }
19 }, { sequelize, modelName: 'employee' });
20
21 Employee
22 .create({ name: 'John Doe', title: 'senior engineer' })
23 .then(employee => {
24 console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
25 console.log(employee.get('title')); // SENIOR ENGINEER
26 })
SEQUELIZE - Relations

1 class Player extends Model {}


2 Player.init({/* attributes */}, { sequelize, modelName: 'player' });
3 class Team extends Model {}
4 Team.init({/* attributes */}, { sequelize, modelName: 'team' });
5
6 Player.belongsTo(Team);
7 // Will add a teamId attribute to Player to hold the primary key value for Team
8
9
10
11 Person.hasOne(Person, {as: 'Father'})
12 // this will add the attribute FatherId to Person
13
14 // also possible:
15 Person.hasOne(Person, {as: 'Father', foreignKey: 'DadId'})
16 // this will add the attribute DadId to Person
17
18 // In both cases you will be able to do:
19 Person.setFather()
20 Person.getFather()

1. BelongsTo
2. HasOne
SEQUELIZE - Relations

1 class User extends Model {}


2 User.init({/* ... */}, { sequelize, modelName: 'user' })
3 class Project extends Model {}
4 Project.init({/* ... */}, { sequelize, modelName: 'project' })
5
6 // First let's define a hasMany association
7 Project.hasMany(User, {as: 'Workers'});
8
9
10 // N x M
11 Project.belongsToMany(User, {through: 'UserProject'});
12 User.belongsToMany(Project, {through: 'UserProject'});

1. HasMany
2. BelongsToMany
SEQUELIZE - Relations

1 Project.hasMany(Task)
2 Task.belongsTo(Project)
3
4 Project.create()...
5 Task.create()...
6 Task.create()...
7
8 // save them... and then:
9 project.setTasks([task1, task2]).then(() => {
10 // saved!
11 })
12
13 // ok, now they are saved... how do I get them later on?
14 project.getTasks().then(associatedTasks => {
15 // associatedTasks is an array of tasks
16 })
17
18 // You can also pass filters to the getter method.
19 // They are equal to the options you can pass to a usual finder method.
20 project.getTasks({ where: 'id > 10' }).then(tasks => {
21 // tasks with an id greater than 10 :)
22 })
23
24 // You can also only retrieve certain fields of a associated object.
25 project.getTasks({attributes: ['title']}).then(tasks => {
26 // retrieve tasks with the attributes "title" and "id"
27 })
SEQUELIZE - Queries

1 // search for known ids


2 Project.findByPk(123).then(project => {
3 // project will be an instance of Project and stores the content of the table entry
4 // with id 123. if such an entry is not defined you will get null
5 })
6
7 // search for attributes
8 Project.findOne({ where: {title: 'aProject'} }).then(project => {
9 // project will be the first entry of the Projects table with the title 'aProject' || null
10 })
11
12
13 Project.findOne({
14 where: {title: 'aProject'},
15 attributes: ['id', ['name', 'title']]
16 }).then(project => {
17 // project will be the first entry of the Projects table with the title 'aProject' || null
18 // project.get('title') will contain the name of the project
19 })
SEQUELIZE - Queries

1 // search for known ids


2 Project.findByPk(123).then(project => {
3 // project will be an instance of Project and stores the content of the table entry
4 // with id 123. if such an entry is not defined you will get null
5 })
6
7 // search for attributes
8 Project.findOne({ where: {title: 'aProject'} }).then(project => {
9 // project will be the first entry of the Projects table with the title 'aProject' || null
10 })
11
12
13 Project.findOne({
14 where: {title: 'aProject'},
15 attributes: ['id', ['name', 'title']]
16 }).then(project => {
17 // project will be the first entry of the Projects table with the title 'aProject' || null
18 // project.get('title') will contain the name of the project
19 })

You might also like