【问题标题】:Is there a way to programmatically override a datasource url with nest config?有没有办法用嵌套配置以编程方式覆盖数据源 url?
【发布时间】:2022-01-27 11:37:57
【问题描述】:

我有一个 app.config.ts 文件,其中包含许多如下所示的配置变量:


export const exampleConfig = (config: ConfigService) => {
    // Do stuff

    return config.get('EXAMPLE')
}

我的 schema.prisma 文件需要一个数据库 URL...目前,我在 app.module.tsmain.ts 上使用此配置文件:

AppModule:


      ExampleModule.forRootAsync({
         imports: [ConfigModule],
         inject: [ConfigService],
         useFactory: exampleConfig
    }),


主要:


[...]
import { ConfigService } from '@nestjs/config';
import { exampleConfig } from './config/app.config';
[...]


(async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);

  [...]

  app.exampleCallThatNeedsConfig(exampleConfig(configService));

  await app.listen(3000);
})();

注意我总是在我的app.config.ts 上使用@nestjs/config configService 吗?这里的问题是,我的 schema.prisma 文件需要一个 DB_URL,但我不能使用 configService 也不能在那里使用类似的东西......我可以使用 env('DB_URL') 就像文档告诉我的那样,但我'我想在我的应用程序中继续使用相同的模式,所以我宁愿坚持使用 configService

【问题讨论】:

    标签: javascript node.js typescript nestjs prisma


    【解决方案1】:

    当我发布这个问题后,我最终找到了比我坚持的更接近的答案:基本上,我必须在我的 PrismaClient 上设置 URL(与 NestJS Prisma doc 一样),如下所示:

    [...]
    import { PrismaClient } from '@prisma/client'
    import { exampleConfig } from './config/app.config';
    
    @Injectable()
    export class PrismaService extends PrismaClient
      implements OnModuleInit {
    
    [...]
    
    const prisma = new PrismaClient({
      datasources: {
        db: {
          url: exampleConfig(configService),
        },
      },
    })
    

    https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#programmatically-override-a-datasource-url

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • @camille 你完全正确!我刚刚编辑了我的答案以改进它,感谢您的提醒!
    猜你喜欢
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2014-11-09
    • 2010-10-30
    相关资源
    最近更新 更多