As your GraphQL application grows from a demo to an actual application, the complexity of your schema will grow. And it is very difficult to organize the schema in one file. So, to organize your code and schema, you’ll want to split up your schema into multiple files - Modularizing your GraphQL schema code.
Schema
Let’s take a schema example:
Suppose we have a schema of the employee and designation. If the schema is not modularized then it will look complex in a single file:
Here we can see that to identify the schema of a particular collection is difficult, also if the schema increases then the complexity also increases.
Ideally, instead of having everything in one schema definition string, we’d like to place the schema types for Employee and Designation in separate files called employee.ts and designation.ts.
The schema definitions we’ve written are just Strings. In this way, we have a simple way of importing type definitions across different files. Splitting up the string into multiple strings that we can combine later.
employee.ts
designation.ts
schema.ts
Finally, we pull it all together in one file schema.ts
And in the same file, we can build schema like below:
So it is very easy to maintain a schema, and if you want to add a new field or new type in the existing schema, it is very easy.
Conclusion
In this post, we present a straightforward method for modularizing the schema’s built. We can arrange our schema and resolver code in separate files and with just a few simple JavaScript concepts we can build the final schema.
Find the code sample here: graphql-schema-modularize