GraphQL Schemas — Easier & Better Structure

Nicolas Dao
Neap For Startups
Published in
2 min readAug 7, 2017

--

SchemaGlue.js and graphql-s2s.js will respectively help breaking down your schema into modules and add support for inheritance and generic types.

From:

To:

With this:

Part I — Organising Your GraphQL Schema & Resolvers

If you’ve been using the awesome graphql-tools from Apollo to build GraphQL server on node.js, and if your codebase has started to grow beyond the usual HelloWorld demo project, then you must have started to wonder what would be a good way to organise your schema beyond the usual big monolithic string. For example, let’s have a look at the following:

You can simply execute this code on your local machine as is by running:

node index.js

The above demonstrates the usual HelloWorld project with a monolithic schema.js file under the src folder. That schema.js contains both the GraphQL schema and the resolvers. But as your code grows, what would be better is to organise your code around something like this instead:

Where the code could be refactor this way:

SchemaGlue.js is our nice addition to the Apollo ecosystem to organise your code. Our team at Neap has just opened source it, so feel free to give it a go here.

Part II — Adding Support For GraphQL Type Inheritance & Generic Typing

After having written a series of GraphQL APIs, we’ve realised that we were duplicating a lot of code as we’re writing our GraphQL schemas. We created graphql-s2s (schema-2-schema) to be able to rewrite schema that looked like this:

to something like this:

Another chore is to deal with paging. We added support for generic typing to deal with such problems. Instead of writing this:

you can now write:

To use this new schema, simply transpile the new schema using graphql-s2s:

In the case of the generic types, graphql-s2s will create new type for each concrete generic types it finds (e.g. Paged<Product> will become PagedProduct). graphql-s2s also supports metadata (more details here) to define custom names on a generic type.

The example above will convert the new concrete generic types as follow:

  • Paged<Product>: Products
  • Paged<Inventory>: Inventories
  • Paged<Business>: Businesses

Hope those tools will help you. Let us know what you think about those. Leave us comments here or on our github pages if you want more features or if you feel there could be improvements.

Cheers,

The Neap Team :)

--

--

Focused on nurturing happiness in tech. and in life. Co-founder of Neap (https://neap.co), a Tech. Consultancy based in Sydney.