Search code examples
graphqlapolloopenapifastify

Issue Exposing GraphQL In Fastify With TypeDefs Built With `openapi-to-graphql`


I have a working Fastify REST server that exposes a standards-compliant OpenAPI contract, and I was looking to additionally add GraphQL support via Apollo.

https://www.npmjs.com/package/apollo-server-fastify

I worked through the setup directions for the above module, and everything seemed straightforward, until it came time to define the TypeDef and Resolver information needed to connect the dots. Not wanting to re-invent the mappings manually, I decided to leverage the following package:

https://www.npmjs.com/package/openapi-to-graphql-cli

Specifically, I ran the following command:

openapi-to-graphql spec-2.0.json --operationIdFieldNames --save spec.graphql

That ran without complaint, and spit out what appears to me to be a complete TypeDef set for my API. Hoping that was all that was required, I wired it up like so:

  const apolloServer = new ApolloServer({
    typeDefs: gql`${fs.readFileSync('spec.graphql', 'utf-8')}`,
    tracing: true,
    playground: true
  })
  fastifyInstance.register(apolloServer.createHandler())

When I navigated to the new /graphql endpoint, the GraphQL Playground rendered, and the Intellisense/AutoComplete functionality in the Query window seemed to work - it flagged syntax errors, listed my operations and properties, etc. However, any time I execute a command, I end up getting a null result similar to the following:

{
  "data": {
    "operationNameGoesHere": null
  }
}

I'm at a loss. Clearly something isn't wiring up the default resolver properly that connects the GraphQL queries to the REST endpoints, but I have no idea how to troubleshoot.

As a sanity check I hard-coded a basic resolver for one of my operations to always return true, and that did work in the GraphQL Playground, so I think the rest of the setup is fine, other than the GraphQL-to-REST connection.

Any insight is appreciated.


Solution

  • You've provided type definitions, but no resolvers. The resolvers are what actually instruct your schema how to resolve individual fields. The package you're using is not an appropriate tool for what you're trying to do. Instead, you can use openapi-to-graphql, which allows you to create an executable schema:

    const { schema } = await createGraphQLSchema(oas)
    const apolloServer = new ApolloServer({
      schema,
    })
    

    You might also want to take a look at GraphQL Mesh.