thewolfx41
thewolfx41

Reputation: 65

How to pass custom data to a provider NestJS

Is there any way to pass information to a provider but not passing this information in the request?? I say it to be able to use the following provider with a @nestjs/schedule service, since they do not allow the REQUEST scope.

This is my databaseProvider where I connect dynamically to a mongo database depending on a request param. The idea is pass this information but not using request

import * as mongoose from 'mongoose';
import { Connection } from 'mongoose';
import { ExecutionContext, Scope } from "@nestjs/common";
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

export const databaseProviders = [
  {
    provide: 'DATABASE_CONNECTION',
    inject: [REQUEST],
    useFactory: (request: Request): Connection => {
      const _conn = mongoose.connections.find(
        (e) => e.name === `Dynamic${request.params.id}`,
      );
      if (_conn) {
        return _conn;
      } else {
        return mongoose.createConnection(
          `mongodb+srv://*:*@*.mongodb.net/Dynamic${request.params.id}?retryWrites=true&w=majority`,
          {},
        );
      }
    },
  },
];

And the same for choose the collection name of a model dynamically:

import { Connection } from 'mongoose';
import { TestSchema } from './schemas/test.schema';
import { Scope } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

export const testsProviders = [
  {
    provide: 'TEST_MODEL',
    useFactory: (connection: Connection, request: Request) => {
      return connection.model('Test', TestSchema, `test_${request.params.id}`);
    },
    inject: ['DATABASE_CONNECTION', REQUEST],
  }
];

the question is....how can I still using this providers on a schedule service that cannot use scope REQUEST ????

Upvotes: 0

Views: 683

Answers (1)

Sydwell
Sydwell

Reputation: 31

What about passing the service in the useFactory ?

Like so: useFactory: (config: ConfigService) => config.get('GQL_API')

Upvotes: 2

Related Questions