keke
keke

Reputation: 53

Resolving a Graphql query from different data sources

I have a graphql server I've created using ApolloServer and Type-Graphql.

I have two types defined on my graphql server:

User{
   id:string;
   name:string
   email:string;
   ...
}

UserPrefrences{
   userId:string;
   theme: string;
   color:string;
   ...
}

The data for the User type is saved in a database which I access through a different graphql server by forwarding the request I get from client.

The data for the UserPrefrences type is saved on a different database which I access directly from my graphql server.

I don't want my client side to need to know these two separate types and to need to run two separate queries. I'm looking for a way to let my client run the following query on my graphql server:

query UserData($userId: String!) {
   id
   name
   email
   theme
   color
}

But if I forward this request to the graphql server that I'm querying, I will get a response saying the fields 'theme' and 'color' are unknown to him.

I'm trying to find a way to forward only the relevant fields to the graphql server, and then resolving the rest within my graphql server. But I receive the query as a string which makes it a pain trying to use regex to only forward the fields I'm interested in.

I'd be more than happy for any ideas on how to solve this issue.

Upvotes: 1

Views: 893

Answers (1)

xdemocle
xdemocle

Reputation: 1335

the only way I found is using a Graphql client in Node.js.

I'm using the npm library called graphql-request https://www.npmjs.com/package/graphql-request

import { GraphQLClient, gql } from 'graphql-request';

const client = new GraphQLClient('http://localhost:4000/graphql');

const query = `
  {
    yourQuery {
      id
      name
    }
  }
`;

const response = client.request(query);

Upvotes: 0

Related Questions