Files
webapp-back/src/word/controllers/word.controller.ts
T
2024-12-29 12:04:19 +01:00

97 lines
2.6 KiB
TypeScript

import {
Body,
Controller,
Delete,
Get,
HttpException,
HttpStatus,
Param,
ParseIntPipe,
Post,
Put,
Sse,
UseGuards,
} from '@nestjs/common';
import { WordService } from '../services/word.service';
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from 'src/users/guards/auth.guard';
import { WordResponseDTO } from '../../../events/dto/wordresponse.dto';
import { WordRecieveDTO } from '../dto/wordrecieve.dto';
import { WordPipe } from '../pipe/word.pipe';
import { Word } from '../entities/word.entity';
import { GetUser } from 'src/users/user.pipe';
import { User } from 'src/users/entities/user.entity';
import { fromEvent, map, Observable } from 'rxjs';
import { EventEmitter2 } from '@nestjs/event-emitter';
@ApiTags('words')
@Controller('words')
export class WordController {
constructor(
private readonly wordService: WordService,
private eventEmitter: EventEmitter2,
) {}
@Sse('/subscribe')
subscribe(): Observable<{ data: string }> {
return fromEvent(this.eventEmitter, this.wordService.sse_prefix).pipe(
map((payload) => {
return {
data: JSON.stringify(payload),
};
}),
);
}
@Delete()
@ApiOperation({ summary: 'Delete a word' })
@UseGuards(AuthGuard)
async delete(@Param('id') id: number) {
const word = await this.wordService.getById(id);
if (!word) {
throw new HttpException('Word not found', HttpStatus.NOT_FOUND);
}
await this.wordService.delete(word);
}
@Post('/')
@ApiOperation({ summary: 'Submit a word' })
@ApiBody({ type: WordRecieveDTO })
@UseGuards(AuthGuard)
async create(@Body('value') value: string, @GetUser() user: User) {
const word = await this.wordService.create(value, user);
return new WordResponseDTO(word);
}
@Get('/')
@ApiOperation({ summary: 'List enabled words' })
async read() {
return (await this.wordService.listActive()).map(
(w) => new WordResponseDTO(w),
);
}
@Get('/all')
@ApiOperation({ summary: 'List all words' })
async readAll() {
return (await this.wordService.list()).map((w) => new WordResponseDTO(w));
}
@Put('/enable/:id')
@ApiOperation({ summary: 'Enable a word' })
@UseGuards(AuthGuard)
async enable(@Param('id', ParseIntPipe, WordPipe) word: Word) {
await this.wordService.enable(word);
return new WordResponseDTO(word);
}
@Put('/disable/:id')
@ApiOperation({ summary: 'Disable a word' })
@UseGuards(AuthGuard)
async disable(@Param('id', ParseIntPipe, WordPipe) word: Word) {
await this.wordService.enable(word);
return new WordResponseDTO(word);
}
}