javascriptgraphql-jsprisma-graphqlnexus-prisma

Add custom GraphQL resolvers and types into Prisma/Nexus schema


Using: TypeScript, Prisma, MySQL, GraphQLServer, ApolloClient, building schema this way:

const schema = makePrismaSchema({
  // Provide all the GraphQL types we've implemented
  types: [Query, Mutation, User, Post],...

And then:

  const server = new GraphQLServer({
    schema,
    context: { prisma }
  });

How to combine that with custom resolvers and types unrelated to the SQL?

(I would like to call some REST endpoint by the GQL as well)


Solution

  • While nexus was created to be used alongside prisma, it's really just a schema builder. You could easily use it to create a schema without even utilizing Prisma. For example:

    export const User = prismaObjectType({
      name: 'User',
      definition(t) {
        t.list.field('comments', {
          type: 'Comment',
          resolve(root, args, ctx) {
            return getComments();
          },
        });
      },
    })
    
    export const Comment = prismaObjectType({
      name: 'Comment',
      definition(t) {
        t.string('body');
      },
    })
    

    Here getComments can return an array of comment objects, or a Promise that resolves to one. For example, if you're calling some other API, you'll normally return a Promise with the results of the call. As shown above, the resolver exposes the parent value, the field's arguments and a context object -- you can use any of this information in determining how to resolve a particular field.