Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow QueryManager to intercept hook functionality #11617

Merged
merged 17 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
397 changes: 391 additions & 6 deletions .api-reports/api-report-react_internal.md

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions .changeset/curvy-maps-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@apollo/client": patch
---

Allow Apollo Client instance to intercept hook functionality
2 changes: 1 addition & 1 deletion .size-limits.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"dist/apollo-client.min.cjs": 39075,
"dist/apollo-client.min.cjs": 39283,
"import { ApolloClient, InMemoryCache, HttpLink } from \"dist/index.js\" (production)": 32584
}
4 changes: 3 additions & 1 deletion config/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import cleanup from "rollup-plugin-cleanup";
const entryPoints = require("./entryPoints");
const distDir = "./dist";

const removeComments = cleanup({});
const removeComments = cleanup({
comments: ["some", /#__PURE__/, /#__NO_SIDE_EFFECTS__/],
});
Comment on lines +11 to +13
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't strictly need this here anymore in this specific case, but it would be good to have this in our bundling config anyways, so I'll leave it here.


function isExternal(id, parentId, entryPointsAreExternal = true) {
let posixId = toPosixPath(id);
Expand Down
1 change: 1 addition & 0 deletions src/react/hooks/internal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect.js";
export { useRenderGuard } from "./useRenderGuard.js";
export { useLazyRef } from "./useLazyRef.js";
export { __use } from "./__use.js";
export { makeHookWrappable } from "./wrapHook.js";
98 changes: 98 additions & 0 deletions src/react/hooks/internal/wrapHook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import type {
useQuery,
useSuspenseQuery,
useBackgroundQuery,
useReadQuery,
useFragment,
} from "../index.js";
import type { QueryManager } from "../../../core/QueryManager.js";
import type { ApolloClient } from "../../../core/ApolloClient.js";
import type { ObservableQuery } from "../../../core/ObservableQuery.js";

const wrapperSymbol = Symbol.for("apollo.hook.wrappers");

interface WrappableHooks {
useQuery: typeof useQuery;
useSuspenseQuery: typeof useSuspenseQuery;
useBackgroundQuery: typeof useBackgroundQuery;
useReadQuery: typeof useReadQuery;
useFragment: typeof useFragment;
}

/**
* @internal
* Can be used to correctly type the [Symbol.for("apollo.hook.wrappers")] of
* a class that extends `ApolloClient`, to override/wrap hook functionality.
*/
export type HookWrappers = {
[K in keyof WrappableHooks]?: (
originalHook: WrappableHooks[K]
) => WrappableHooks[K];
};

interface QueryManagerWithWrappers<T> extends QueryManager<T> {
[wrapperSymbol]?: HookWrappers;
}

/**
* @internal
*
* Makes an Apollo Client hook "wrappable".
* That means that the Apollo Client instance can expose a "wrapper" that will be
* used to wrap the original hook implementation with additional logic.
* @example
* ```tsx
* // this is already done in `@apollo/client` for all wrappable hooks (see `WrappableHooks`)
* const wrappedUseQuery = makeHookWrappable('useQuery', useQuery, (_, options) => options.client);
*
* // although for tree-shaking purposes, in reality it looks more like
* function useQuery() {
* useQuery = makeHookWrappable('useQuery', (_, options) => options.client, _useQuery);
* return useQuery.apply(null, arguments as any);
* }
* function _useQuery() {
* // original implementation
* }
*
* // this is what a library like `@apollo/client-react-streaming` would do
* class ApolloClientWithStreaming extends ApolloClient {
* constructor(options) {
* super(options);
* this.queryManager[Symbol.for("apollo.hook.wrappers")] = {
* useQuery: (original) => (query, options) => {
* console.log("useQuery was called with options", options);
* return original(query, options);
* }
* }
* }
* }
*
* // this will now log the options and then call the original `useQuery`
* const client = new ApolloClientWithStreaming({ ... });
* wrappedUseQuery(query, { client });
* ```
*/
/*#__NO_SIDE_EFFECTS__*/
export function makeHookWrappable<Name extends keyof WrappableHooks>(
hookName: Name,
getClientFromOptions: (
...args: Parameters<WrappableHooks[Name]>
) => ObservableQuery<any> | ApolloClient<any>,
useHook: WrappableHooks[Name]
): WrappableHooks[Name] {
return function (this: any) {
const args = arguments as unknown as Parameters<WrappableHooks[Name]>;
const queryManager = (
getClientFromOptions.apply(this, args) as unknown as {
// both `ApolloClient` and `ObservableQuery` have a `queryManager` property
// but they're both `private`, so we have to cast around for a bit here.
queryManager: QueryManagerWithWrappers<any>;
}
)["queryManager"];
const wrappers = queryManager && queryManager[wrapperSymbol];
const wrapper = wrappers && wrappers[hookName];
const wrappedHook: WrappableHooks[Name] =
wrapper ? wrapper(useHook) : useHook;
return (wrappedHook as any).apply(this, args);
} as any;
}
16 changes: 14 additions & 2 deletions src/react/hooks/useBackgroundQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
} from "../internal/index.js";
import type { CacheKey, QueryReference } from "../internal/index.js";
import type { BackgroundQueryHookOptions, NoInfer } from "../types/types.js";
import { __use } from "./internal/index.js";
import { __use, makeHookWrappable } from "./internal/index.js";
import { useWatchQueryOptions } from "./useSuspenseQuery.js";
import type { FetchMoreFunction, RefetchFunction } from "./useSuspenseQuery.js";
import { canonicalStringify } from "../../cache/index.js";
Expand Down Expand Up @@ -170,7 +170,19 @@ export function useBackgroundQuery<
UseBackgroundQueryResult<TData, TVariables>,
];

export function useBackgroundQuery<
export function useBackgroundQuery() {
// @ts-expect-error Cannot assign to 'useBackgroundQuery' because it is a function.ts(2630)
useBackgroundQuery = makeHookWrappable(
"useBackgroundQuery",
(_, options) =>
useApolloClient(typeof options === "object" ? options.client : undefined),
_useBackgroundQuery as any
);

return useBackgroundQuery.apply(null, arguments as any);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps I'm missing something obvious or its been a long travel day, but couldn't you just set this to any variable name and call it? Any reason you need to override the original function?

Suggested change
useBackgroundQuery = makeHookWrappable(
"useBackgroundQuery",
(_, options) =>
useApolloClient(typeof options === "object" ? options.client : undefined),
_useBackgroundQuery as any
);
return useBackgroundQuery.apply(null, arguments as any);
const uBQ = makeHookWrappable(
"useBackgroundQuery",
(_, options) =>
useApolloClient(typeof options === "object" ? options.client : undefined),
_useBackgroundQuery as any
);
return uBQ.apply(null, arguments as any);

or if if you wanted to do it all inline

return makeHookWrappable(
  "useBackgroundQuery",
  (_, options) =>
    useApolloClient(typeof options === "object" ? options.client : undefined),
  _useBackgroundQuery as any
).apply(null, arguments as any);

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is based on a babel pattern:

function _extends() {
  _extends = Object.assign
    ? Object.assign.bind()
    : function (target) {
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i];
          for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }
        return target;
      };
  return _extends.apply(this, arguments);
}
var a = _extends({}, b);

Essentially, it's a lazy override pattern, so makeHookWrappable wouldn't have to be called again in the future.

But, one sleep later, I agree with you that this can be simplified - we are not on a hot path here (something is seriously wrong if we ever are), so we might as well optimize a bit more for readability and amount of code.

I still prefer the first approach we had, overriding the hooks after creation, as that way we didn't have to touch their contents. But as we don't have that option, I believe what I've ended up doing now should be one of the simpler possible solutions. Can you please take another look?

}

function _useBackgroundQuery<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
Expand Down
21 changes: 20 additions & 1 deletion src/react/hooks/useFragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ import { useApolloClient } from "./useApolloClient.js";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
import type { ApolloClient, OperationVariables } from "../../core/index.js";
import type { NoInfer } from "../types/types.js";
import { useDeepMemo, useLazyRef } from "./internal/index.js";
import {
useDeepMemo,
useLazyRef,
makeHookWrappable,
} from "./internal/index.js";

export interface UseFragmentOptions<TData, TVars>
extends Omit<
Expand Down Expand Up @@ -53,6 +57,21 @@ export type UseFragmentResult<TData> =

export function useFragment<TData = any, TVars = OperationVariables>(
options: UseFragmentOptions<TData, TVars>
): UseFragmentResult<TData>;

export function useFragment<TData = any, TVars = OperationVariables>() {
// @ts-expect-error Cannot assign to 'useFragment' because it is a function.ts(2630)
useFragment = makeHookWrappable(
"useFragment",
(options) => useApolloClient(options.client),
_useFragment
);

return useFragment.apply(null, arguments as any);
}

function _useFragment<TData = any, TVars = OperationVariables>(
options: UseFragmentOptions<TData, TVars>
): UseFragmentResult<TData> {
const { cache } = useApolloClient(options.client);

Expand Down
21 changes: 20 additions & 1 deletion src/react/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
isNonEmptyArray,
maybeDeepFreeze,
} from "../../utilities/index.js";
import { makeHookWrappable } from "./internal/index.js";

const {
prototype: { hasOwnProperty },
Expand Down Expand Up @@ -78,13 +79,31 @@ const {
export function useQuery<
TData = any,
TVariables extends OperationVariables = OperationVariables,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>
): QueryResult<TData, TVariables>;

export function useQuery() {
// @ts-expect-error Cannot assign to 'useQuery' because it is a function. ts(2630)
useQuery = makeHookWrappable(
"useQuery",
(_, options) => useApolloClient(options && options.client),
_useQuery
);
return useQuery.apply(null, arguments as any);
}

function _useQuery<
TData = any,
TVariables extends OperationVariables = OperationVariables,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: QueryHookOptions<
NoInfer<TData>,
NoInfer<TVariables>
> = Object.create(null)
): QueryResult<TData, TVariables> {
) {
return useInternalState(useApolloClient(options.client), query).useQuery(
options
);
Expand Down
16 changes: 15 additions & 1 deletion src/react/hooks/useReadQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
updateWrappedQueryRef,
} from "../internal/index.js";
import type { QueryReference } from "../internal/index.js";
import { __use } from "./internal/index.js";
import { __use, makeHookWrappable } from "./internal/index.js";
import { toApolloError } from "./useSuspenseQuery.js";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
import type { ApolloError } from "../../errors/index.js";
Expand Down Expand Up @@ -38,6 +38,20 @@ export interface UseReadQueryResult<TData = unknown> {

export function useReadQuery<TData>(
queryRef: QueryReference<TData>
): UseReadQueryResult<TData>;

export function useReadQuery() {
// @ts-expect-error Cannot assign to 'useReadQuery' because it is a function.ts(2630)
useReadQuery = makeHookWrappable(
"useReadQuery",
(ref) => unwrapQueryRef(ref)["observable"],
_useReadQuery
);
return useReadQuery.apply(null, arguments as any);
}

function _useReadQuery<TData>(
queryRef: QueryReference<TData>
): UseReadQueryResult<TData> {
const internalQueryRef = React.useMemo(
() => unwrapQueryRef(queryRef),
Expand Down
15 changes: 13 additions & 2 deletions src/react/hooks/useSuspenseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import type {
ObservableQueryFields,
NoInfer,
} from "../types/types.js";
import { __use, useDeepMemo } from "./internal/index.js";
import { __use, useDeepMemo, makeHookWrappable } from "./internal/index.js";
import { getSuspenseCache } from "../internal/index.js";
import { canonicalStringify } from "../../cache/index.js";
import { skipToken } from "./constants.js";
Expand Down Expand Up @@ -166,7 +166,18 @@ export function useSuspenseQuery<
| SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>
): UseSuspenseQueryResult<TData | undefined, TVariables>;

export function useSuspenseQuery<
export function useSuspenseQuery() {
// @ts-expect-error Cannot assign to 'useSuspenseQuery' because it is a function. ts(2630)
useSuspenseQuery = makeHookWrappable(
"useSuspenseQuery",
(_, options) =>
useApolloClient(typeof options === "object" ? options.client : undefined),
_useSuspenseQuery
);
return useSuspenseQuery.apply(null, arguments as any);
}

function _useSuspenseQuery<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
Expand Down
1 change: 1 addition & 0 deletions src/react/internal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export {
wrapQueryRef,
} from "./cache/QueryReference.js";
export type { SuspenseCacheOptions } from "./cache/SuspenseCache.js";
export type { HookWrappers } from "../hooks/internal/wrapHook.js";
Loading