Vincit / objection-graphql

GraphQL schema generator for objection.js
MIT License
307 stars 35 forks source link

How to write mutation in Schema Defition Language #71

Closed nickreese closed 5 years ago

nickreese commented 5 years ago

Hi, absolutely loving this code.

Being new to graphql and objection in general I’m struggling to sort out a way to write my mutations in Schema Defition Language. I’ve tried using the graphql-tools library but can’t get it to output schema without including the type defs.

Anyone found a way to use SDL with this library?

nasushkov commented 5 years ago

Hi, if you want to add mutations to this library you have two options:

  1. You can use extendWithMutations to enhance the generated schema with mutations. Here you need to use plain old verbose GraphQL js for type definitions). Here is an example
  2. You can define the other schema with mutations and then merge schemas with graphql-tools (it works well with the recent version from Apollo)
Trellian commented 5 years ago

Hi @nasushkov , do you perhaps have an example of how to access the models defined by build(), inside of a mutation? I don't see them available in the context of the mutation. The example given in the docs just returns a static result

ryanvanderpol commented 5 years ago

@Trellian a bit late to the punch here but I was playing around with this today and discovered you can call getType on the built schema and use what comes back in your mutation. It seems that build is immutable (although adding models to the builder is not, which is a bit confusing) so you can call build before creating your mutation schemas, call extendWithMutations next, and then call build again at the end.

Here's an example:

const schema = schema.model(Person);

const graphQlSchema = schema.build();

const updatePersonType = new GraphQLInputObjectType({
    name: 'PersonInputType',
    description: 'Schema for updating a Person',
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'Unique ID',
        },
        name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'Name',
        },
    }),
});

const mutationType = new GraphQLObjectType({
    name: 'RootMutationType',
    description: 'Domain API actions',
    fields: () => ({
        updatePerson: {
            description: 'Updates a person',
            type: graphQlSchema.getType('Persons'),
            args: {
                input: { type: new GraphQLNonNull(updatePersonType) },
            },
            resolve: async (root, userData) => {
                const { id, name } = userData.input;

                return await Person.query().findById(id).patch({ name }).returning('*');
            },
        },
    }),
});

const finalSchema = schema.extendWithMutation(mutationType).build();