What is the correct method for setting the DATABASE_URL in ormconfig.json?

As I work on deploying my Vesper server to Heroku, I've encountered a challenge with the ormconfig.json file that Vesper requires.

While setting up my local database, everything runs smoothly as I can input all the necessary fields for the connection string. However, when it comes to adding a database in Heroku, I only have access to the full URL and I'm unsure where to place it within the configuration file.

Currently, this is how my ormconfig.json looks:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "postgres",
  "password": "password",
  "database": "test",
  "synchronize": true,
  "entities": ["target/entity/**/*.js"],
  "migrations": ["target/migrations/*.js"],
  "cli": {
    "migrationsDir": "src/migrations"
  }
}

I'm hoping to streamline the configuration by replacing most of the fields with just the database_url, but I haven't been able to find any documentation specifying where exactly to include it.

Answer №1

If you're looking to parse Heroku environment variables, consider utilizing an URL parser like pg-connection-string. You can find more information about it at this link.

To get started with TypeOrm on the server side, use the createConnection function provided by TypeOrm.

import * as PostgressConnectionStringParser from "pg-connection-string";

const databaseUrl: string = process.env.DATABASE_URL;
const connectionOptions = PostgressConnectionStringParser.parse(databaseUrl);
const typeOrmOptions: PostgresConnectionOptions = {
    type: "postgres",
    name: connectionOptions.name,
    host: connectionOptions.host,
    port: connectionOptions.port,
    username: connectionOptions.username,
    password: connectionOptions.password,
    database: connectionOptions.database,
    synchronize: true,
    entities: ["target/entity/**/*.js"],
    extra: {
        ssl: true
    }
};
const connection = createConnection(typeOrmOptions);
...

For managing different configurations, you may need to adjust this code snippet to handle scenarios such as enabling/disabling SSL based on the environment (disabling SSL in dev mode, handling entity formats in .ts for ts-node, etc.).

If generating ormconfig.json is a necessity, you can achieve that by creating the file through a script using the preceding code and including a writing operation:

...
const json = JSON.stringify(typeOrmOptions, null, 2);
fs.writeFile("./target/ormconfig.json", json, (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log("File has been created");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The entire space should be filled with the background

My goal is to achieve the following while addressing some current issues: The background is currently limited to affecting only the container. I want it to span the entire area. There needs to be space between the cards and padding inside them. https://i ...

Customizing the toString Method in a TypeScript Class for JavaScript Objects

I've been struggling with a particular issue for the past few days and I just can't seem to find a solution anywhere. Context: I currently have a TypeScript class that is defined like this: export class Client extends Person { claimNumber: s ...

Problems with importing modules in Apollo Server

I've encountered a never-ending stream of error messages post importing Apollo Server into my Typescript-based Node.js application. (Check out the screenshot below) It appears that Apollo is unable to locate anything in the graphql dependency. Could ...

Collision Detection in Kendo UI Menu

When working with TypeScript, it ensures that the parameters are of the correct type. For Kendo's menu, in order to disable the popupCollision property, you need to set it to false. However, this property actually accepts a string as its value, so if ...

What causes an Object to potentially be null even after Array.isArray(obj) check has been performed?

The provided code demonstrates TypeScript focusing on the line result[key].push(submenuKey); where it acknowledges that result might be null, but a check for Array.isArray() is included. Code snippet: interface resultI { [key: string]: string | null ...

Tips for adding an autocomplete feature to your Angular application with Bootstrap 4, all without the need for JQuery

I am looking to integrate an autocomplete input feature into my Angular application, utilizing Bootstrap 4. I envision achieving a result similar to this: https://i.sstatic.net/oqEt7.png Using an array of countries, I aim to allow users to match the text ...

Updated the application to Angular 6 but encountered errors when attempting to run npm run build --prod. However, running the command npm run build --env=prod was executed without any issues

Running the command npm run build -- --prod results in the following error messages: 'PropertyName1' is private and can only be accessed within the 'AppComponent' class 'PropertyName2' does not exist in type 'AppCompo ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Elevate the Appearance of Material UI Elements with custom CSS Sty

I am currently facing an issue while trying to customize the styling of a Material UI component using CSS. Here is the code snippet: <IconButton className="my-class"> <Close /> </IconButton> CSS: .my-class { float: right ...

The value of 'number' can be assigned to the constraint 'T[keyof T]', however, there is a possibility that 'T[keyof T]' may be initialized with a different subtype of the constraint 'number'

The code below shows how I am attempting to sum each property of an array of T and return it as T: export function sumProperties<T extends { [k: string]: number }>(values: T[]): T { return values.reduce((acc, cur) => { (Object.keys(cur) as A ...

Mastering TypeScript debugging in Visual Studio Code with automatic restart

Currently, I am in the process of setting up a TypeScript project using Node. For debugging my main.ts file in Visual Studio Code, I have configured the launch.json as follows: { "type": "node", "request": "launch", "name": "Star ...

The unit test is not passing due to inconsistencies between the mock data generated in the constructors and the original mock data

Currently, I am delving into the world of unit testing and have created a test to work on. Here is what I have so far: const EXEPECTED: MergedFood = { id: '1', name: 'test mergedFood', ingredients: { '2': ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

Having trouble getting the generated component from Ionic v4 CLI to function properly

I'm currently facing a challenge while working with the latest version of Ionic. I am struggling to make a CLI-generated component work properly. After starting with a blank project, I create a new component using the following command: ionic genera ...

update the data source of the material table inside the subscription

Seeking guidance for updating a MatTable datasource within an Angular application. The current Typescript code involves fetching data from an API using AdminService, iterating over the results to make additional API calls for more information about a fleet ...

What is the best approach for associating interfaces with nested objects to ensure proper configuration validation?

Exploring the use of typescript for implementing type checking on a configuration file similar to the one below: const _config = { local: { host: 'localhost', port: 1234 }, dev: { host: 'https://dev.myapp ...

Set up a TypeScript project with essential dependencies for creating multiple raw JavaScript output files

Currently, I am in the process of developing scripts for Bot Land, a real-time strategy game that offers a unique gameplay experience. Rather than controlling units traditionally with a mouse and keyboard, players code their bots using an API to engage in ...

Generating data types based on the output of functions

I'm currently working on optimizing my typescript react code by reducing repetition. I'm curious to know if there's a way to generate a type based on the return type of a known function? For example: const mapStateToProps = (state: StoreSt ...

The function cannot be called on a type that does not have a callable signature. The specified type, 'number | Dispatch<SetStateAction<number>>', does not have any compatible call signatures

Currently, I am working on setting up state to be passed through context in React using hooks. However, when I attempt to use the dispatched state updater function, an error is thrown: Cannot invoke an expression whose type lacks a call signature. Type &a ...