graphql-nexus / nexus

Code-First, Type-Safe, GraphQL Schema Construction
https://nexusjs.org
MIT License
3.4k stars 274 forks source link

Feature Request: Integrate mocks directly into queryField and mutationField #134

Open soosap opened 5 years ago

soosap commented 5 years ago

Using graphql-yoga we can pass a mocks object into GraphQLServer. This is kind of painful to manage this additional mocks object...

import { GraphQLServer, MockList } from 'graphql-yoga'

const typeDefs = `
  type Query {
    hello(name: String): String!
    listOfStrings: [String]
  }
`

const mocks = {
  Query: () => ({
    hello: () => 'Hello World',
    listOfStrings: () => new MockList([2, 6]),
  }),
}

const server = new GraphQLServer({ typeDefs, resolvers: () => true, mocks })
server.start()

... instead what I would prefer is something like authorize:

export const CreateProductMutation = mutationField('createProduct', {
  type: 'Product',
  args: { data: arg({ type: 'ProductCreateInput', required: true }) },
  mock: (parent, args, context, info) => {
    // return mocked "Product"
    return {
      name: faker.random.firstName(),
    }
  },
  resolve: async (parent, { data }) => {
    return ProductsController.createProducts(data);
  },
});

nexus could then generate a mocks.js file which we could import and pass to graphql-yoga's GraphQLServer. It would allow us to co-locate mock data with queries and mutations. What do you think about this idea :) ?

tgriesser commented 5 years ago

This is a neat idea! I'm going to think about how we also might accomplish this more generally as part of a middleware.

moltar commented 5 years ago

Feels like mocking is outside of the concern of the library.

But, as @tgriesser said, the overall idea is interesting. Maybe just needs a cleaner implementation that piling on more props.