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

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.

主站蜘蛛池模板: 西乡县| 昆明市| 都江堰市| 大方县| 本溪| 贵港市| 深圳市| 武川县| 仲巴县| 舟山市| 吴忠市| 宕昌县| 嵊州市| 剑川县| 辉南县| 祁东县| 海伦市| 邵阳县| 佛冈县| 胶州市| 黄冈市| 咸阳市| 武定县| 阿勒泰市| 东安县| 望江县| 米泉市| 汶川县| 嫩江县| 曲阳县| 三原县| 沐川县| 安宁市| 沙田区| 兴城市| 聊城市| 鸡东县| 民县| 军事| 盐亭县| 应用必备|