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

Encountering compilation errors during the vue-cli build process

My Vue 2.2.3 application is experiencing difficulties in the build process due to 4 TypeScript-related errors that are perplexing me. This is the error output displayed on the console: Failed to compile with 4 errors ...

I prefer not to run the next.js SWR until after the initial rendering

Development Setup ・ next.js ・ typescript ・ swr This uses swr for communication purposes. I am looking to only trigger it when the query value changes. However, it is also being executed during the initial rendering. How can I prevent it ...

Vuetify's v-data-table is experiencing issues with displaying :headers and :items

I'm facing an issue while working on a Vue project with typescript. The v-data-table component in my Schedule.vue file is not rendering as expected. Instead, all I can see is the image below: https://i.sstatic.net/AvjwA.png Despite searching extensi ...

What is the most effective approach to scan Angular 2, 4, 5 template html files before AOT compilation for optimal code quality assessment?

Recently, I stumbled upon an interesting GitHub repository called "gulp html angular validate". If you're not familiar with it, you can check it out here. However, I have doubts about whether this tool is suitable for Angular 2+ projects. Additionall ...

Setting up Mailgun with TypeScript on Firebase Cloud Functions

Currently, I am working on a Cloud Function within Firebase to integrate with Mailgun for sending emails, following the guidelines provided in the Mailgun documentation. My challenge lies in implementing this functionality using TypeScript, as I have been ...

What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings. AcceptLanguageList = CultureInfo.CurrentUICulture.Name In my TypeScript code ...

Creating a custom data type for the Tanstack table filtering function

I developed a unique filter function specifically for enhancing the functionality of Tanstack Table by utilizing fuse.js. Despite my efforts, TypeScript consistently raises concerns when I try to define the type for my custom function. My goal is to alig ...

Can you explain the distinction between @types/material-ui and the official @mui/types bundle?

When it comes to npm packages, I came across @types/material-ui and @mui/types. I'm aware that the former is backed by the Definitely Typed community, but what's the reasoning behind its existence when an official types package already exists? D ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

Requires the refreshing of an Angular component without altering any @Input properties

Currently delving into the world of Angular (along with Typescript). I've put together a small application consisting of two components. This app is designed to help track work hours (yes, I am aware there are commercial products available for this pu ...

next-intl failing to identify the primary language setting

When testing next-intl for the app directory in the Next.js v13.4.0, I encountered an issue where the default locale was not recognized. Despite following the documentation step by step, I also faced significant challenges with the client-side version in p ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

What are some ways I can enhance the typography within Material UI?

Currently, I am in the process of developing a custom theme utilizing createMuiTheme. However, my application requires more typography variants than what Material UI provides out of the box. I need to extend the typography so that it aligns with my specifi ...

Differences between Angular 4 and AngularJs directives

Delving into the world of Angular 4, I have encountered a slight hurdle in my understanding of directives. My goal is to create a directive that can resize an element based on its width. Back in the days of AngularJs, this task was accomplished with code r ...

Angular 6: Harnessing the Power of RouterLinks

Can you navigate to a different section of another page using the defined ID without having to reload the entire page? ...

Tips for retrieving modified data from a smart table in Angular 4

Currently, I am working on an angular project where I am utilizing smart table. Here is a snippet of my .html file: <ng2-smart-table [settings]="settings" [source]="source" (editConfirm)="onSaveConfirm($event)" (deleteConfirm)="onDeleteConfirm($event ...

In React-Typescript, the second index of the todos array is constantly being updated while the rest of the array remains unchanged

I am struggling to get my Todo-List working with typescript-react. The code I have doesn't seem to be functioning properly. Here is a snippet of my App.tsx: import { useState } from "react"; import "./App.css"; export default fun ...

Creating a DynamoDB table and adding an item using CDK in Typescript

Can anyone guide me on how to add items to a Dynamodb Table using CDK and Typescript? I have figured out the partition/sort keys creation, but I am struggling to find a straightforward solution for adding items or attributes to those items. Additionally, ...

Am I effectively implementing async await in TypeScript?

I'm not quite sure if I'm using the async/await functionality correctly in my TypeScript and Protractor code. Looking at the code snippet below, the spec uses await to call the page object, which itself is an async/await function. The page object ...

Here is a method to display a specific string in the mat-datepicker input, while only sending the date in the backend

enter image description hereIn this code snippet, there is a date input field along with a Permanent button. The scenario is that when the Permanent button is clicked, it should display "Permanent" in the input UI (nativeElements value), but the value bein ...