feat(ws): add integration for manually ack

This commit is contained in:
Seongjee Kim
2025-08-18 19:13:55 +09:00
parent 92372ae978
commit 0c7b94d34e
2 changed files with 54 additions and 1 deletions

View File

@@ -41,5 +41,38 @@ describe('WebSocketGateway (ack)', () => {
);
});
it('should handle manual ack for async operations when @Ack() is used (success case)', async () => {
app = await createNestApp(AckGateway);
await app.listen(3000);
ws = io('http://localhost:8080');
const payload = { shouldSucceed: true };
await new Promise<void>(resolve =>
ws.emit('manual-ack', payload, response => {
expect(response).to.eql({ status: 'success', data: payload });
resolve();
}),
);
});
it('should handle manual ack for async operations when @Ack() is used (error case)', async () => {
app = await createNestApp(AckGateway);
await app.listen(3000);
ws = io('http://localhost:8080');
const payload = { shouldSucceed: false };
await new Promise<void>(resolve =>
ws.emit('manual-ack', payload, response => {
expect(response).to.eql({
status: 'error',
message: 'Operation failed',
});
resolve();
}),
);
});
afterEach(() => app.close());
});

View File

@@ -1,4 +1,9 @@
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import {
Ack,
MessageBody,
SubscribeMessage,
WebSocketGateway,
} from '@nestjs/websockets';
@WebSocketGateway(8080)
export class AckGateway {
@@ -6,4 +11,19 @@ export class AckGateway {
onPush() {
return 'pong';
}
@SubscribeMessage('manual-ack')
async handleManualAck(
@MessageBody() data: any,
@Ack() ack: (response: any) => void,
) {
await new Promise(resolve => setTimeout(resolve, 20));
if (data.shouldSucceed) {
ack({ status: 'success', data });
} else {
ack({ status: 'error', message: 'Operation failed' });
}
return { status: 'ignored' };
}
}