Sequelize supports the same API on several SQL database engines. The database connection is initialized using parameters on the Sequelize constructor. The Twelve Factor Application model suggests that configuration data such as this should be kept outside the code and injected using environment variables or a similar mechanism. What we'll do is use a YAML-formatted file to store the connection parameters, specifying the filename with an environment variable.
The Sequelize library does not define any such file for storing connection parameters. But it's simple enough to develop such a file. Let's do so.
The API for the Sequelize constructor is: constructor(database: String, username: String, password: String, options: Object).
In the connectDB function, we wrote the constructor as follows:
sequlz = new Sequelize(params.dbname, params.username, params.password, params.params);
This file, named models/sequelize-sqlite.yaml, provides with us a simple mapping that looks like this for an SQLite3 database:
dbname: notes
username:
password:
params:
dialect: sqlite
storage: notes-sequelize.sqlite3
The YAML file is a direct mapping to the Sequelize constructor parameters. The dbname, username, and password fields in this file correspond directly to the connection credentials, and the params object gives additional parameters. There are many, many, possible attributes to use in the params field, and you can read about them in the Sequelize documentation at http://docs.sequelizejs.com/manual/installation/usage.html.
The dialect field tells Sequelize what kind of database to use. For an SQLite database, the database filename is given in the storage field.
Let's first use SQLite3, because no further setup is required. After that, we'll get adventurous and reconfigure our Sequelize module to use MySQL.
If you already have a different database server available, it's simple to create a corresponding configuration file. For a plausible MySQL database on your laptop, create a new file, such as models/sequelize-mysql.yaml, containing something like the following code:
dbname: notes
username: .. user name
password: .. password
params:
host: localhost
port: 3306
dialect: mysql
This is straightforward. The username and password must correspond to the database credentials, while host and port will specify where the database is hosted. Set the database dialect and other connection information, and you're good to go.
To use MySQL, you will need to install the base MySQL driver so that Sequelize can use MySQL:
$ npm install mysql@2.x --save
Running with Sequelize against other databases it supports, such as PostgreSQL, is just as simple. Just create a configuration file, install the Node.js driver, and install/configure the database engine.