Skip to content

Instantly share code, notes, and snippets.

@ancyrweb
Last active July 8, 2022 17:22
Show Gist options
  • Save ancyrweb/02faadd0916803b54690cb0c2efee308 to your computer and use it in GitHub Desktop.
Save ancyrweb/02faadd0916803b54690cb0c2efee308 to your computer and use it in GitHub Desktop.
import { Body, Controller, Post } from '@nestjs/common';
import { AppService } from './app.service';
import { CommentDTO } from './comment.interfaces';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Post()
addComment(@Body() data: CommentDTO) {
return this.appService.addComment(data);
}
}
import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
BullModule.registerQueue({
name: 'emails',
redis: {
host: 'localhost',
port: 7003,
},
}),
EventEmitterModule.forRoot({}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { CommentEvents, NewCommentEvent } from './comment.events';
import { CommentDTO } from './comment.interfaces';
@Injectable()
export class AppService {
constructor(private readonly eventEmitter: EventEmitter2) {}
addComment(data: CommentDTO) {
// First we validate and save our comment inside a database
// We'll skip that part inside this exemple.
// Then we emit the event that a new comment has been added
// note that we use emitAsync to avoid blocking the thread
this.eventEmitter.emitAsync(
CommentEvents.NewComment,
new NewCommentEvent(data),
);
// Then our work is done, we return here.
return {
done: true,
};
}
}
import { CommentDTO } from './comment.interfaces';
export enum CommentEvents {
NewComment = 'comments.new',
}
export class NewCommentEvent {
constructor(public comment: CommentDTO) {}
}
export type CommentDTO = {
text: string;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment