File size: 2,567 Bytes
97dab2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { Controller, Req, Res, All, Get } from '@nestjs/common';
import { NorthwindService } from './northwind.service';
import { Request, Response } from 'express';

@Controller('northwind')
export class NorthwindController {
    constructor(private readonly gateway: NorthwindService) {}

    @Get('/')
    async get(@Req() req: Request, @Res() res: Response) {
        //console.log('Request received:', req.method, req.url);
        res.send('🚀 You have reached northwind service...............');
    }

    @Get(['/swagger', '/swagger/*'])
        async swagger(@Req() req: Request, @Res() res: Response) {
        const baseUrl = "/api/northwind";
        const strippedPath = req.url.toLocaleLowerCase().slice(baseUrl.length);
        const isProd = process.env.NODE_ENV === 'production';

        const targetBaseUrl = isProd
            ? 'http://northwindapi-nestjs-service.riskiq.svc.cluster.local'
            : 'http://localhost:3002';

        console.log(strippedPath);

        const result = await this.gateway.forwardRequest(
            targetBaseUrl,
            req.method as any,
            strippedPath,
            req.headers,
            undefined
        );

        // Attempt to parse and transform JSON paths
        if (typeof result === 'object' && result?.paths) {
            const transformed = {
            ...result,
            paths: {},
            };

            for (const [path, value] of Object.entries(result.paths)) {
            const newPath = path.replace(/^\/api/, baseUrl);
            transformed.paths[newPath] = value;
            }

            return res.json(transformed);
        }

        // Fallback to regular response
        return res.send(result);
    }

    
    
    @All('*')
    async allRequests(@Req() req: Request, @Res() res: Response) {
        const baseUrl = "/api/northwind";
        const strippedPath = req.url.toLocaleLowerCase().slice(baseUrl.length); 
        //console.log('Request received:', req.method, strippedPath);
        const isProd = process.env.NODE_ENV === 'production';
        let targetBaseUrl = isProd
            ? 'http://northwindapi-nestjs-service.riskiq.svc.cluster.local/api'
            : 'http://localhost:3002/api';

        const hasBody = !['GET', 'HEAD'].includes(req.method.toUpperCase());

        const result = await this.gateway.forwardRequest(
            targetBaseUrl,
            req.method as any,
            strippedPath,
            req.headers,
            hasBody ? req.body : undefined
        );

        res.send(result);
    }
}