Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.

feat(core): Allow partial context in makeOperation (QOL) (#3081)

Changed files
+18 -8
.changeset
packages
core
src
exchanges
utils
+5
.changeset/dry-days-wait.md
···
+
---
+
'@urql/core': patch
+
---
+
+
Allow `makeOperation` to be called with a partial `OperationContext` when it’s called to copy an operation. When it receives an `Operation` as a second argument now, the third argument, the context, will be spread into the prior `operation.context`.
-1
packages/core/src/exchanges/cache.ts
···
export const reexecuteOperation = (client: Client, operation: Operation) => {
return client.reexecuteOperation(
makeOperation(operation.kind, operation, {
-
...operation.context,
requestPolicy: 'network-only',
})
);
+13 -7
packages/core/src/utils/operation.ts
···
/** Creates a {@link Operation} from the given parameters.
*
* @param kind - The {@link OperationType} of GraphQL operation, i.e. `query`, `mutation`, or `subscription`.
-
* @param request - The {@link GraphQLRequest} used as a template for the `Operation`.
+
* @param request - The {@link GraphQLRequest} or {@link Operation} used as a template for the new `Operation`.
* @param context - The {@link OperationContext} `context` data for the `Operation`.
-
* @returns An {@link Operation}.
+
* @returns A new {@link Operation}.
*
* @remarks
* This method is both used to create new {@link Operation | Operations} as well as copy and modify existing
* operations. While it’s not required to use this function to copy an `Operation`, it is recommended, in case
* additional dynamic logic is added to them in the future.
*
+
* Hint: When an {@link Operation} is passed to the `request` argument, the `context` argument does not have to be
+
* a complete {@link OperationContext} and will instead be combined with passed {@link Operation.context}.
+
*
* @example
* An example of copying an existing `Operation` to modify its `context`:
*
···
* makeOperation(
* operation.kind,
* operation,
-
* { ...operation.context, requestPolicy: 'cache-first' },
+
* { requestPolicy: 'cache-first' },
* );
* ```
*/
···
>(
kind: OperationType,
request: Operation<Data, Variables>,
-
context?: OperationContext
+
context?: Partial<OperationContext>
): Operation<Data, Variables>;
function makeOperation(kind, request, context) {
-
if (!context) context = request.context;
return {
...request,
kind,
-
context,
+
context: request.context
+
? {
+
...request.context,
+
...context,
+
}
+
: context || request.context,
};
}
···
meta: OperationContext['meta']
) => {
return makeOperation(operation.kind, operation, {
-
...operation.context,
meta: {
...operation.context.meta,
...meta,