LoginSignup
1
1

More than 1 year has passed since last update.

【Sequelize】configファイルで環境変数を使いたい

Posted at

sequelize-cli

npm install --save-dev sequelize-cli
npx sequelize-cli init

こうするとRubyのActiveRecord風にSequelize経由でdbを操作することができるようになる。また、initで生成されたconfig/config.jsonからdbへの接続情報を指定することになる。

config.json
{
  "development": {
    "username": "root",
    "password": null,
    "database": "database_development",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "postgres"
  }
}

でも、jsonにパスワードなどを直接記入するのは避け、.envを使いたいところ。

.sequelizerc

そこで.sequelizercの登場。
プロジェクトのルートで

touch .sequelizerc
.sequelizerc
const path = require('path');

module.exports = {
    'config': path.resolve('./config', 'config.js'),
};

そして、先程のconfig.jsonconfig.jsにリネームし、内容を下記に書き換える。

config.js
module.exports = {
  development: {
    username: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: 'development',
    host: '127.0.0.1',
    dialect: 'postgres',
  },
}

このようにすることで、sequelizeのconfigに環境変数が利用できるようになった。

参考

Sequlize公式ドキュメント

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1