【发布时间】: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