Ask Your Question
2

Is it possible to incorporate .env variables into an entity schema in TypeORM?

asked 2021-05-25 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-09-27 00:00:00 +0000

pufferfish gravatar image

Yes, it is possible to incorporate .env variables into an entity schema in TypeORM. One way to achieve this is by using TypeORM's configuration system. You can define your database connection options in a separate configuration file, which can be loaded from environment variables using a library like dotenv.

In your TypeORM entity schema, you can then import the configuration file and use the connection options to specify the database connection. For example:

import { createConnection } from "typeorm";
import { Config } from "./config";

const connection = await createConnection({
  type: Config.DB_TYPE,
  host: Config.DB_HOST,
  port: Config.DB_PORT,
  username: Config.DB_USERNAME,
  password: Config.DB_PASSWORD,
  database: Config.DB_NAME,
  entities: [__dirname + "/entity/*.js"],
  synchronize: true,
  logging: false
});

In this example, the configuration values are accessed through a Config object, which can be loaded from environment variables using dotenv.

import dotenv from "dotenv";

dotenv.config();

export const Config = {
  DB_TYPE: process.env.DB_TYPE || "mysql",
  DB_HOST: process.env.DB_HOST || "localhost",
  DB_PORT: Number(process.env.DB_PORT) || 3306,
  DB_USERNAME: process.env.DB_USERNAME || "root",
  DB_PASSWORD: process.env.DB_PASSWORD || "",
  DB_NAME: process.env.DB_NAME || "mydb"
};

By using this approach, you can easily change your database connection options by updating the environment variables without having to modify your entity schema code.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-25 11:00:00 +0000

Seen: 13 times

Last updated: Sep 27 '21