Deliver the commitment to the data source connection settings in TypeORM

Is it possible to retrieve the datasource connection options from AWS Parameter Store instead of storing them as environment variables in a general JavaScript question? I am having difficulty finding a solution and seeking expert advice on this matter.

This is my datasource class:

let options = {
  type: "mssql" as any,
  host: AwsParameterStore.getParameter("DATABASE_HOST").then(
    async (secretKey) => {
      return secretKey;
    }
  ),
  database: process.env.DATABASE_NAME,
  username: process.env.DATABASE_USERNAME,
  password: process.env.DATABASE_PASSWORD,
  options: { encrypt: false },
  synchronize: false
};

export const VcsDatabase = new DataSource((options = options));

and this is my AwsParameterStore class:

@Injectable()
export class AwsParameterStore {
  constructor(private eventLogger: LoggingService) {}
  static async getParameter(parameterName: string): Promise<any> {
    let ssm = new SSM({ region: "eu-west-1" });
    let options = {
      Name: parameterName
    };
    let parameter = ssm.getParameter(options).promise();
    return parameter.then((response) => {
      let token: string = response.Parameter.Value;
      return token;
    });
  }
}

It seems that passing the host value as a promise does not work, as TypeORM Datasource requires it as a string based on the error message received.

connection error TypeError: The "config.server" property is required and must be of type string.

I have two questions:

  • Is there a way to pass the connection parameters from another service like the AwsParameterStore?
  • If not feasible, would it be acceptable to store the database credentials in GitLab CI/CD variables and access them during pipeline execution?

I am primarily concerned with securing the credentials and believe storing them in SSM and retrieving them at runtime is the best approach.

Answer №1

In order to ensure that the promise is fulfilled and options are properly passed in, you must use await or include your code within a then clause. Exporting an async function will require you to await it when using. Here is an example:

async function createDataSource() {
    let options = {
        type: "mssql" as any,
        host: await AwsParameterStore.getParameter("DATABASE_HOST"),
        database: process.env.DATABASE_NAME,
        username: process.env.DATABASE_USERNAME,
        password: process.env.DATABASE_PASSWORD,
        options: { encrypt: false },
        synchronize: false
    };

    return new DataSource(options);  // Your previous code was not correct
}

export const createDatabaseConnection = createDataSource;

To import and utilize this function, you can do so like this:

const dbConnection = await createDatabaseConnection();

or

createDatabaseConnection().then(dbConnection => {
   // Perform tasks here
}

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

Webclipse is having trouble locating a module, despite the fact that Angular CLI is able to

I am facing an issue with my project structure src | +--app | +--components | | | +-component.ts | +--entities | +--entity.ts In entity.ts, I have export class Entity { ... In component.ts, there is an import statement ...

Waiting for variable to become false using Angular 7 Observable

The observable below highlights the authentication process: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { CookieService } from 'ngx-cookie-service'; import { Observabl ...

What is the best way to terminate a Node.js app using a scheduler?

I've been attempting to halt my cron task and shut down the entire nodeapp after 5 executions, but despite trying various methods, all attempts have failed. The message "time to quit" continues to appear in the log every minute. What would be the mos ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

"Exploring Angular 9: A guide to retrieving form data with an array of objects [Revised as of July 29th, 2020

I am encountering an issue with my Angular 9 form code. I am getting the error "ERROR TypeError: Cannot read property 'mobile_number' of undefined" and I need help in resolving this problem. <form (ngSubmit)="processForm()"> & ...

Is it considered best practice to pass an argument that represents an injectable service?

Is it a good practice to pass an argument that is an injectable service to a function? Hello everyone, I have been doing some research but have not found a definitive answer to the question above yet. I am currently working with Angular and came across so ...

The new data is not being fetched before *ngFor is updating

In the process of developing a "Meeting List" feature that allows users to create new meetings and join existing ones. My technology stack includes: FrontEnd: Angular API: Firebase Cloud Functions DB: Firebase realtime DB To display the list of meeting ...

Update the class attributes to a JSON string encoding the new values

I have created a new class with the following properties: ''' import { Deserializable } from '../deserializable'; export class Outdoor implements Deserializable { ActualTemp: number; TargetTemp: number; Day: number; ...

When using Typescript inheritance, the datatypes shown in IntelliSense are unexpectedly listed as "any" instead of

In my Typescript code, I have a small implementation where a class is either implementing an interface or extending another class. interface ITest { run(id: number): void } abstract class Test implements ITest { abstract run(id); } class TestEx ...

The error message indicates that the argument cannot be assigned to the parameter type 'AxiosRequestConfig'

I am working on a React app using Typescript, where I fetch a list of items from MongoDB. I want to implement the functionality to delete items from this list. The list is displayed in the app and each item has a corresponding delete button. However, when ...

Issue - The path to the 'fs' module cannot be resolved in ./node_modules/busboy/lib/main.js

After adding a new React component to my NextJS app, I encountered a mysterious error in my local development environment: wait - compiling... error - ./node_modules/busboy/lib/main.js:1:0 Module not found: Can't resolve 'fs' null Interest ...

Angular integration problem with aws-amplify when signing up with Google account

I am attempting to integrate AWS-Amplify(^4.3.0) with angular-12 and typescript (4.3.5). I have followed the documentation to configure amplify properly, but when trying to start the app, I encountered some amplify errors as shown below. Warning: D:\G ...

Ignoring TypeScript type errors in ts-jest is possible

Recently, I embarked on a journey to learn TypeScript and decided to test my skills by creating a simple app with jest unit testing (using ts-jest): Here is the code snippet for the 'simple app.ts' module: function greet(person: string): string ...

The category 'Moment' cannot be assigned to the category 'Date'. The characteristic 'toDateString' is not present in the category 'Moment'

I recently integrated moment into my Angular2 application, and encountered an issue when attempting to assign the date of this week's Saturday to a variable of type date, case "weekend": this.fromDate = moment().startOf('week ...

Try querying again if you receive no results from an http.get request in Angular using RXJS Operators

In my Angular service, I sometimes encounter an issue where I receive an empty array. In such cases, I would like to trigger a fresh query. let request = this.http.post(this.searchlUrl, payload).pipe( retryWhen(errors => errors.pipe(delay(100 ...

Fixing Typescript assignment error: "Error parsing module"

Trying to assign an object to the variable initialState, where the type of selectedActivity is Activity | undefined. After using the Nullish Coalescing operator (??), the type of emptyActivity becomes Activity. However, upon execution of this line, an err ...

Multiple asynchronous calls in Angular 2

In my Component, there is a function that is supposed to return a value (Promise). This value requires information from two distinct sources: an API call and data from a database. The method in question looks like this: public getValue(): Promise<numb ...

"Experience the power of utilizing TypeScript with the seamless compatibility provided by the

I'm attempting to utilize jsymal.safeDump(somedata). So far, I've executed npm install --save-dev @types/js-yaml I've also configured my tsconfig file as: { "compilerOptions": { "types": [ "cypress" ...

Successive type label

Looking to create an object that can have either primitives or objects as properties? Avoid pitfalls like the following: const obj: DesiredType = { correctProp1: 'string', correctProp2: 123, correctProp3: true, wrongProp4: [1, 2, 3], pr ...

Analyzing a string using an alternative character

I want to convert the string "451:45" into a proper number. The desired output is 451.45. Any help would be appreciated! ...