0

So I was able to connect to localhost:9200 successfully, but now I have to connect my NestJS server to Elastic Cloud using this:

{
   "encoded": <my_encoded_key>,
   "api_key": <my_api_key>,
   "id": <my_id>,
   "name": <my_name>
}

Also, I'm using aws elastic cloud so I have an apiUrl to connect to but nothing else

  1. I'm not sure how to establish the connection to the elastic cloud so I need a little guidance.
  2. Also, if I cannot directly connect to RDS, do I have to use axios or fetch?

Might sound stupid to some people, but thanks in advance..

I have tried to configure axios and use it because that's what my coworker tried.. but I think it's a little inefficient.. there should be another way?

1 Answers1

0

You don't necessarily need Axios to connect to a database with RDS. You can establish the connection using Prisma ORM just with the URL. Here's how you can set it up:

First, install Prisma to your application by running:

npm install prisma --save-dev
npx prisma
npx prisma init

Afterwards, you can configure your tables in the schema.prisma file:

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

Then, you can use a db.service.ts file to establish the connection and distribute the service via injection and the module file. Here's an example:

import { Injectable, OnModuleInit, OnModuleDestroy, INestApplication } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { PrismaUniversal } from 'prisma-decimal/lib/prisma.universal';

@Injectable()
export class DbService
  extends PrismaUniversal
  implements OnModuleInit {
  async onModuleInit() {
    // optional: this.models = ['table'];
    this.$use(this.convertDecimal);
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }

As for AWS Elastic Cloud, you can create a user, assign necessary permissions, and establish the connection using the keys.

One thing to add regarding AWS Elastic Cloud is the importance of managing your keys securely. It's recommended to use secure mechanisms for managing and storing your AWS keys, such as environment variables or AWS Secrets Manager.

Remember, the example above uses SQLite as the provider. To connect to an RDS instance, you'll need to change this to the appropriate database provider (like postgresql, mysql, etc.) and provide the correct connection string.

For your reference, Prisma supports a variety of databases such as PostgreSQL, MySQL, SQLite, and SQL Server. Be sure to choose the correct provider that matches your RDS database instance. Also, for production applications, it's typically best to avoid storing sensitive information like database URLs directly in your code. Consider using environment variables or a secure secrets manager for this purpose.

berat
  • 63
  • 5