From b17a631c47c5006ea2b160e9cdf1d7560ca74255 Mon Sep 17 00:00:00 2001 From: Kevin Lacker Date: Mon, 22 Aug 2016 15:45:48 -0700 Subject: [PATCH] improve default fn behavior --- src/execution/__tests__/resolve-test.js | 28 +++++++++++++++++++++++++ src/execution/execute.js | 7 +++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/execution/__tests__/resolve-test.js b/src/execution/__tests__/resolve-test.js index 896b0b8919..e160060a1f 100644 --- a/src/execution/__tests__/resolve-test.js +++ b/src/execution/__tests__/resolve-test.js @@ -66,6 +66,34 @@ describe('Execute: resolve function', () => { }); }); + it('default function passes args and context', async () => { + const schema = testSchema({ + type: GraphQLInt, + args: { + addend1: { type: GraphQLInt }, + }, + }); + + class Adder { + constructor(num) { + this._num = num; + } + + test({addend1}, context) { + return this._num + addend1 + context.addend2; + } + } + const source = new Adder(700); + + expect( + await graphql(schema, '{ test(addend1: 80) }', source, { addend2: 9 }) + ).to.deep.equal({ + data: { + test: 789 + } + }); + }); + it('uses provided resolve function', async () => { const schema = testSchema({ type: GraphQLString, diff --git a/src/execution/execute.js b/src/execution/execute.js index 6a5ae81c40..ed05b5466a 100644 --- a/src/execution/execute.js +++ b/src/execution/execute.js @@ -990,13 +990,16 @@ function defaultResolveTypeFn( * If a resolve function is not given, then a default resolve behavior is used * which takes the property of the source object of the same name as the field * and returns it as the result, or if it's a function, returns the result - * of calling that function. + * of calling that function while passing along args and context. */ function defaultResolveFn(source: any, args, context, { fieldName }) { // ensure source is a value for which property access is acceptable. if (typeof source === 'object' || typeof source === 'function') { const property = source[fieldName]; - return typeof property === 'function' ? source[fieldName]() : property; + if (typeof property === 'function') { + return source[fieldName](args, context); + } + return property; } }