NestJS:将自定义服务注入 MongooseModule

时间:2021-04-26 13:52:21

标签: node.js mongoose nestjs

尝试注入我自己的 GoogleService 以在 Facility 架构的预保存挂钩中使用它。但是,一旦我添加 imports: [GoogleModule],就不会在没有任何错误的情况下调用预保存钩子。相同类型的注入适用于默认的 ConfigModule

google.module.ts:

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { GoogleService } from './google.service';

@Module({
  imports: [ConfigModule],
  providers: [GoogleService],
  exports: [GoogleService]
})
export class GoogleModule { }

facilities.module.ts:

import { MongooseModule } from '@nestjs/mongoose';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as zip2tz from 'zipcode-to-timezone';


import { FacilitiesService } from './facilities.service';
import { UsersModule } from '../users/users.module';
import { ShiftTemplatesModule } from '../shift-templates/shift-templates.module';

import { FacilitiesController } from './facilities.controller';
import { Facility, FacilitySchema, FacilityDocument } from './schemas/facility.schema';
import { MailerModule } from '../thirdparty/mailer/mailer.module';
import { ServicedStatesModule } from './../serviced-states/serviced-states.module';
import { GoogleModule } from '../thirdparty/google/google.module';
import { GoogleService } from '../thirdparty/google/google.service';

@Module({
    imports: [
        ShiftTemplatesModule,
        MongooseModule.forFeatureAsync([{
            imports: [GoogleModule],
            inject: [GoogleService],
            name: Facility.name,
            useFactory: async (googleService: GoogleService) => {
                const schema = FacilitySchema;
                schema.pre<FacilityDocument>('save', async function (next) {
                    console.log('****************************8') //this isn't invoked, however it is with no imports
                    console.log('PRESAVE')
                    if (!this.timezone || this.isModified('address')) {
                        this.timezone = zip2tz.lookup(this.address.zip) || 'America/New_York';
                    }
                    if (!this.address.lat || !this.address.long || this.isModified('address')) {
                        this.address = await googleService.attachCoordinatesToAddress(this.address);
                    }
                    next();
                });
                return schema;
            }
        }]),
        UsersModule,
        MailerModule,
        ConfigModule,
        ServicedStatesModule,
        GoogleModule
    ],
    controllers: [FacilitiesController],
    providers: [FacilitiesService],
    exports: [FacilitiesService]
})
export class FacilitiesModule { }

0 个答案:

没有答案