【问题标题】:How would you pass a property from a nest service to a Schema's virtual property declaration?您如何将属性从嵌套服务传递到 Schema\ 的虚拟属性声明?
【发布时间】:2022-10-19 05:29:01
【问题描述】:

我正在将现有的 nodejs + mongoose API 迁移到 NestJS。 对于这个框架的新手,我只是按照官方网站上的文档设置了我的configuration服务和模块,并重新定义了我的schemas以使用@nestjs\mongoose提供的装饰器。

在我的第一个 API 上,我只是有一个导出的 ConfigClass,使用 Nest,我有一个在我的控制器中调用的服务。

我要做的是根据配置的值创建一个猫鼬虚拟字段。 由于我的配置现在存储在服务中,我怀疑我是否可以直接导入它并按原样使用它。

代码方面,我当前的配置模块和服务看起来像:

    //app-config.config.ts

    import { registerAs } from '@nestjs/config';

    export const AppConfiguration = registerAs('app', () => ({
      name: process.env.APP_NAME.trim(),
      host: process.env.APP_HOST.trim(),
    }));

    //app-config.service.ts
    
    import { Injectable } from '@nestjs/common';
    import { ConfigService } from '@nestjs/config';
    
    @Injectable()
    export class AppConfigService {
      constructor(private _config: ConfigService) {}
    
      get name(): string {
        return this._config.get<string>('app.name');
      }
    
      get host(): number {
        return this._config.get<number>('app.host');
      }
    }

    //app-config.module.ts
    
    import { Module } from '@nestjs/common';
    import { ConfigModule, ConfigService } from '@nestjs/config';
    import * as Joi from 'joi';
    
    import { AppConfiguration } from './app-config.config';
    import { AppConfigService } from './app-config.service';
    
    @Module({
      imports: [
        ConfigModule.forRoot({
          load: [AppConfiguration],
          validationSchema: Joi.object({
            APP_NAME: Joi.string().default('nest api'),
            APP_HOST: Joi.string().default('localhost.lan'),
          }),
        }),
      ],
      providers: [ConfigService, AppConfigService],
      exports: [AppConfigService],
    })
    export class AppConfigModule {}

我的架构看起来像:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

    @Schema({
      toObject: {
        virtuals: true,
      },
      toJSON: {
        virtuals: true,
      },
    })
    export class Category extends Document {
      @Prop({
        required: true,
      })
      name: string;
    }
    


    export const CategorySchema = SchemaFactory.createForClass(Category);

    //Before my virtual would simply look like this: 
    CategorySchema.virtual('access').get(function (this: Category) {
      // Config would be my configuration class directly imported, 
      //and now accessing my config property as wished.
      const url: URL = new URL('/download', Config.Host);
      // What I'd like to know, now is how I should proceed to get the same result
      // except with AppConfigService.host ? 
      url.searchParams.set('name', this.name);
      return url.toString();
    });

到目前为止,我考虑在 AppConfigModule 构造函数中设置 nodejs 全局变量,甚至考虑将所需的配置属性发送给客户端,并让客户端进行连接。

我正在寻找最干净的方法来做到这一点,我可能不知道内置方法。

提前致谢。如果我找到我的问题可接受的解决方案,我会保持更新。

【问题讨论】:

    标签: node.js mongodb mongoose nestjs mongoose-schema


    【解决方案1】:

    我终于在我的配置服务中将我的属性作为 nodejs 全局变量传递了。

    @Injectable()
    export class AppConfigService {
    
      get port(): number {
        return this._config.get<number>('app.port');
      }
    
      get host(): string {
        return this._config.get<string>('app.host');
      }
    
      get url(): string {
        const _url = new URL(`${this.host}:${this.port}`);
        return _url.href;
      }
    
      constructor(private _config: ConfigService) {
        global.api = this.url;
      }
    }
    

    我可能会将它们的声明从构造函数中移到方法中,甚至移到我的应用程序主文件中(因为在启动时调用了该服务)。但现在它正在完成这项工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 2014-11-25
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多