Skip to content

Commit

Permalink
more type fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
phryneas committed Sep 13, 2023
1 parent b568689 commit b49b269
Show file tree
Hide file tree
Showing 19 changed files with 93 additions and 59 deletions.
6 changes: 5 additions & 1 deletion src/cache/inmemory/entityStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,11 @@ class Layer extends EntityStore {
public getStorage(): StorageType {
let p: EntityStore = this.parent;
while ((p as Layer).parent) p = (p as Layer).parent;
return p.getStorage.apply(p, arguments);
return p.getStorage.apply(
p,
// @ts-expect-error
arguments
);
}
}

Expand Down
18 changes: 11 additions & 7 deletions src/core/ObservableQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -929,13 +929,7 @@ Did you mean to call refetch(variables) instead of refetch({ variables })?`,
newNetworkStatus?: NetworkStatus
) {
return this.reobserveAsConcast(newOptions, newNetworkStatus).promise.then(
(value) => {
invariant(
value,
"A Concast finished without a result. This in an Apollo Client bug, please file a bug report."
);
return value;
}
ensureResult
);
}

Expand Down Expand Up @@ -1102,3 +1096,13 @@ function skipCacheDataFor(
fetchPolicy === "standby"
);
}

export function ensureResult<TData = any>(
value: ApolloQueryResult<TData> | undefined
): ApolloQueryResult<TData> {
invariant(
value,
"A Concast finished without a result. This in an Apollo Client bug, please file a bug report."
);
return value;
}
7 changes: 4 additions & 3 deletions src/core/QueryInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ function wrapDestructiveCacheMethod(
// that matters in any conceivable practical scenario.
(destructiveMethodCounts.get(cache)! + 1) % 1e15
);
// @ts-expect-error this is just too generic to be typed correctly
return original.apply(this, arguments);
};
}
Expand Down Expand Up @@ -113,7 +114,7 @@ export class QueryInfo {
// NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
// or setVariables.
networkStatus?: NetworkStatus;
observableQuery?: ObservableQuery<any>;
observableQuery?: ObservableQuery<any, any>;
lastRequestId?: number;
}): this {
let networkStatus = query.networkStatus || NetworkStatus.loading;
Expand Down Expand Up @@ -214,10 +215,10 @@ export class QueryInfo {
}
}

public readonly observableQuery: ObservableQuery<any> | null = null;
public readonly observableQuery: ObservableQuery<any, any> | null = null;
private oqListener?: QueryListener;

setObservableQuery(oq: ObservableQuery<any> | null) {
setObservableQuery(oq: ObservableQuery<any, any> | null) {
if (oq === this.observableQuery) return;

if (this.oqListener) {
Expand Down
19 changes: 13 additions & 6 deletions src/core/QueryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@ import type {
ErrorPolicy,
MutationFetchPolicy,
} from "./watchQueryOptions.js";
import { ObservableQuery, logMissingFieldErrors } from "./ObservableQuery.js";
import {
ObservableQuery,
ensureResult,
logMissingFieldErrors,
} from "./ObservableQuery.js";
import { NetworkStatus, isNetworkRequestInFlight } from "./networkStatus.js";
import type {
ApolloQueryResult,
Expand Down Expand Up @@ -479,7 +483,7 @@ export class QueryManager<TStore> {
const results: any[] = [];

this.refetchQueries({
updateCache: (cache: TCache) => {
updateCache: (cache) => {
if (!skipCache) {
cacheWrites.forEach((write) => cache.write(write));
}
Expand Down Expand Up @@ -526,7 +530,7 @@ export class QueryManager<TStore> {
// either a SingleExecutionResult or the final ExecutionPatchResult,
// call the update function.
if (isFinalResult) {
update(cache, result, {
update(cache as TCache, result, {
context: mutation.context,
variables: mutation.variables,
});
Expand Down Expand Up @@ -616,8 +620,11 @@ export class QueryManager<TStore> {
options: WatchQueryOptions<TVars, TData>,
networkStatus?: NetworkStatus
): Promise<ApolloQueryResult<TData>> {
return this.fetchConcastWithInfo(queryId, options, networkStatus).concast
.promise;
return this.fetchConcastWithInfo(
queryId,
options,
networkStatus
).concast.promise.then(ensureResult);
}

public getQueryStore() {
Expand Down Expand Up @@ -1301,7 +1308,7 @@ export class QueryManager<TStore> {
normalized.variables,
normalized.context
)
.then(fromVariables)
.then(fromVariables as (Variables: any) => SourcesAndInfo<TData>)
.then((sourcesWithInfo) => sourcesWithInfo.sources)
);
// there is just no way we can synchronously get the *right* value here,
Expand Down
2 changes: 0 additions & 2 deletions src/link/http/HttpLink.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import type { RequestHandler } from "../core/index.js";
import { ApolloLink } from "../core/index.js";
import type { HttpOptions } from "./selectHttpOptionsAndBody.js";
import { createHttpLink } from "./createHttpLink.js";

export class HttpLink extends ApolloLink {
public requester: RequestHandler;
constructor(public options: HttpOptions = {}) {
super(createHttpLink(options).request);
}
Expand Down
14 changes: 11 additions & 3 deletions src/link/http/iterators/reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { canUseAsyncIteratorSymbol } from "../../../utilities/index.js";

interface ReaderIterator<T> {
next(): Promise<ReadableStreamReadResult<T>>;
next(): Promise<IteratorResult<T, T | undefined>>;
[Symbol.asyncIterator]?(): AsyncIterator<T>;
}

Expand All @@ -15,12 +15,20 @@ export default function readerIterator<T>(
): AsyncIterableIterator<T> {
const iterator: ReaderIterator<T> = {
next() {
return reader.read();
return reader.read() as Promise<
| ReadableStreamReadValueResult<T>
// DoneResult has `value` optional, which doesn't comply with an
// `IteratorResult`, so we assert it to `T | undefined` instead
| Required<ReadableStreamReadDoneResult<T | undefined>>
>;
},
};

if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function (): AsyncIterator<T> {
iterator[Symbol.asyncIterator] = function (): AsyncIterator<
T,
T | undefined
> {
return this;
};
}
Expand Down
2 changes: 1 addition & 1 deletion src/link/http/serializeFetchParameter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const serializeFetchParameter = (p: any, label: string) => {
let serialized;
try {
serialized = JSON.stringify(p);
} catch (e) {
} catch (e: any) {
const parseError = newInvariantError(
`Network request failed. %s is not serializable: %s`,
label,
Expand Down
6 changes: 4 additions & 2 deletions src/react/cache/SuspenseCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ export class SuspenseCache {
cacheKey: CacheKey,
createObservable: () => ObservableQuery<TData>
) {
const ref = this.queryRefs.lookupArray(cacheKey);
const ref = this.queryRefs.lookupArray(cacheKey) as {
current?: InternalQueryReference<TData>;
};

if (!ref.current) {
ref.current = new InternalQueryReference(createObservable(), {
Expand All @@ -44,6 +46,6 @@ export class SuspenseCache {
});
}

return ref.current as InternalQueryReference<TData>;
return ref.current;
}
}
1 change: 1 addition & 0 deletions src/react/hoc/mutation-hoc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export function withMutation<

return (
<Mutation ignoreResults {...opts} mutation={document}>
{/* @ts-expect-error */}
{(
mutate: MutationFunction<TData, TGraphQLVariables>,
{ data, ...r }: MutationResult<TData>
Expand Down
6 changes: 4 additions & 2 deletions src/react/hooks/useBackgroundQuery.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import * as React from "react";
import type {
DocumentNode,
FetchMoreQueryOptions,
OperationVariables,
TypedDocumentNode,
WatchQueryOptions,
} from "../../core/index.js";
import { useApolloClient } from "./useApolloClient.js";
import { wrapQueryRef } from "../cache/QueryReference.js";
Expand Down Expand Up @@ -197,7 +199,7 @@ export function useBackgroundQuery<
];

const queryRef = suspenseCache.getQueryRef(cacheKey, () =>
client.watchQuery(watchQueryOptions)
client.watchQuery(watchQueryOptions as WatchQueryOptions<any, any>)
);

const [promiseCache, setPromiseCache] = React.useState(
Expand All @@ -213,7 +215,7 @@ export function useBackgroundQuery<

const fetchMore: FetchMoreFunction<TData, TVariables> = React.useCallback(
(options) => {
const promise = queryRef.fetchMore(options);
const promise = queryRef.fetchMore(options as FetchMoreQueryOptions<any>);

setPromiseCache((promiseCache) =>
new Map(promiseCache).set(queryRef.key, queryRef.promise)
Expand Down
1 change: 1 addition & 0 deletions src/react/hooks/useLazyQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export function useLazyQuery<
// Only the first time populating execOptionsRef.current matters here.
internalState.forceUpdateState();
}
// @ts-expect-error this is just too generic to type
return method.apply(this, arguments);
};
}
Expand Down
41 changes: 24 additions & 17 deletions src/react/hooks/useSuspenseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ export function useSuspenseQuery<
];

const queryRef = suspenseCache.getQueryRef(cacheKey, () =>
client.watchQuery(watchQueryOptions)
client.watchQuery(watchQueryOptions as WatchQueryOptions<any, any>)
);

const [promiseCache, setPromiseCache] = React.useState(
Expand Down Expand Up @@ -236,18 +236,21 @@ export function useSuspenseQuery<

const result = fetchPolicy === "standby" ? skipResult : __use(promise);

const fetchMore: FetchMoreFunction<TData, TVariables> = React.useCallback(
(options) => {
const promise = queryRef.fetchMore(options);
const fetchMore: FetchMoreFunction<TData | undefined, TVariables> =
React.useCallback(
(options) => {
const promise = queryRef.fetchMore(
options as WatchQueryOptions<TVariables, TData | undefined>
);

setPromiseCache((previousPromiseCache) =>
new Map(previousPromiseCache).set(queryRef.key, queryRef.promise)
);
setPromiseCache((previousPromiseCache) =>
new Map(previousPromiseCache).set(queryRef.key, queryRef.promise)
);

return promise;
},
[queryRef]
);
return promise;
},
[queryRef]
);

const refetch: RefetchFunction<TData, TVariables> = React.useCallback(
(variables) => {
Expand All @@ -262,13 +265,17 @@ export function useSuspenseQuery<
[queryRef]
);

const subscribeToMore: SubscribeToMoreFunction<TData, TVariables> =
React.useCallback(
(options) => queryRef.observable.subscribeToMore(options),
[queryRef]
);
const subscribeToMore: SubscribeToMoreFunction<
TData | undefined,
TVariables
> = React.useCallback(
(options) => queryRef.observable.subscribeToMore(options),
[queryRef]
);

return React.useMemo(() => {
return React.useMemo<
UseSuspenseQueryResult<TData | undefined, TVariables>
>(() => {
return {
client,
data: result.data,
Expand Down
2 changes: 1 addition & 1 deletion src/testing/core/mocking/mockSubscriptionLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface MockedSubscriptionResult {
export class MockSubscriptionLink extends ApolloLink {
public unsubscribers: any[] = [];
public setups: any[] = [];
public operation: Operation;
public operation?: Operation;

private observers: any[] = [];

Expand Down
3 changes: 1 addition & 2 deletions src/testing/core/withConsoleSpy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ function wrapTestFunction(
fn: (...args: any[]) => any,
consoleMethodName: "log" | "warn" | "error"
) {
return function () {
const args = arguments;
return function (this: any, ...args: any[]) {
const spy = jest.spyOn(console, consoleMethodName);
spy.mockImplementation(() => {});
return new Promise((resolve) => {
Expand Down
2 changes: 1 addition & 1 deletion src/testing/internal/profile/profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export function profile<
return render;
},
async takeRender(options: NextRenderOptions = {}) {
let error: { message?: string } | undefined = undefined;
let error: unknown = undefined;
try {
return await Profiled.peekRender({
[_stackTrace]: captureStackTrace(Profiled.takeRender),
Expand Down
17 changes: 8 additions & 9 deletions src/testing/matchers/ProfiledComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import type {
ProfiledHook,
} from "../internal/index.js";
export const toRerender: MatcherFunction<[options?: NextRenderOptions]> =
async function (
_profiled: ProfiledComponent<any, any> | ProfiledHook<any, any>,
options?: NextRenderOptions
) {
async function (actual, options) {
const _profiled = actual as
| ProfiledComponent<any, any>
| ProfiledHook<any, any>;
const profiled =
"ProfiledComponent" in _profiled
? _profiled.ProfiledComponent
Expand Down Expand Up @@ -42,11 +42,10 @@ const failed = {};

export const toRenderExactlyTimes: MatcherFunction<
[times: number, options?: NextRenderOptions]
> = async function (
_profiled: ProfiledComponent<any, any> | ProfiledHook<any, any>,
times: number,
optionsPerRender?: NextRenderOptions
) {
> = async function (actual, times, optionsPerRender) {
const _profiled = actual as
| ProfiledComponent<any, any>
| ProfiledHook<any, any>;
const profiled =
"ProfiledComponent" in _profiled ? _profiled.ProfiledComponent : _profiled;
const options = { timeout: 100, ...optionsPerRender };
Expand Down
2 changes: 1 addition & 1 deletion src/utilities/common/mergeDeep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ const defaultReconciler: ReconcilerFunction<any[]> = function (

export class DeepMerger<TContextArgs extends any[]> {
constructor(
private reconciler: ReconcilerFunction<TContextArgs> = defaultReconciler
private reconciler: ReconcilerFunction<TContextArgs> = defaultReconciler as any as ReconcilerFunction<TContextArgs>
) {}

public merge(target: any, source: any, ...context: TContextArgs): any {
Expand Down
2 changes: 1 addition & 1 deletion src/utilities/common/mergeOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { compact } from "./compact.js";
type OptionsUnion<TData, TVariables extends OperationVariables, TContext> =
| WatchQueryOptions<TVariables, TData>
| QueryOptions<TVariables, TData>
| MutationOptions<TData, TVariables, TContext>;
| MutationOptions<TData, TVariables, TContext, any>;

export function mergeOptions<
TDefaultOptions extends Partial<OptionsUnion<any, any, any>>,
Expand Down
1 change: 1 addition & 0 deletions src/utilities/observables/Observable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type { Observer, ObservableSubscription, Subscriber };
const { prototype } = Observable;
const fakeObsSymbol = "@@observable" as keyof typeof prototype;
if (!prototype[fakeObsSymbol]) {
// @ts-expect-error
prototype[fakeObsSymbol] = function () {
return this;
};
Expand Down

0 comments on commit b49b269

Please sign in to comment.