tgd-backend/src/state/state.controller.ts
2024-11-20 14:24:46 +04:00

58 lines
2 KiB
TypeScript

import {Body, Controller, Get, Inject, Logger, Param, Post} from '@nestjs/common';
import {StateService} from './state.service';
import {SharedService} from '../shared/shared.service';
import {EventBus} from '@nestjs/cqrs';
import {GameStartedEvent} from '../game/events/game-started.event';
import {ClientProxy} from "@nestjs/microservices";
import {CommandsConsts} from "../Consts/commands.consts";
import {MqtMessageModel} from "../messaging/models/mqt-message.model";
import {ClientNotificationType} from "../socket/socket.gateway";
import {IStateInfo} from "../Consts/types";
interface SetStateDTO {
state: string;
value: string;
}
@Controller('state')
export class StateController {
private readonly logger = new Logger(StateController.name);
constructor(
private stateService: StateService,
private sharedService: SharedService,
private eventBus: EventBus,
@Inject('Telegram') private telegramService: ClientProxy,
) {}
@Get(':name')
async getState(@Param('name') name: string) {
return await this.stateService.getState(name);
}
@Post()
async setState(@Body() setStateDto: SetStateDTO) {
const res = await this.stateService.setState(
setStateDto.state,
setStateDto.value,
);
if (setStateDto.value === 'quiz') {
this.eventBus.publish(new GameStartedEvent());
} else if(setStateDto.value === 'onboarding') {
this.telegramService.send<MqtMessageModel,any>(
{ cmd: CommandsConsts.SetCommands },
[
{ command: 'start', description: 'главное меню'},
{ command: 'cards', description: 'сыграть карту'},
{ command: 'question', description: 'вернутся к вопросу'}
]
).subscribe(() => {
this.logger.verbose('Bot commands updated');
});
} else {
this.logger.verbose('reset commands');
this.telegramService.emit({ cmd: CommandsConsts.ResetCommands }, {});
}
this.sharedService.notifyAllClients<IStateInfo>(ClientNotificationType.StateChanged, res);
return res;
}
}