In NestJS, I have to use a module service into an entity/model to populate data into elastic-search index. populating elastic search index logic is written in Job.service.ts.
I want to call that onCreate method from Job.service.ts from sequelize hooks present in models.
Here is code for Job.ts model/entity -
import { Table, Model, Column, AutoIncrement, PrimaryKey } from "sequelize-typescript";
#Table({ schema: "job", tableName: "job" })
export class Job extends Model<Job> {
#AutoIncrement
#PrimaryKey
#Column
id: number;
#Column
title: string;
#AfterCreate
static async jobAfterCreate(instance, options) {
// <--- need to call job service onCreate method here
}
#AfterUpdate
static async jobAfterUpdate() {}
#AfterDestroy
static async jobAfterDestroy() {}
}
and here is code for Job.service.ts -
//imports not added
#Injectable()
export class JobService {
constructor(
#Inject("SEQUELIZE")
private readonly sequelizeInstance: Sequelize,
#Inject(forwardRef(() => ElasticsearchService))
private readonly elasticsearchService: ElasticsearchService,
#InjectModel(Job)
private jobModel: typeof Job
) {}
// here will write logic for updating elastic search index
async onCreate(instance, options){
console.log("ON CREATE INSTANCE:", instance);
console.log("ON CREATE OPTIONS:", options);
}
async onDestroy(instance, options){
console.log("ON DESTROY INSTANCE:", instance);
console.log("ON DESTROY OPTIONS:", options);
}
}
I tried injecting service into Job model but it did not worked.
And I cannot write elastic search logic inside model directly because for that I need ElasticsearchService.
The Solution is To Override the provider
The primary way to inject information into the models is by overriding the injection behavior.
First, you would need to add a static property referencing the service in your model.
I am going to use the event emitter as an example here.
Your Model Class
import {Model, Table, Column, AfterCreate} from "sequelize-typescript";
import { EventEmitter2 } from "#nestjs/event-emitter";
#Table()
export class SomeModel extends <SomeModel> {
// this would be your referencing
public static EventEmitter: EventEmitter2;
#Column
public someColumn: string;
#AfterCreate
public static triggerSomeEvent(instance: SomeModel) {
SomeModel.EventEmitter.emit('YourEvent', instance);
}
}
The module where you are going to use the model
Now we are overriding the default injection process.
import { EntitiesMetadataStorage } from '#nestjs/sequelize/dist/entities-metadata.storage';
import {
getConnectionToken,
getModelToken,
SequelizeModule,
} from '#nestjs/sequelize';
import { EventEmitter2 } from '#nestjs/event-emitter';
// The provider override
const modelInjector: Provider = {
provide: getModelToken(AccountabilityPartnerModel, DEFAULT_CONNECTION_NAME),
useFactory: (connection: Sequelize, eventEmitter: EventEmitter2) => {
SomeModel.EventEmitter = eventEmitter;
if (!connection.repositoryMode) {
return SomeModel;
}
return connection.getRepository(SomeModelas any);
},
inject: [getConnectionToken(DEFAULT_CONNECTION_NAME), EventEmitter2],
};
// Updating the meta information of sequelize-typescript package to handle connection injection in to the model overridden.
EntitiesMetadataStorage.addEntitiesByConnection(DEFAULT_CONNECTION_NAME, [
SomeModel,
]);
// our custom module being used rather than the Sequelize.forFeature([SomeModel])
const someModelModule: DynamicModule = {
module: SequelizeModule,
providers: [modelInjector],
exports: [modelInjector],
};
#Module({
imports: [someModelModule],
providers: [SomeService],
})
export class SomeModule {
}
Inject your model into your service as you would do using Sequlize.forFeature and InjectModel indicated as below.
#Injectable()
export class SomeService {
constructor(#InjectModel(SomeModel) someModel: typeof SomeModel) {}
public someFunction(data: any) {
this.someModel.EventEmitter.emit('YourEvent', data);
}
}
Related
I have a NestJS App and I have a Class where the app generates multiple instances from. Inside that class I need to access a service method but I dont know how to inject a service into a plain class.
This is the service I want to use inside the class "Stream"
import { Injectable } from '#nestjs/common';
import * as technicalindicators from 'technicalindicators';
import { CandleIndex } from 'src/utils/CandleIndex';
import * as ccxt from 'ccxt';
#Injectable()
export class AnalysisService {
async RSI(ohlcv: ccxt.OHLCV[], period: number) {
const close = ohlcv.map((candle) => candle[CandleIndex.CLOSE]);
const result = technicalindicators.rsi({ values: close, period: period });
return result;
}
}
import { AnalysisService } from './analysis.service';
import { Module } from '#nestjs/common';
#Module({
imports: [],
controllers: [],
providers: [AnalysisService],
exports: [AnalysisService],
})
export class AnalysisModule {}
Here is the class I want to get access to the analysis service. The class is a normal typescript class, its not part of any module.
export class Stream {
private exchange: ccxt.Exchange;
private market: ccxt.Market;
private timeframe: string;
private ohlcv_cache: ccxt.OHLCV[];
private createdAt: Date;
private stream;
#Inject(AnalysisService)
private readonly analysisService: AnalysisService;
constructor(exchange: ccxt.Exchange, market: ccxt.Market, timeframe: string) {
this.exchange = exchange;
this.market = market;
this.timeframe = timeframe;
this.createdAt = new Date();
this.initialize();
console.log(this.analysisService);
}
}
When I do this and call a method of the analysis service inside of the Stream class, analysisService is undefined.
As you're calling new Stream() yourself, Nest will do no injection for you. You'd need to either pass the AnalysisService instance yourself, or you'd need to create a setter for that property before running any methods that need the AnalysisService.
I have an app that receives a service as a dependency on the controller, so far so good, but I would like to find a way to instead of declaring the specific implementation of that service, to be able to "ask" from the controller for the interface that this service implements to decouple of the concrete implementation of that service. How is this done in nest js?
To do this you have to create an injection token for your interface and use the #Inject() decorator with the injection token when injecting your service. Then in your module you can declare which implementation to provide for that injection token.
Below is a simple greeting service interface and our injection token that will be used when registering our service as a provider.
greeting-service.interface.ts
// This will be our injection token.
export const GREETING_SERVICE = 'GREETING SERVICE';
export interface IGreetingService {
greet(name: string): Promise<string>;
}
A basic service that will implements our greeting interface...
professional-greeting.service.ts
import { Injectable } from '#nestjs/common';
import { IGreetingService } from './greeting-service.interface';
#Injectable()
export class ProfessionalGreetingService implements IGreetingService {
public async greet(name: string): Promise<string> {
return `Hello ${name}, how are you today?`;
}
}
And our greeting module where we register our service using the token...
greeting.module.ts
import { Module } from '#nestjs/common';
import { ProfessionalGreetingService } from './services/professional-greeting.service';
import { GREETING_SERVICE } from './services/greeting-service.interface';
import { GreetingController } from './controllers/greeting.controller';
#Module({
providers: [
{
// You can switch useClass to different implementation
useClass: ProfessionalGreetingService,
provide: GREETING_SERVICE
}
],
controllers: [
GreetingController
]
})
export class GreetingModule {}
Now when we inject our service, we can use the #Inject() decorator with our injection token. Whichever implementation you provived to useClass in our GreetingModule will be injected...
greeting.controller.ts
import { Controller, Get, Inject, Query } from '#nestjs/common';
import { GREETING_SERVICE, IGreetingService } from '../services/greeting-service.interface';
#Controller('greeting')
export class GreetingController {
constructor(
#Inject(GREETING_SERVICE)
private readonly _greetingService: IGreetingService
) {}
#Get()
public async getGreeting(#Query('name') name: string): Promise<string> {
return await this._greetingService.greet(name || 'John');
}
}
https://jasonwhite.xyz/posts/2020/10/20/nestjs-dependency-injection-decoupling-services-with-interfaces/
https://github.com/jmw5598/nestjs-di-decoupling-with-interfaces
https://docs.nestjs.com/fundamentals/custom-providers
I am working on an API with NestJS, and because I have DTO's I am using an AutoMapper (made by #nartc and/or nestjsx), I have tried to make my example as small as I could with the Foo example, because I use multiple files.
This is my module:
// foo.module.ts
import { Module } from "#nestjs/common";
import { MongooseModule } from "#nestjs/mongoose";
import { Foo, FooSchema } from "./foo.entity.ts";
import { FooController } from "./foo.controller.ts";
import { FooService } from "./foo.service.ts";
import { FooProfile } from "./foo.profile.ts";
#Module({
imports: [
MongooseModule.forFeature([
{
name: Foo.name,
schema: FooSchema,
collection: "foos",
}
])
// FooProfile <-- if I uncomment this, the program will give the error (shown at the bottom of this question)
],
controllers: [FooController],
providers: [FooProivder],
})
export class FooModule {}
This is my entity:
// foo.entity.ts
import { Schema, SchemaFactory, Prop } from "#nestjs/mongoose";
import { Document } from "mongoose";
#Schema()
export class Foo extends Document { // if I remove the `extends Document` it works just fine
#Prop({ required: true })
name: string;
#Prop()
age: number
}
export const FooSchema = SchemaFactory.createForClass(Foo);
This is my DTO:
// foo.dto.ts
export class FooDTO {
name: string;
}
This is my controller:
// foo.controller.ts
import { Controller, Get } from "#nestjs/common";
import { InjectMapper, AutoMapper } from "nestjsx-automapper";
import { Foo } from "./foo.entity";
import { FooService } from "./foo.service";
import { FooDTO } from "./dto/foo.dto";
#Controller("foos")
export class FooController {
constructor(
private readonly fooService: FooService
#InjectMapper() private readonly mapper: AutoMapper
) {}
#Get()
async findAll() {
const foos = await this.fooService.findAll();
const mappedFoos = this.mapper.mapArray(foos, Foo, FooDTO);
// ^^ this throws an error of the profile being undefined (duh)
return mappedFoos;
}
}
This is my profile:
// foo.profile.ts
import { Profile, ProfileBase, InjectMapper, AutoMapper } from "nestjsx-automapper";
import { Foo } from "./foo.entity";
import { FooDTO } from "./foo.dto";
#Profile()
export class FooProfile extends ProfileBase {
constructor(#InjectMapper() private readonly mapper: AutoMapper) {
// I've read somewhere that the `#InjectMapper() private readonly` part isn't needed,
// but if I exclude that, it doesn't get the mapper instance. (mapper will be undefined)
super();
this.mapper.createMap(Foo, FooDTO);
}
}
If I uncomment the line I highlighted in the module, it will result in the following error..
[Nest] 11360 - 2020-08-18 15:53:06 [ExceptionHandler] Cannot read property 'plugin' of undefined +1ms
TypeError: Cannot read property 'plugin' of undefined
at Foo.Document.$__setSchema ($MYPATH\node_modules\mongoose\lib\document.js:2883:10)
at new Document ($MYPATH\node_modules\mongoose\lib\document.js:82:10)
at new Foo($MYPATH\dist\foo\foo.entity.js:15:17)
I have also referred to this answer on stackoverflow, but that doesn't work for me either. I have also combined that with the documentation, but with no luck.. How would I get the AutoMapper to register my profiles?
Update
The error seems to originate from the foo entity, if I remove the extends Document and the Schema(), Prop({ ... }) from the class it works fine, it seems like I have to inject mongoose or something?
In your module, just import the path to the profile like below:
import 'relative/path/to/foo.profile';
By importing the path to file, TypeScript will include the file in the bundle and then the #Profile() decorator will be executed. When #Profile() is executed, AutoMapperModule keeps track of all the Profiles then when it's turn for NestJS to initialize AutoMapperModule (with withMapper() method), AutoMapperModule will automatically add the Profiles to the Mapper instance.
With that said, in your FooProfile's constructor, you'll get AutoMapper instance that this profile will be added to
#Profile()
export class FooProfile extends ProfileBase {
// this is the correct syntax. You would only need private/public access modifier
// if you're not going to use this.mapper outside of the constructor
// You DON'T need #InjectMapper() because that's Dependency Injection of NestJS.
// Profile isn't a part of NestJS's DI
constructor(mapper: AutoMapper) {
}
}
The above answer will solve your problems with AutoMapper. As far as your Mongoose problem, I would need a sample repro to tell for sure. And also, visit our Discord for this kind of question.
What worked for me.
1. Updated all the absolute paths for models, schemas, entities (is easy if you search for from '/src in your projects, and update all the routes to relative paths)
from:
import { User } from 'src/app/auth/models/user/user.entity';
to:
import { User } from './../../auth/models/user/user.entity';
2. mongoose imports:
from:
import mongoose from 'mongoose';
to:
import * as mongoose from 'mongoose';
3. Remove validation pipe if you don't use it. For some reason (I think i don't use them on the controller, I didn't investigate, I've removed from one controller the Validation Pipe) so If you have this try it:
from:
#Controller('someroute')
#UsePipes(new ValidationPipe())
export class SomeController {}
to:
#Controller('someroute')
export class SomeController {}
I hope my solution worked for you ^_^
When I use Custom Repository class without any extension then I run into the error: No repository for "MasterDataRepo" was found. Looks like this entity is not registered in current "default" connection?
#EntityRepository()
export class MasterDataRepo {
constructor(private manager: EntityManager) {
}
getDriveryByTerminal(terminalCode: string):Promise<Driver> {
return this.manager.findOne(Driver, { terminalCode });
}
}
The app works fine if I create repository class after extending Repository<Entity>
#EntityRepository(Driver)
export class MasterDataRepo extends Repository<Driver> {
getDriveryByTerminal(terminalCode: string):Promise<Driver> {
return this.manager.findOne(Driver, { terminalCode });
}
}
My MasterDataModule is:
import { Module } from '#nestjs/common';
import { MasterDataController } from './MasterData.controller';
import { MasterDataService } from './masterData.service';
import { TypeOrmModule } from '#nestjs/typeorm';
import { MasterDataRepo } from './MasterData.Repo';
#Module({
imports: [
TypeOrmModule.forFeature([MasterDataRepo])
],
controllers: [MasterDataController],
providers: [MasterDataService],
})
export class MasterDataModule {}
and AppModule is:
import { Module } from '#nestjs/common';
import { TasksModule } from './tasks/tasks.module';
import { TypeOrmModule } from '#nestjs/typeorm';
import { typeOrmConfig } from './config/typeorm.config';
import { MasterDataModule } from './masterData/MasterData.module';
import { Connection } from 'typeorm';
#Module({
imports: [
TypeOrmModule.forRoot(typeOrmConfig),
TasksModule,
MasterDataModule
],
})
export class AppModule {
constructor(private connection: Connection) {}
}
TypeOrmModule.forFeature([MasterDataRepo])
TypeOrmModule.forFeature accepts array of Entities and your MasterDataRepo is not an entity.
But when you use EntityRepository decorator with the User entity, it will add your User entity to the available entities list(which will be applied to the database connection).
Also extending the Repository class will make your MasterDataRepo as an extended version of an Entity.
https://github.com/typeorm/typeorm/blob/906d97fc8dbf1dba8f4e579a4f5bfead83af36ab/src/decorator/EntityRepository.ts
https://github.com/typeorm/typeorm/blob/906d97fc8dbf1dba8f4e579a4f5bfead83af36ab/src/repository/Repository.ts
Note:
There are two solutions:
Nestjs already provides #nestjs/typeorm module and you can inject a repository for an entity easily in your service.
For example:
#Injectable()
export class UsersService {
constructor(
#InjectRepository(User)
private usersRepository: Repository<User>
) {}
...
}
You can check the documentation here - https://docs.nestjs.com/techniques/database
You can just use Active Record pattern that doesn't require a repository.
What you need to do is just to make your entities extend BaseEntity of typeorm.
For example:
#Entity()
export class User extends BaseEntity {} // <- BaseEntity
...
const user = await User.find({}) // You just use the User class for executing a query.
user.name = 'something';
await user.save();
Thanks, #yash. I could find a workaround. Defined the repo as injecatable
#Injectable()
#EntityRepository()
export class MasterDataRepo {
constructor(private manager: EntityManager) {
}
getDriveryByTerminal(terminalCode: string):Promise<Driver> {
return this.manager.findOne(Driver, { terminalCode });
}
}
and the service as
#Injectable()
export class MasterDataService {
constructor(
private masterDataRepo: MasterDataRepo,
) {}
}
Do you see any concerns?
For those using TypeORM and who had the Injection configured correctly but still running into the error:
In my case, the issue was that my #Entity was not registered in the Postgres TypeOrmModuleOptions (more precisely the entity array of the BaseConnectionOptions, cf their git repo ). Those options allow to configure Nest's TypeOrmModule
Hope this helps someone else coming to this thread
I have some Service classes as follows:
//Cat Service:
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository, getManager } from 'typeorm';
import { CatRepo } from '../tables/catrepo.entity';
import { CatInterface } from './cat.interface';
#Injectable()
export class CatService {
constructor(
#InjectRepository(CatRepo)
private catRepo: Repository<CatRepo>,
) {}
async customFindAll(offset:number, limit: number): Promise<CatRepo[]> {
const entityManager = getManager();
const catRows = await entityManager.query(
`
SELECT * FROM CATREPO
${offset ? ` OFFSET ${offset} ROWS ` : ''}
${limit ? `FETCH NEXT ${limit} ROWS ONLY` : ''}
`,
);
return catRows;
}
formResponse(cats: CatRepo[]): CatInterface[] {
const catsResults: CatInterface[] = [];
.
//form cat response etc.
.
//then return
return catsResults;
}
}
//Pet Service:
import { Injectable } from '#nestjs/common';
import { getManager } from 'typeorm';
import { PetInterface } from './pet.interface';
#Injectable()
export class PetService {
async customFindAll(offset:number, limit: number) {
const entityManager = getManager();
const petRows = await entityManager.query(
`
JOIN ON TABLES......
${offset ? ` OFFSET ${offset} ROWS ` : ''}
${limit ? `FETCH NEXT ${limit} ROWS ONLY` : ''}
`,
);
//returns list of objects
return petRows;
}
formResponse(pets): PetInteface[] {
const petsResults: PetInteface[] = [];
.
. //form pet response etc.
.
//then return
return petsResults;
}
}
I am running a cron BatchService that uses these two services subsequently saving the data into respective batch files.
I'm calling CatService and PetService from the BatchService as follows:
/Start the Batch job for Cats.
if(resource === "Cat") {
//Call Cat Service
result = await this.catService.findAllWithOffest(startFrom, fetchRows);
finalResult = this.catService.formResponse(result);
}
//Start the batch job for Pets.
if(resource === "Pet") {
//Call Pet Service
result = await this.petService.findAllWithOffest(startFrom, fetchRows);
finalResult = this.petService.formResponse(result);
}
However, instead of the above I want to use these Services dynamically.
In order to achieve the CatService and PetService now extends AbstractService...
export abstract class AbstractService {
public batchForResource(startFrom, fetchRows) {}
}
//The new CatService is as follows:
export class CatService extends AbstractService{
constructor(
#InjectRepository(CatRepo)
private catRepo: Repository<CatRepo>,
) {}
.
.
.
}
//the new PetService is:
export class PetService extends AbstractService{
constructor(
) {super()}
.
.
.
}
//the BatchService...
public getService(context: string) : AbstractService {
switch(context) {
case 'Cat': return new CatService();
case 'Pet': return new PetService();
default: throw new Error(`No service found for: "${context}"`);
}
}
However in the CatService I'm getting the a compilation error...(Expected 1 Argument but got 0). What should be the argument passed in the CatService.
Also, the larger question is if this can be achieved by using NestJS useValue/useFactory...If so how to do it?
You can probably use useFactory to dynamically retrieve your dependencies but there are some gotcha's.
You must make the lifecycle of your services transient, since NestJS dependencies are registered as singletons by default. If not, you would get the same first service injected each time, regardless of the context of subsequent calls.
Your context must come from another injected dependency - ExecutionContext, Request or something similarly dynamic, or something you register yourself.
Alternative
As an alternative, you can implement the "servicelocator/factory" pattern. You're already halfway there with your BatchService. Instead of your service creating instances of the CatService and PetService, you have it injected and just return the injected services depending on the context. Like so:
#Injectable()
export class BatchService {
constructor(
private readonly catService: CatService,
private readonly petService: PetService
)
public getService(context: string) : AbstractService {
switch(context) {
case 'Cat': return this.catService;
case 'Pet': return this.petService;
default: throw new Error(`No service found for: "${context}"`);
}
}
}
The alternative is more flexible than using useFactory, since your context is not limited to what is available in the DI container. On the negative side, it does expose some (usually unwanted) infrastructure details to the calling code, but that's the tradeoff you'll have to make.