簡體   English   中英

如何使用 heroku 和 nodejs 設置 postgresql 配置?

[英]How to set up postgresql config with heroku and nodejs?

這是我第一次嘗試在 heroku 上托管 nodeJS 應用程序 - 使用 hapi.js、typeorm 和 postgresql 構建。 我在 heroku 上創建了兩個應用程序 - 用於“登台”(服務器登台)和“生產”(服務器產品)——它們使用相同的代碼但將使用不同的配置。 為什么不同的配置? 因為 heroku 上的每個應用程序都將使用不同的 postgres 憑據,因為它作為附加組件附加。

客觀的

我的目標/主要問題是我必須如何以及在哪里為我的應用程序設置數據庫配置?

我使用.env文件(我在.gitignore中忽略它 -我不想將憑證放入我的 repo )將應用程序連接到我的本地數據庫。 這是.env的樣子:

HOST=localhost
PORT=3001

TYPEORM_CONNECTION=postgres
TYPEORM_HOST=localhost
TYPEORM_USERNAME=postgres
TYPEORM_PASSWORD=password
TYPEORM_DATABASE=database
TYPEORM_PORT=5432
TYPEORM_SYNCHRONIZE=true
TYPEORM_LOGGING=false

在應用程序中,我從不編寫/編寫諸如process.env.TYPEORM_USERNAME之類的代碼,因為它是由 typeorm node_modules 完成的。 我開始連接的方法是這樣做:

const server = new Hapi.Server({
    port: process.env.PORT,
    host: process.env.HOST,
    routes: {
      cors: Cors,
    },
  });

  await server.register(Plugins);

  server.route(Router);

  await createConnection();
  await server.start();

我的應用程序自動連接到.env中定義的指定數據庫。 現在,在 heroku 中,憑證就在這里:

在此處輸入圖像描述

所有信息都在那里,但是,[Q1] 我不知道如何告訴我的應用程序(當然,沒有在我的代碼/存儲庫中存儲憑據)我必須使用上圖中定義的配置? 此外,如上圖所述,“Heroku 會定期輪換憑據並更新附加此數據庫的應用程序。”。 這是否意味着憑據會定期更改? [Q2] 如果是,有什么方法可以讓我的應用程序自動識別新的憑證?

對不起,如果我的解釋混淆了。 如果您不理解我想要達到的目標,請詢問您不理解的內容,以便我可以修復/更新我的問題以使其易於理解。

無論如何,我找到了這個例子first-examplesecond-example 但是,他們正在使用包含憑據的process.env.DATABASE_URL 我認為,這意味着他們不會在他們的倉庫中忽略他們的.env文件?

*) 注意:Q1 表示問題 1,rest 也是如此

在 repo 的根目錄中編寫一個 ormconfig.js 文件。 這樣,您可以訪問從 heroku 提供的 url 等環境變量,並且您的存儲庫中沒有憑據。

 require('dotenv').config(); module.exports = [ { name: 'default', type: 'postgres', url: process.env.DATABASE_URL, synchronize: false, logging: false, entities: ['dist/entities/*.*'], migrations: ['dist/database/migrations/**/*.js'], subscribers: ['dist/database/subscribers/**/*.js'], cli: { entitiesDir: 'dist/entities', migrationsDir: 'dist/database/migrations', subscribersDir: 'dist/database/subscribers', }, }, { name: 'development', type: 'postgres', host: process.env.POSTGRES_HOST, port: process.env.POSTGRES_PORT, username: process.env.POSTGRES_USER, password: process.env.POSTGRES_PASSWORD, database: process.env.POSTGRES_DB, synchronize: true, logging: true, entities: ['src/entities/*.*'], migrations: ['src/database/migrations/**/*.ts'], subscribers: ['src/database/subscribers/**/*.ts'], cli: { entitiesDir: 'src/entities', migrationsDir: 'src/database/migrations', subscribersDir: 'src/database/subscribers', }, }, ];

使用此配置,您可以在 javascript/typescript 中獲取特定配置:

let connectionOptions: ConnectionOptions;

if(process.env.NODE_ENV ==='development') { 
  connectionOptions = await getConnectionOptions("development");
} else {
  connectionOptions = await getConnectionOptions("default");
}
await createConnection(connectionOptions);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM