How to use the @nestjs/microservices.MessagePattern function in @nestjs/microservices

To help you get started, weโ€™ve selected a few @nestjs/microservices examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github neoteric-eu / nestjs-auth / src / app / message / message.controller.ts View on Github external
}
		});
		this.logger.debug(`[onMessageNew] how manny conversation ${userConversations.length} to update`);
		for (const userConversation of userConversations) {
			this.logger.debug(`[onMessageNew] if user ${userConversation.userId} if offline, send to him notification`);
			if (this.onlineService.isOffline({id: userConversation.userId} as UserEntity)) {
				this.logger.debug(`[onMessageNew] user ${userConversation.userId} is offline`);
				this.messageBuffer.addMessage(userConversation.userId, message);
			}
			userConversation.updatedAt = DateTime.utc();
			await userConversation.save();
			await this.messageService.pubSub.publish('userConversationUpdated', {userConversationUpdated: userConversation});
		}
	}

	@MessagePattern({cmd: OFFLINE_MESSAGE_CMD_NEW})
	public whenOfflineMessageNew(message: MessageEntity) {

	}
}
github vendure-ecommerce / vendure / packages / core / src / service / controllers / collection.controller.ts View on Github external
import { ProductVariant } from '../../entity/product-variant/product-variant.entity';
import { CollectionService } from '../services/collection.service';
import { ApplyCollectionFiltersMessage } from '../types/collection-messages';

/**
 * Updates collections on the worker process because running the CollectionFilters
 * is computationally expensive.
 */
@Controller()
export class CollectionController {
    constructor(
        @InjectConnection() private connection: Connection,
        private collectionService: CollectionService,
    ) {}

    @MessagePattern(ApplyCollectionFiltersMessage.pattern)
    applyCollectionFilters({
        collectionIds,
    }: ApplyCollectionFiltersMessage['data']): Observable {
        return new Observable(observer => {
            (async () => {
                Logger.verbose(`Processing ${collectionIds.length} Collections`);
                const timeStart = Date.now();
                const collections = await this.connection.getRepository(Collection).findByIds(collectionIds, {
                    relations: ['productVariants'],
                });
                let completed = 0;
                for (const collection of collections) {
                    const affectedVariantIds = await this.applyCollectionFiltersInternal(collection);

                    observer.next({
                        total: collectionIds.length,
github nestjs / nest / integration / microservices / src / redis / redis.controller.ts View on Github external
@HttpCode(200)
  concurrent(@Body() data: number[][]): Promise {
    const send = async (tab: number[]) => {
      const expected = tab.reduce((a, b) => a + b);
      const result = await this.client
        .send({ cmd: 'sum' }, tab)
        .toPromise();

      return result === expected;
    };
    return data
      .map(async tab => send(tab))
      .reduce(async (a, b) => (await a) && b);
  }

  @MessagePattern({ cmd: 'sum' })
  sum(data: number[]): number {
    return (data || []).reduce((a, b) => a + b);
  }

  @MessagePattern({ cmd: 'asyncSum' })
  async asyncSum(data: number[]): Promise {
    return (data || []).reduce((a, b) => a + b);
  }

  @MessagePattern({ cmd: 'streamSum' })
  streamSum(data: number[]): Observable {
    return of((data || []).reduce((a, b) => a + b));
  }

  @MessagePattern({ cmd: 'streaming' })
  streaming(data: number[]): Observable {
github nestjs / nest / integration / microservices / src / redis / redis.controller.ts View on Github external
return data
      .map(async tab => send(tab))
      .reduce(async (a, b) => (await a) && b);
  }

  @MessagePattern({ cmd: 'sum' })
  sum(data: number[]): number {
    return (data || []).reduce((a, b) => a + b);
  }

  @MessagePattern({ cmd: 'asyncSum' })
  async asyncSum(data: number[]): Promise {
    return (data || []).reduce((a, b) => a + b);
  }

  @MessagePattern({ cmd: 'streamSum' })
  streamSum(data: number[]): Observable {
    return of((data || []).reduce((a, b) => a + b));
  }

  @MessagePattern({ cmd: 'streaming' })
  streaming(data: number[]): Observable {
    return from(data);
  }

  @Post('notify')
  async sendNotification(): Promise {
    return this.client.emit('notification', true);
  }

  @EventPattern('notification')
  eventHandler(data: boolean) {
github nestjs / nest / integration / microservices / src / kafka / kafka-broadcast.controller.ts View on Github external
import { Observable } from 'rxjs';
import { scan, take } from 'rxjs/operators';

@Controller()
export class KafkaBroadcastController {
  @Client({ transport: Transport.KAFKA })
  client: ClientProxy;

  @Get('broadcast')
  multicats() {
    return this.client
      .send('broadcast.test', {})
      .pipe(scan((a, b) => a + b), take(2));
  }

  @MessagePattern('broadcast.*')
  replyBroadcast(): Observable {
    return new Observable(observer => observer.next(1));
  }
}
github neoteric-eu / nestjs-auth / src / app / home-media / home-media.controller.ts View on Github external
import {MEDIA_CMD_DELETE} from '../media/media.constants';
import {HomeMediaService} from './home-media.service';

@Controller('home-favorite')
export class HomeMediaController {

	@Client({ transport: Transport.TCP })
	private client: ClientProxy;

	private logger = new AppLogger(HomeMediaController.name);

	constructor(private readonly homeMediaService: HomeMediaService) {

	}

	@MessagePattern({ cmd: HOME_CMD_DELETE })
	public async onMediaDelete(home: HomeEntity): Promise {
		this.logger.debug(`[onMediaDelete] soft delete all medias for home ${home.id}`);
		const homeMedias = await this.homeMediaService.findAll({where: {homeId: home.id.toString()}});
		await this.homeMediaService.updateAll({homeId: {eq: home.id.toString()}}, {'$set': {isDeleted: true}});
		for (const homeMedia of homeMedias) {
			this.client.send({cmd: MEDIA_CMD_DELETE}, homeMedia).subscribe(() => {}, error => {
				this.logger.error(error, '');
			});
		}
	}
}
github nestjs / nest / integration / microservices / src / rmq / rmq.controller.ts View on Github external
@MessagePattern({ cmd: 'sum' })
  sum(data: number[]): number {
    return (data || []).reduce((a, b) => a + b);
  }

  @MessagePattern({ cmd: 'asyncSum' })
  async asyncSum(data: number[]): Promise {
    return (data || []).reduce((a, b) => a + b);
  }

  @MessagePattern({ cmd: 'streamSum' })
  streamSum(data: number[]): Observable {
    return of((data || []).reduce((a, b) => a + b));
  }

  @MessagePattern({ cmd: 'streaming' })
  streaming(data: number[]): Observable {
    return from(data);
  }

  @Post('notify')
  async sendNotification(): Promise {
    return this.client.emit('notification', true);
  }

  @EventPattern('notification')
  eventHandler(data: boolean) {
    RMQController.IS_NOTIFIED = data;
  }
}
github nestjs / nest / integration / microservices / src / app.controller.ts View on Github external
@HttpCode(200)
  concurrent(@Body() data: number[][]): Promise {
    const send = async (tab: number[]) => {
      const expected = tab.reduce((a, b) => a + b);
      const result = await this.client
        .send({ cmd: 'sum' }, tab)
        .toPromise();

      return result === expected;
    };
    return data
      .map(async tab => send(tab))
      .reduce(async (a, b) => (await a) && b);
  }

  @MessagePattern({ cmd: 'sum' })
  sum(data: number[]): number {
    return (data || []).reduce((a, b) => a + b);
  }

  @MessagePattern({ cmd: 'asyncSum' })
  async asyncSum(data: number[]): Promise {
    return (data || []).reduce((a, b) => a + b);
  }

  @MessagePattern({ cmd: 'streamSum' })
  streamSum(data: number[]): Observable {
    return of((data || []).reduce((a, b) => a + b));
  }

  @MessagePattern({ cmd: 'streaming' })
  streaming(data: number[]): Observable {
github TheAifam5 / nestjs-docker-microservices / microservices / users / src / app.controller.ts View on Github external
import { Controller } from '@nestjs/common';
import { MessagePattern, ClientProxy, Transport, Client } from '@nestjs/microservices';
import { Observable } from 'rxjs';

import { UserDto } from '@shared/dto/user.dto';
import { CreateUserDto } from '@shared/dto/create-user.dto';

@Controller()
export class AppController {
  @Client({ transport: Transport.TCP, options: { port: 3001 } })
  private db: ClientProxy;

  @MessagePattern({ cmd: 'create' })
  public create(dto: CreateUserDto): Observable {
    return this.db.send({ cmd: 'create' }, dto);
  }

  @MessagePattern({ cmd: 'findAll' })
  public findAll(data: string): Observable {
    return this.db.send({ cmd: 'findAll' }, data);
  }
}
github ConnextProject / indra / modules / node / src / app.controller.ts View on Github external
import { AppService } from "./app.service";
import { CLogger } from "./util";

const logger = new CLogger("AppController");

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @MessagePattern("hello")
  getHelloMessage(data: any): string {
    logger.log(`Got Hello message, data: ${JSON.stringify(data)}`);
    return this.appService.getHello();
  }
}