官术网_书友最值得收藏!

Using a configuration file with Sequelize

The previous setup for our database connection with Sequelize is fine, but it is not made for later deployment. The best option is to have a separate configuration file that is read and used according to the environment that the server is running in.

For this, create a new index.js file inside a separate folder (called config), next to the database folder:

mkdir src/server/config
touch src/server/config/index.js

Your sample configuration should look like the following code, if you have followed the instructions for creating a MySQL database. The only thing that we did here was to copy our current configuration into a new object indexed with the development or production environment:

module.exports = {
"development": {
"username": "devuser",
"password": "PASSWORD",
"database": "graphbook_dev",
"host": "localhost",
"dialect": "mysql",
"operatorsAliases": false,
"pool": {
"max": 5,
"min": 0,
"acquire": 30000,
"idle": 10000
}
},
"production": {
"host": process.env.host,
"username": process.env.username,
"password": process.env.password,
"database": process.env.database,
"logging": false,
"dialect": "mysql",
"operatorsAliases": false,
"pool": {
"max": 5,
"min": 0,
"acquire": 30000,
"idle": 10000
}
}
}

Sequelize expects a config.json file inside of this folder by default, but this setup will allow us a more custom approach in later chapters. The development environment directly store the credentials for your database whereas the production configuration uses environment variables to fill them.

We can remove the configuration that we hardcoded earlier and replace the contents of our index.js database file to require our configFile, instead.

This should look like the following code snippet:

import Sequelize from 'sequelize';
import configFile from '../config/';

const env = process.env.NODE_ENV || 'development';
const config = configFile[env];

const sequelize = new Sequelize(config.database, config.username,
config.password, config);

const db = {
sequelize,
};

export default db;

In the preceding code, we are using the NODE_ENV environmental variable to get the environment that the server is running in. We read the config file and pass the correct configuration to the Sequelize instance. The environmental variable will allow us to add a new environment, such as production, at a later point in the book.

The Sequelize instance is then exported for use throughout our application. We use a special db object for this. You will see why we are doing this later on.

Next, you will learn how to generate and write models and migrations for all of the entities that our application will have.

主站蜘蛛池模板: 鄂尔多斯市| 堆龙德庆县| 望奎县| 井研县| 金溪县| 克什克腾旗| 阳西县| 黔南| 高州市| 惠水县| 曲阳县| 庐江县| 长岛县| 岳阳县| 阳朔县| 德江县| 宁远县| 平顶山市| 保山市| 浦东新区| 和平区| 顺平县| 广河县| 漾濞| 墨竹工卡县| 惠水县| 新田县| 建阳市| 余干县| 霍州市| 女性| 罗田县| 灵璧县| 乌什县| 吉首市| 正定县| 靖西县| 和龙市| 香格里拉县| 鲁山县| 永年县|