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