import { InjectQueue } from '@nestjs/bull'; import { Body, Controller, Get, NotFoundException, Param, Post } from '@nestjs/common'; import { QUEUE_NAME, ScreenshotsQueue } from './shared'; type CreateScreenshotJobDto = { pageUrl: URL, imageType: 'jpeg' | 'png' } @Controller('screenshots') export class ScreenshotsController { constructor(@InjectQueue(QUEUE_NAME) private readonly screenshotsQueue: ScreenshotsQueue) {} @Post() async createScreenshotJob(@Body() createScreenshotJobDto: CreateScreenshotJobDto) { const result = await this.screenshotsQueue.add(createScreenshotJobDto) return { jobId: result.id.toString() } } @Get(':id') async getJob(@Param('id') id: string) { const jobInfo = await this.screenshotsQueue.getJob(id) if (!jobInfo) { throw new NotFoundException() } switch (await jobInfo.getState()) { case 'completed': return { status: 'completed' } case 'failed': return { status: 'failed' } default: return { status: 'queued' } } } @Get(':id/result') async getScreenshot(@Param('id') id: string) { const jobInfo = await this.screenshotsQueue.getJob(id) if (!jobInfo) { throw new NotFoundException() } if (!await jobInfo.isCompleted()) { throw new NotFoundException() } return await jobInfo.returnvalue } }