global update and global fix
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import { All, Body, Controller, HttpCode, Param, Req, Res } from '@nestjs/common';
|
||||
import { ApiExcludeController } from '@nestjs/swagger';
|
||||
import { firstValueFrom, timeout } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
|
||||
type HttpRequest = {
|
||||
method: string;
|
||||
query: Record<string, unknown>;
|
||||
};
|
||||
|
||||
type HttpResponse = {
|
||||
status(code: number): HttpResponse;
|
||||
setHeader(name: string, value: string): void;
|
||||
};
|
||||
|
||||
@ApiExcludeController()
|
||||
@Controller()
|
||||
export class TelegramBotApiController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@All(':botPath/:method')
|
||||
@HttpCode(200)
|
||||
async handleTelegramMethod(
|
||||
@Req() request: HttpRequest,
|
||||
@Res({ passthrough: true }) response: HttpResponse,
|
||||
@Param('botPath') botPath: string,
|
||||
@Param('method') method: string,
|
||||
@Body() body: Record<string, unknown>
|
||||
) {
|
||||
if (!botPath.startsWith('bot')) {
|
||||
response.status(404);
|
||||
return { ok: false, error_code: 404, description: 'Not Found' };
|
||||
}
|
||||
|
||||
const token = decodeURIComponent(botPath.slice(3));
|
||||
if (!token) {
|
||||
response.status(401);
|
||||
return { ok: false, error_code: 401, description: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const payload = request.method === 'GET' ? { ...request.query } : body ?? {};
|
||||
const grpcCall = this.core.bot.ExecuteBotMethod({
|
||||
token,
|
||||
method,
|
||||
payloadJson: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
const waitSeconds = method === 'getUpdates' ? Number(payload.timeout ?? 0) : 0;
|
||||
const grpcTimeoutMs = method === 'getUpdates' ? Math.min(Math.max(waitSeconds, 0), 50) * 1000 + 10_000 : 30_000;
|
||||
|
||||
const result = (await firstValueFrom(
|
||||
grpcCall.pipe(timeout(grpcTimeoutMs)) as typeof grpcCall
|
||||
)) as { responseJson: string; httpStatus: number };
|
||||
|
||||
response.status(result.httpStatus ?? 200);
|
||||
response.setHeader('Content-Type', 'application/json');
|
||||
return JSON.parse(result.responseJson);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user