Monthly Archives: January 2019

nodejs – sequelize ORM many to many setup

Image result for sequelize logo

With help of the Sequelize ORM you can manage your database models and queries. Below is an example of how to setup a many to many relationship with Nodejs and the Sequelize ORM. At the end of this article you can find a link to the source code.

First of all our scenario:

We have Invoices and Products in our database. As you can imagine you can receive a invoice for multiple products. Also a product can occur on multiple invoices. The relation between Invoices and Products is many to many.

1 Invoice can have 1 or more products and 1 product can have one or more invoices.

The way to model this in a database is with a so called join table. This table has a pointer to an Invoice and a pointer to a Product. Lets say we want to send two invoices.

Invoice number 2019001 with a SSD and a Laptop on it and Invoice number 2019002 with a harddisk and monitor on it. We have not yet sold any Desktop’s.

Our Invoice and Product tables look like this:

INVOICE                  PRODUCTS
ID   NR                  ID  DESC
1    2019001             1   Laptop
2    2019002             2   SSD
                         3   Harddisk
                         4   Monitor
                         5   Desktop

Then we have our join table, I have called it ProductInvoices after sending the invoices to our customer it will have the contents as shown below

INVOICEPRODUCT
INVOICE_ID PRODUCT_ID
1          1
1          2
1          3
2          3
2          4

Ok, now lets switch over to Nodejs and Sequelize. How are we going to model this in Sequelize? Below are all the steps to create a working program.

Create a new directory and setup your node environment, also initialize a new Sequelize setup with the Sequelize init command (you need to install the sequelize-cli package for this to work).

mkdir m_to_m
cd m_to_m
npm init -y
npm install sequelize-cli sequelize sqlite3
./node_modules/.bin/sequelize init

After this you will have the following directory structure (I use Visual Code for my development work as you can see).

Now we are going to create the Invoice model. Start up visual code in the m_to_m directory (execute code . in this directory). Right click on the models folder and choose new file. Name it invoice.js. Place the code shown below in it.

module.exports = (sequelize, DataTypes) => {

	var Invoice = sequelize.define('Invoices', {
		nr : {
			type : DataTypes.INTEGER,
			allowNull : false,
			unique : {msg : 'Invoice nr should be unique'}
		}
	});

	Invoice.associate = (models) => {
    		Invoice.belongsToMany(models.Products, {
			through: 'ProductInvoices',
			as: 'Products',
			foreignKey: 'invoiceId'
		});
	};

	return Invoice;
}

Next create a file product.js also in the models folder with the following content:

module.exports = (sequelize, DataTypes) => {
		
	var Product = sequelize.define('Products', {

		name : {
			type : DataTypes.STRING,
            allowNull : false,
			unique : {msg : 'Product name should be unique'}
		}
		
	});

	Product.associate = (models) => {
			Product.belongsToMany(models.Invoices, {
			through: 'ProductInvoices',
			as: 'Invoices',
			foreignKey: 'productId'
		});
	};

	return Product;
}

The next model is optional. When you do not specify it Sequelize will generate one for you. Specifying it yourself has the advantage that you can also query this model if needed and add some attributes to the relation. For this example I have added a ‘remark’ attribute to this join table. We can add a remark to the product for this invoice.

So for now lets code it, but remember, it is optional if there is no need to query the join table or you do not have any relation attributes.

module.exports = (sequelize, DataTypes) => {
		
	var ProductInvoices = sequelize.define('ProductInvoices', {

		id : {
			type : DataTypes.INTEGER,
			primaryKey : true,
			autoIncrement: true,
		},

		productId : {
			type : DataTypes.INTEGER,
			unique : false,
            allowNull : false,
		},
		
		invoiceId : {
			type : DataTypes.INTEGER,
			unique : false,
            allowNull : false,
		},

		remark : {
			type : DataTypes.STRING,
			unique : false,
            allowNull : true,
		},
	});

	ProductInvoices.associate = (models) => {
		
		ProductInvoices.belongsTo(models.Products, {
			as: 'Product',
			foreignKey: 'productId'
		});
		ProductInvoices.belongsTo(models.Invoices, {
			as: 'Invoice',
			foreignKey: 'invoiceId'
		});
	};

	return ProductInvoices;
}

Now our model is complete and we can start to program against it. I love the Sequelize ORM, don’t you, no?, you will in a minute…..

We have to do some configuration for the database connection before we are able to create the database. In this example I will be using a SQLite database. Remove the file generate by Sequelize at ~/m_to_m/config/config.json. Create a new file at this location but with the extension js. Place the contens shown below in this config.js file

module.exports = {
  "development": {
    "dialect": "sqlite",
    "storage" : "./database_dev.sqlite3",
    "operatorsAliases": false,
  },
  "test": {
    "dialect": "sqlite",
    "storage" : "./database_tst.sqlite3",
    "operatorsAliases": false
  },
  "production": {
    "dialect": "sqlite",
    "storage" : "./database_prd.sqlite3",
    "operatorsAliases": false
  }
}

There is one last thing to do before our database setup is complete. Edit the generated index.js file at ~/m_to_m/models and change config.json to config.js (remove the “on” at the end of the filename extension).

const config = require(__dirname + '/../config/config.js')[env];

Now the database setup is complete, lets start to write some code. Create a new file in the root of your project and name it app.js, place the code shown below in it.

var models = require('./models');
models.sequelize.sync().then(() => {
   console.log(`DB ${db.options.storage} created.`);
});

When you execute this node program the database database_dev.sqlite3 will be created (see the config.js file in the config directory). The SQL that is executed against the SQLite driver is also shown:

~/m_to_m$: node app.js
Executing (default): CREATE TABLE IF NOT EXISTS 
`Invoices` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `nr` INTEGER NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);

Executing (default): PRAGMA INDEX_LIST(`Invoices`)

Executing (default): PRAGMA INDEX_INFO(`sqlite_autoindex_Invoices_1`)

Executing (default): CREATE TABLE IF NOT EXISTS 
`Products` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);

Executing (default): PRAGMA INDEX_LIST(`Products`)

Executing (default): PRAGMA INDEX_INFO(`sqlite_autoindex_Products_1`)

Executing (default): CREATE TABLE IF NOT EXISTS `ProductInvoices` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `productId` INTEGER NOT NULL REFERENCES `Products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, `invoiceId` INTEGER NOT NULL REFERENCES `Invoices` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, `remark` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, UNIQUE (`productId`, `invoiceId`));

Executing (default): PRAGMA INDEX_LIST(`ProductInvoices`)

Executing (default): PRAGMA INDEX_INFO(`sqlite_autoindex_ProductInvoices_1`)
~/m_to_m$:DB Created

To inspect the contents of this database you can for example use “DB Browser for SQLite” or DBeaver . Install “DB Browser for SQLite” with

sudo apt install sqlitebrowser
DB Browser for SQLite in action

Now we are going to add some records to our database and query the database. We will be adding five products and two invoices as described above. After that we will generate an overview of the data in the database.

Here is the code to store and query our Invoices and products.

var models = require('./models');

(async () => {

    let db = await models.sequelize.sync();

    console.log(`DB ${db.options.storage} created.`);

    await models.Invoices.destroy({ where : {}, truncate : true});
    await models.Products.destroy({ where : {}, truncate : true});

    let laptop = await models.Products.create( { name : 'Laptop' })
    let ssd = await models.Products.create( { name : 'SSD' });
    let harddisk = await models.Products.create( { name : 'Harddisk' });
    let monitor = await models.Products.create( { name : 'Monitor' });
    let desktop = await models.Products.create( { name : 'Desktop' });

    invoice = await models.Invoices.create({ nr : 2019001 });
    await invoice.addProducts([ssd],  {through: { remark: '10% discount on SSD' }});
    await invoice.addProducts([harddisk, laptop]);

    invoice = await models.Invoices.create({ nr : 2019002 });
    await invoice.addProducts([harddisk, monitor]);

    invoices = await models.Invoices.findAll(
        { 
            include : [ {model: models.Products, through: 'ProductInvoices', as: 'Products'}]
        }
    );

    invoices.forEach(invoice => {

        console.log(`INVOICE: ${invoice.id} ${invoice.nr}`);
        invoice.Products.forEach(product => {
            console.log(`\tPRODUCT: ${product.id} ${product.name}`);
        })
        console.log();

    });

    products = await models.Products.findAll(
        { 
            include : [ {model: models.Invoices, through: 'ProductInvoices', as: 'Invoices'}]
        }
    );

    products.forEach(product => {

        console.log(`PRODUCT ${product.id} ${product.name}`);
        product.Invoices.forEach(invoice => {
            console.log(`\tINVOICE: ${invoice.id} ${invoice.nr}`);
        })
        console.log();

    });

    /*
     * Weird but possible adding records via jointable.....
     */
    pi = await models.ProductInvoices.create(
    { 
        invoiceId : (await models.Invoices.create({ nr : 2019009})).id,
        productId : (await models.Products.findOne({ where : { name : 'Desktop' } })).id
    });

    productInvoices = await models.ProductInvoices.findAll(
        { 
            include : [ 
                {model: models.Products, as : 'Product'},
                {model: models.Invoices, as : 'Invoice'}
            ]
        }
    );

    productInvoices.forEach(pi => {
        console.log(`${pi.id} ${pi.Invoice.id} ${pi.Invoice.nr} ${pi.Product.id} ${pi.Product.name}`);
    });
})();

After running this code you will have two Invoices and five Products in your database. The image below shows the console output of running this Nodejs program. I have switched of Sequelize logging (add an attribute “logging” : false to the appropriate entry in ~/config/config.json) so the output is a bit more readable.

You can find the complete working example here and a typescript variant can be found here.

Got to elaborate on this, see https://www.npmjs.com/package/sequelize-typescript


Share

nodejs – using typescript with nodemon

Create a new directory and run the command below in it

npm init -y

Next install nodemon with

sudo npm install -D nodemon

Add a script tag to your package.json to execute the nodemon command. This works because npm looks under node_modules/.bin for an executable. The package.json looks then like this

{
  "name": "learnnode",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "nodemon": "nodemon"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^1.18.9"
  }
}

Create a new file index.js, this is the default file nodemon looks for when started without any parameters. index.js contains only:

console.log('Hello');

Now start the nodemon executable

npm run nodemon

Now if you change the index.js file nodemon will restart and execute nodejs with the new index.js file.

Now we want to make use of TypeScript. Install the typescript compiler locally together with the ts-node binary with

npm install -D typescript
npm install -D ts-node

Also add a new script to your package.json called tsc. The complete contents of the package.json file is shown below:

{
  "name": "ts",
  "version": "1.0.0",
  "description": "Example live build",
  "main": "index.js",
  "scripts": {
    "start": "npm run build:live",
    "build": "tsc -p .",
    "build:live": "nodemon --watch '*.ts' --exec 'ts-node' app.ts"
  },
  "keywords": [],
  "author": "B J de Jong",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^1.18.9",
    "ts-node": "^7.0.1",
    "typescript": "^3.2.2"
  },
  "dependencies": {}
}

Now you will need a tsconfig.json for the typescript compiler. Create a tsconfig.json file with default settings with:

npm run tsc -- --init

Now to start monitoring your ts files start the ‘start’ node script with

npm run start
Share

nodejs – using express-session

In this article I will show you how to use express sessions. Default express-sessions are stored in memory. With help of the package ‘session-file-store’ you can persist sessions to your filesystem.

Use memory store for sessions (default)

First setup your nodejs app to use express and express-essions:

# Create new package.json file
npm init -y
# Add express and express-ession to node module
npm install express express-ession --save

Now add an app.js file to the current folder with the following contents:

const session = require('express-session');
// const FileStore = require('session-file-store')(session);
const express = require('express')
const app = express()
const port = 3000

app.use(session({
        secret: 'mysecret', 
        resave : false, 
        saveUninitialized : false,
        // store: new FileStore()
    })
)

app.get('/', (req, res) => {

    if (req.session.views) {
        req.session.views++
        res.send(`Returning client (${req.session.views} times})`)
    }
    else {
        req.session.views = 1
        res.send('New client')
    }
})

app.get('/destroy', (req, res) => {
    req.session.destroy()
    res.send('Session destroyed')
})

app.listen(port, () => console.log(`Listening on port ${port}`))

Start your nodejs application with

nodemon app.js

and navigate to ‘http://localhost:3000/’. A webpage shows up with the text ‘New client’. Now hit F5 and see the text ‘Returning client (2 times)’ appearing. The session is created on first request with a ‘views’ variable in it. Every next visit of the site this ‘views’ variable is incremented with 1.

Use a FileStore for session data

Now if you want to use persistent session you will have to install the session-file-store with:

npm install session-file-store --save

Uncomment the two lines of code in app.js and you are ready to go. Sessions are stored on the filesystem in a sub folder called ‘sessions’ below the location of your app.js.

If you are using nodemon to monitor changes in your nodejs code be sure to exclude monitoring of the ‘sessions’ folder as it will change on every request of the browser. Start nodemon with:

nodemon --ignore sessions/ app,js

Custom session id’s

In case you want to generate custom session id’s you will have to provide a genid callback to the session initialized. First add the uuid package with

npm install uuid

Add the require statement to the top of your app.js file:

const uuidv1 = require('uuid/v1')

And add the genid callback to the session initialization:

app.use(session({
        genid: (req) => {
            return 'app_' + uuidv1() // use UUIDs for session IDs
        },
        secret: 'keyboard cat', 
        resave : false, 
        saveUninitialized : false,
        store: new FileStore()
    })
)
Share

nodejs – use mongodb for CRUD application

In this article I’m going to create a minimalistic CRUD application with nodejs, express and mongodb. First I will show you the pug files and finally the nodejs code for creating our application.

To use mongodb you have to install it on your (ubuntu) box with:

sudo apt install mongodb

Then we have to add the node module to our project (and package.json) with:

npm install mongodb --save

Now on to the pug files. First of all the ‘index.pug’ file (remember pug files are stored in the views folder (default).

html
  head
  body
    h2 Add email address
    a(href='/all') All
    form(method='POST' action='/add')
      div
        p Your email address
        input#name.form-control(type='text', placeholder='Email address' required name='email')
      p 
          button.btn.btn-primary(type='submit') Sign up

Then we have the ‘all.pug’ file which gives us an overview of entries in the database together with a link to delete or edit the entry

html
  head
  body
    h2 List of email addresses
    a(href='/') Add
    table
        each email in email_addresses
            tr#email_list_item    
                td #{email.email}
                td #{email.i}
                td
                    a(href='delete?id=' + email._id) x
                td
                    a(href='edit?id=' + email._id) e

We have an ‘edit.pug’ file to edit our document entries

html
  head
  body
    h2 Update email address
    a(href='/all') All
    form(method='POST' action='/edit')
        input#email.form-control(type='hidden', name='id' value=id)
        div
            p Edit email address
            input#email.form-control(type='text', placeholder='Email address' required name='email' value=email_address)
        p 
            button.btn.btn-primary(type='submit') Update
        p

And finally we have our app.js nodejs application.

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

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'pug')

var ObjectId = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/", { useNewUrlParser: true }, function(err, client) {

    if (err) throw (err)
    mongoDB = client.db('emailaddresses')
    app.listen(port, () => console.log(`Listening on port ${port}`))

});

app.get('/', (req, res) =>  {

        res.render('index')

    }
)

app.post('/add', (req, res) =>  {
    
    mongoDB.collection('email_addresses').insertOne(req.body, (err, result) => {

        if (err) throw err
        res.redirect('all')

    })
})

app.get('/all', (req, res) =>  {

    mongoDB.collection('email_addresses').find().toArray((err, results) => {

        if (err) throw err
        res.render('all', { 'email_addresses': results })

    })

})

app.get('/delete', (req, res) =>  {

    mongoDB.collection('email_addresses').deleteOne({'_id': ObjectId(req.query.id)}, (err, results) => {

        if (err) throw err
        res.redirect('/all')
        
    });
})

app.get('/edit', (req, res) =>  {

    mongoDB.collection('email_addresses').findOne({'_id': ObjectId(req.query.id)}, (err, result) => {

        if (err) throw err
        res.render('edit', { 'email_address' : result.email, 'id' : result._id })

    });
})

app.post('/edit', (req, res) => {

    mongoDB.collection('email_addresses').updateOne({'_id': ObjectId(req.body.id)}, { $set:req.body }, (err, result) => {

        if(err) throw err
        res.redirect('/all')

    });
})
Share

nodejs – https and selfsigned certificate

In this article I will talk about nodejs and listening to a ssl (https) port. To make a selfsigned certificate execute the command below:

openssl req -nodes -new -x509 -keyout server.key -out server.cert -days 3650

Remember that browsers will complain about an invalid certificate. For most browsrs you can add a security exception for the certificate.

Now we have to tell nodejs to make use of this certificate when starting the https server. We have to create an option object with two properties: ‘key’ and ‘cert’. When we create the https server we pass in this option object:

var options = {
	key: fs.readFileSync('server.key'),
	cert: fs.readFileSync('server.cert')
};
https.createServer(options, app).listen(3030);

The complete code for a https server with nodejs is shown below

const https = require('https');
const fs = require('fs')
const express = require('express')
const app = express()
const port = 3030

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'pug')

app.get('/', (req, res) =>  {
        res.render('index')
    }
)

var options = {
	key: fs.readFileSync('server.key'),
	cert: fs.readFileSync('server.cert')
};
https.createServer(options, app).listen(3030);

console.log(`Listening on port ${port}`);

The pug template that is served:

html
  head
  body
    p SSL site
Share

nodejs – asynchronous explained

nodejs – asynchronous explained

In this article i will talk about asynchronous nodejs functions. I use express as the routing middleware and pug as the template engine. The code below shows the setup for the nodejs snippets used later on in this post:

/*
 * Setup:
 * - use 'express' for routing
 * - use 'fs' for reading file from filesystem
 * - use 'pug' as the templating engine
 */
const express = require('express')
const fs = require('fs')
const app = express()
const port = 3000

app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'pug')

We have setup the nodejs app with the code above. Now we are going to add the routes that we want to publish in our example app, see the code below:

// render input form which posts to /read route
app.get('/', (req, res) =>  {

        res.render('index')

    }
)

// read the file
app.post('/read', async (req, res, next) => {

    fs.readFile('./test.txt', (err, data) =>{

        if (err) {
            next(err)
        }

        next(data)
    })

});

app.listen(port, () => console.log(`Listening on port ${port}`))

When we navigate to ‘http://localhost:3000’ the route ‘/’ is processed. This will render our index.pug file which has the following contents:

html
  head
  body
    form(method='POST' action='/read')
      div
        p Your email address
        input#name.form-control(type='text', placeholder='Email address' name='email')
        p 
          button.btn.btn-primary(type='submit') Sign up

Pressing the ‘Sign up’ button will take us to the ‘http://localhost:3000/read’ route. As you can see this route will try to read the ‘./test.txt’ file, The fs.readFile is an asynchronous function. When the readFile operation is complete it will execute the callback that is provided as the second parameter.

When an error occurs fs.readFile will execute the callback with an error object (the data parameter will be ‘undefined’). The error object contains, as you expect, a description of the error:

Error: ENOENT: no such file or directory, open './does_not_exist.txt'

If you would like to have a complete stacktrace in your error object you should change the line ‘next(err)’ to next(new Error(err)’, the resulting error after this change:

Error: Error: ENOENT: no such file or directory, open './does_not_exist.txt'
  at ReadFileContext.fs.readFile [as callback] (/home/uname/node/app.js:21:18)
  at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)

The code above makes use of the callback function of the readFile method on the fs object. An alternative way of accomplishing the same result is to use promises. Lets have a look at the code below:

app.post('/read', (req, res, next) => {

    new Promise((resolve,reject) => {

        fs.readFile('./test.txt', 'utf-8', (err, data) => {

            if (err) {
                // in the case of error, reject the promise, executing the catch code block
                reject(err); 
            }
            else {
                // in the case of success, resolve the promise, exectuing the then code block
                resolve(data);  
            }

        });

    })
    .then((data) => {

        res.send(data)

    })
    .catch((err) => {

        res.send(err)
        
    })
});

As you can see we wrap our fs.readFile in a Promise object. A promise will be rejected on error (the file could not be found for example) and will be resolved on success. When a promise is rejected the catch code block will be executed. If the promise is resolved the then code block will be executed.

The advantage of using a promise is that we can wait on the result if we want to. The code below will wait for the readFile function to complete and then continues the /read handle after the wait promise line

app.post('/read', async (req, res, next) => {

    let fileContent = null

    let promise = new Promise((resolve,reject) => {

        fs.readFile('./test.txt', 'utf-8', (err, data) => {

            if (err) {
                // in the case of error, reject the promise, executing the catch code block
                reject(err); 
            }
            else {
                // in the case of success, resolve the promise, exectuing the then code block
                resolve(data);  
            }

        });

    })
    .then((data) => {

        fileContent = data

    })
    .catch((err) => {

        res.send(err)

    })

    await promise

    if (fileContent) {
        // the catch of the promise did not send(..) any text
        res.send(fileContent)
    }

});
Share