graphql-nexus / nexus

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

Can't return undefined in a resolver that allows an optional #749

Open edjiang opened 3 years ago

edjiang commented 3 years ago

If I define:

query {
    success: Boolean
}
// This will work
resolve(_root, args, context) {
    return true
}

// This will work
resolve(_root, args, context) {
    return null
}

// This will NOT work
resolve(_root, args, context) {
    return undefined
}

Is there a reason to differentiate undefined with null? This means that I can't pass a typescript optional directly, and will have to return optional || null

acro5piano commented 3 years ago

Me too.

acro5piano commented 3 years ago

My workaround is to add a custom formatTypegen fn.


export const schema = makeSchema({
  types: [User, Mutation, Query, GraphQLDate],
  outputs: {
    typegen: path.resolve(__dirname, './__generated__/nexus-typegen.ts'),
    schema: path.resolve(__dirname, './__generated__/schema.graphql'),
  },
  formatTypegen: (code, type) => {
    if (type === 'types') {
      return code.replace(/null/g, 'null | undefined');
    }
    return code;
  },
});