When writing the schema that you just defined elsewhere gets a little old....
I have been working on a graphql instance where the main data source is, currently at least, a mongo database. As you may have seen in my last blog post about defining graphql schema's, I was able to include a more useful set of scalar types to make my graph API easier to consume.
I did this using the merge tools in the graphql-tools library. Well, I found another use for those tools in my next TypeScript/Mongo/GraphQL adventure!
First of all I should point out that the process for using graphql-compose-mongoose is well documented in the readme of the library. To summarise, once a mongoose model has been defined it is necessary to define a detailed schema definition and resolvers for graphql. The schema definition and associated resolvers for graphql are a lot of work to write and maintain manually. Here is where this library steps in and helps you generate the types, input types, enumerations and resolvers. It really is quite the life-saver!
I was curious however, as to whether I could include it on top of the schema that I had already defined (see previous blog post). After googling around for a way to merge schemas I found out that it was available from the graphql-tools library that I was already using. So I was able to really easily.
import gqlTools from 'graphql-tools';
import gqlCompose from 'graphql-compose';
import monCompose from 'graphql-compose-mongoose';
const competitionTC = monCompose.composeMongoose(customModel, {}); gqlCompose.schemaComposer.Query.addFields({ competitions: competitionTC.mongooseResolvers.findMany(),
}); const graphqlSchemaFromMongoose = gqlCompose.schemaComposer.buildSchema(); const existingSchema = gqlTools.makeExecutableSchema({ alreadyExistingTypeDefs, alreadyExistingResolvers, }); const allSchemas = gqlTools.mergeSchemas({ schemas: [ existingSchema, graphqlSchemaFromMongoose ] });
This code works beautifully, although it almost feels like it shouldn't. There is a lot going on and I found myself wondering whether it was all necessary.
In the graphql UI the competitionTC now has a much more complete filter than the one I had before and skip, limit and sort also work great.
But, the code is messy 😉. Do I really need those extra scalar types?
Something went wrong Error: Unknown type "Date".
OK then, turns out this is the best solution for now! It produces really complete GraphQL queries and mutations with very little effort.
Resources and references:
No comments:
Post a Comment