Files
helix-engage-server/src/graphql-proxy/graphql-proxy.controller.ts

46 lines
1.5 KiB
TypeScript

import { Controller, Post, Req, Res, Logger, HttpException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { Request, Response } from 'express';
import axios from 'axios';
@Controller('graphql')
export class GraphqlProxyController {
private readonly logger = new Logger(GraphqlProxyController.name);
private readonly graphqlUrl: string;
constructor(private config: ConfigService) {
this.graphqlUrl = config.get<string>('platform.graphqlUrl')!;
}
@Post()
async proxy(@Req() req: Request, @Res() res: Response) {
const authHeader = req.headers.authorization;
if (!authHeader) {
throw new HttpException('Authorization header required', 401);
}
try {
const response = await axios.post(
this.graphqlUrl,
req.body,
{
headers: {
'Content-Type': 'application/json',
'Authorization': authHeader,
},
},
);
res.status(response.status).json(response.data);
} catch (error: any) {
if (error.response) {
res.status(error.response.status).json(error.response.data);
} else {
this.logger.error(`GraphQL proxy error: ${error.message}`);
throw new HttpException('Platform unreachable', 503);
}
}
}
}