feat: submission analyze sse

This commit is contained in:
2026-10-10 13:46:44 +03:30
parent f6075ba146
commit 5ac99d1772
4 changed files with 64 additions and 28 deletions
@@ -3,7 +3,7 @@ Content-Type: application/json
{ {
"phone": "09333026363", "phone": "09333026363",
"otp": "23122" "otp": "50226"
} }
{{ {{
@@ -3,3 +3,7 @@ Authorization: Bearer {{$global.accessToken}}
GET {{baseUrl}}/submissions GET {{baseUrl}}/submissions
Authorization: Bearer {{$global.accessToken}} Authorization: Bearer {{$global.accessToken}}
GET {{baseUrl}}/submissions/1/analyze
Accept: text/event-stream
Authorization: Bearer {{$global.accessToken}}
@@ -6,14 +6,14 @@ Authorization: Bearer {{$global.accessToken}}
"testId": 1 "testId": 1
} }
POST {{baseUrl}}/submissions/2/answer POST {{baseUrl}}/submissions/1/answer
Content-Type: application/json Content-Type: application/json
Authorization: Bearer {{$global.accessToken}} Authorization: Bearer {{$global.accessToken}}
{ {
"choiceId": 33 // "choiceId":
// "numericValue": 1 // "numericValue": 1
// "choiceIds": [] "choiceIds": [7, 9]
} }
POST {{baseUrl}}/submissions/1/analyze POST {{baseUrl}}/submissions/1/analyze
@@ -6,10 +6,11 @@ import {
HttpStatus, HttpStatus,
Param, Param,
Post, Post,
Res, MessageEvent,
Sse,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { ApiResponse } from '@nestjs/swagger'; import { ApiResponse, ApiProduces } from '@nestjs/swagger';
import { Public } from '../auth/decorators/public.decorator'; import { Public } from '../auth/decorators/public.decorator';
import { OptionalJwtGuard } from '../auth/guards/optional-jwt.guard'; import { OptionalJwtGuard } from '../auth/guards/optional-jwt.guard';
import { User } from '../users/entities/user.entity'; import { User } from '../users/entities/user.entity';
@@ -24,6 +25,8 @@ import { GetAnswerSubmissionDTO } from './dtos/responses/get-answer-submission.d
import { GetSubmissionHistoryDTO } from './dtos/responses/get-submission-history.dto'; import { GetSubmissionHistoryDTO } from './dtos/responses/get-submission-history.dto';
import { GetSubmissionDetailDTO } from './dtos/responses/get-submission-detail.dto'; import { GetSubmissionDetailDTO } from './dtos/responses/get-submission-detail.dto';
import type { Response } from 'express'; import type { Response } from 'express';
import { Observable } from 'rxjs';
import { I18nService } from 'nestjs-i18n';
@Controller('submissions') @Controller('submissions')
export class SubmissionsController { export class SubmissionsController {
@@ -32,6 +35,11 @@ export class SubmissionsController {
* Inject Submissions Service * Inject Submissions Service
*/ */
private readonly submissionsService: SubmissionsService, private readonly submissionsService: SubmissionsService,
/**
* Inject I18n Service
*/
private readonly i18nService: I18nService,
) {} ) {}
@Public() @Public()
@@ -164,8 +172,8 @@ export class SubmissionsController {
return await this.submissionsService.getUserSubmissions(user); return await this.submissionsService.getUserSubmissions(user);
} }
@Post(':id/analyze') @Sse(':id/analyze')
@HttpCode(HttpStatus.OK) @ApiProduces('text/event-stream')
@ApiResponse({ @ApiResponse({
status: HttpStatus.OK, status: HttpStatus.OK,
description: description:
@@ -215,33 +223,57 @@ export class SubmissionsController {
public async analyzeSubmission( public async analyzeSubmission(
@Param('id') id: string, @Param('id') id: string,
@ActiveUser() user: User, @ActiveUser() user: User,
@Res() res: Response, ): Promise<Observable<MessageEvent>> {
) {
/** /**
* Validation and preparation happen before streaming starts, so any * Validation and preparation happen before streaming starts, so any
* error here reaches the client as a regular HTTP error response. * error here reaches the client as a regular HTTP error response.
*/ */
const analysis = await this.submissionsService.analyzeSubmission(id, user); const analysis = await this.submissionsService.analyzeSubmission(id, user);
res.setHeader('Content-Type', 'text/event-stream'); return new Observable<MessageEvent>((subscriber) => {
res.setHeader('Cache-Control', 'no-cache'); let cancelled = false;
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
try { const consume = async (): Promise<void> => {
for await (const content of analysis) { try {
res.write(`data: ${JSON.stringify({ content })}\n\n`); for await (const content of analysis) {
} if (cancelled || subscriber.closed) {
break;
}
res.write(`data: ${JSON.stringify({ done: true })}\n\n`); subscriber.next({
} catch { data: { content },
res.write( });
`data: ${JSON.stringify({ }
error: 'submissions.errors.analysisFailed',
})}\n\n`, if (!cancelled && !subscriber.closed) {
); subscriber.next({
} finally { data: { done: true },
res.end(); });
}
subscriber.complete();
}
} catch {
if (!cancelled && !subscriber.closed) {
const message = this.i18nService.translate(
'submissions.errors.analysisFailed',
);
subscriber.next({
data: {
error: message,
},
});
subscriber.complete();
}
}
};
void consume();
return () => {
cancelled = true;
};
});
} }
} }