TheSoul
TheSoul

Reputation: 5346

graphql: Must provide Source. Received: {kind: "Document, definition ...}

I'm really new to Graphql (just yesterday actually). I am "playing" around and try the various tools of the ecosystem (apollo-server, graphql.js ...ect).

For the sake of experimenting, I am trying to call a query from within nodejs (and not from a client in the browser, such as a react application)

First of all this is my simple schema along with resolvers:

export const mySchema = gql`
   type User {
      id: ID!
      name:  
      surname: String
   }

   # root query has been defined in another file
   extend type Query {
      users: [User]
      test: [User]
   }
` 
export const myResolvers = {
   users: () => [ __array_of_users__ ],
   test: () => /* this is where I would like to re-invoke the 'users query'
}

Using the makeExecutableSchema function, I create a schema object with my types and my resolvers and I export this schema into the apollo server application. Every thing works fine so far.

Now following this stackoverflow suggested solution, I created a helper function which should allow me to invoke a query defined in my schema as following:

import { graphql } from "graphql";
import { schema } from "./my-schema";

export const execute = str => {
  return graphql(schema, str );
};

With this helper function, my resolvers become:

import { gql } from "apollo-server-express";
import { execute } from '__path_to_helper_function__';

export const myResolvers = {
  users: () => [ __array_of_users__ ],
  test:  () => execute( gql`
     query users {
           name
      }    
  `)
}

But in the playground, when I try the query:

   {
      test {
        name
      }
   }

I get the following error:

enter image description here

I don't even know if what I am trying to do (to call a query from within node) can be done. Any suggestion will be greatly appreciated.

Thnaks

Upvotes: 2

Views: 4367

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84667

graphql-tag takes a string and parses it into a DocumentNode object. This is effectively the same as passing a String to the parse function. Some functions exported by the graphql module, like execute, expect to be passed in a DocumentNode object -- the graphql function does not. It should be passed just a plain String as the request, as you can see from the signature:

graphql(
  schema: GraphQLSchema,
  requestString: string,
  rootValue?: ?any,
  contextValue?: ?any,
  variableValues?: ?{[key: string]: any},
  operationName?: ?string
): Promise<GraphQLResult>

So, just drop the gql tag. You can see an (incomplete) API reference here.

Upvotes: 1

Related Questions