How to Integrate Rest Api with GraphQL Gateway and send Context

840 Views Asked by At

I use GraphQL Gateway to integrate with GraphQL Federation Microservices . but I use some Rest API code for some reason. like(refresh token , Upload Images with rest)

The Question is : how to communicate with Rest API for the other services from graphql gateway and how to send context to the controller(rest api) server.

import { IntrospectAndCompose, RemoteGraphQLDataSource } from '@apollo/gateway';
import { ApolloGatewayDriver, ApolloGatewayDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { AppController } from './app.controller';

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloGatewayDriverConfig>({
      driver: ApolloGatewayDriver,
      server: {
        // ... Apollo server options
        context: ({ req, res }) => ({
          authorization:req.headers.authorization,
          req,
          res,
          url: req.protocol + '://' + req.headers.host,
        }),
        cors: true,
      },
      gateway: {
        buildService({ name, url }) {         
         
          return new RemoteGraphQLDataSource({
            url,
            willSendRequest({ request, context }) {
              request.http.headers.set('authorization',context['authorization'] ); 
            }
          });
        },
        supergraphSdl: new IntrospectAndCompose({
          subgraphs: [
            { name: 'Service1', url: 'http://localhost:3001/graphql' },
            { name: 'Service2', url: 'http://localhost:3002/graphql' },
            { name:  'Service3' , url: 'http://localhost:3003/graphql' }
          ],
        }),
      },
    }),
  ],controllers:[AppController]
}) 
export class AppModule { }

Note: if I removed '/graphql' from Url to access origin url , it gives me error[Couldn't load service definitions for service1] .

This code works fine with GraphQL but didn't work with Rest.

Server : NestJS.

Thanks..

0

There are 0 best solutions below