From e86f50d1f3152075a793abd8fb103b1828cd7e90 Mon Sep 17 00:00:00 2001 From: Yuta Ura <45471709+YutaUra@users.noreply.github.com> Date: Thu, 1 Dec 2022 19:45:32 +0900 Subject: [PATCH] feat(execute): Resolve promise context values (#2806) Co-authored-by: Phil Pluckthun --- .changeset/olive-rings-yawn.md | 5 +++++ exchanges/execute/src/execute.test.ts | 27 +++++++++++++++++++++++++++ exchanges/execute/src/execute.ts | 5 +++-- 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 .changeset/olive-rings-yawn.md diff --git a/.changeset/olive-rings-yawn.md b/.changeset/olive-rings-yawn.md new file mode 100644 index 0000000000..516eaf2507 --- /dev/null +++ b/.changeset/olive-rings-yawn.md @@ -0,0 +1,5 @@ +--- +'@urql/exchange-execute': minor +--- + +The `context` option, which may be set to a context value or a function returning a context, can now return a `Promise` and will be correctly resolved and awaited. diff --git a/exchanges/execute/src/execute.test.ts b/exchanges/execute/src/execute.test.ts index 2a459b06b9..d9517a16af 100644 --- a/exchanges/execute/src/execute.test.ts +++ b/exchanges/execute/src/execute.test.ts @@ -144,6 +144,33 @@ describe('on operation', () => { }); }); + it('calls execute after executing context as a function returning a Promise', async () => { + const context = async operation => { + expect(operation).toBe(queryOperation); + return 'CALCULATED_USER_ID=' + 8 * 10; + }; + + await pipe( + fromValue(queryOperation), + executeExchange({ schema, context })(exchangeArgs), + take(1), + toPromise + ); + + expect(mocked(execute)).toBeCalledTimes(1); + expect(mocked(execute)).toBeCalledWith({ + schema, + document: queryOperation.query, + rootValue: undefined, + contextValue: 'CALCULATED_USER_ID=80', + variableValues: queryOperation.variables, + operationName: expectedQueryOperationName, + fieldResolver: undefined, + typeResolver: undefined, + subscribeFieldResolver: undefined, + }); + }); + it('should return data from subscribe', async () => { const context = 'USER_ID=123'; diff --git a/exchanges/execute/src/execute.ts b/exchanges/execute/src/execute.ts index cb5c5bed89..ef7121a6a4 100644 --- a/exchanges/execute/src/execute.ts +++ b/exchanges/execute/src/execute.ts @@ -46,14 +46,15 @@ const asyncIterator = const makeExecuteSource = ( operation: Operation, - args: ExecuteParams + _args: ExecuteParams ): Source => { return make(observer => { let iterator: AsyncIterator; let ended = false; Promise.resolve() - .then(() => { + .then(async () => ({ ..._args, contextValue: await _args.contextValue })) + .then(args => { if (ended) return; if (operation.kind === 'subscription') { return subscribe(args) as any;