Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
10 changes: 10 additions & 0 deletions docs/fetching/queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,16 @@ setClient(
notes = useQuery(this, () => [GET_NOTES, { clientId: 'my-custom-client' }]);
```

### `returnPartialData`

With `returnPartialData: true`, Apollo Client reads whatever the cache already holds for the query while the network request is in flight, so `data` can miss fields. `useQuery` then returns a `PartialQueryResource`: `data` and the `onComplete` argument are typed as `DataValue.Partial<TData>` from `@apollo/client`.

```ts
notes = useQuery(this, () => [GET_NOTES, { returnPartialData: true }]);

// notes.data?.notes may be undefined, and each note may miss fields
```

## Query Status

### `loading`
Expand Down
42 changes: 32 additions & 10 deletions glimmer-apollo/src/-private/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { createPromise, getFastboot, settled } from './utils.ts';

import type {
ApolloClient,
DataValue,
DocumentNode,
ErrorLike,
MaybeMasked,
Expand All @@ -24,37 +25,57 @@ import type {
import type { Subscription } from 'rxjs';
import type { TemplateArgs } from './types';

export type QueryOptions<TData, TVariables extends OperationVariables> = Omit<
/**
* `TResultData` is the shape `data` (and `onComplete`'s argument) is typed
* as: complete by default, `DataValue.Partial` when `returnPartialData` is set.
*/
export type QueryOptions<
TData,
TVariables extends OperationVariables,
TResultData = MaybeMasked<TData>,
> = Omit<
ApolloClient.WatchQueryOptions<TData, TVariables>,
'query' | 'variables'
> & {
variables?: TVariables;
skip?: boolean;
ssr?: boolean;
clientId?: string;
onComplete?: (data: MaybeMasked<TData> | undefined) => void;
onComplete?: (data: TResultData | undefined) => void;
onError?: (error: ErrorLike) => void;
};

export type QueryPositionalArgs<
TData,
TVariables extends OperationVariables = OperationVariables,
TResultData = MaybeMasked<TData>,
> = [
DocumentNode | TypedDocumentNode<TData, TVariables>,
QueryOptions<TData, TVariables>?,
QueryOptions<TData, TVariables, TResultData>?,
];

/**
* A query read with `returnPartialData`: `data` can miss fields, whether it is
* a cache read before the network answers, a result with `errorPolicy: 'all'`
* where a field errored, or a cache read after an eviction.
*/
export type PartialQueryResource<
TData,
TVariables extends OperationVariables = OperationVariables,
> = QueryResource<TData, TVariables, DataValue.Partial<MaybeMasked<TData>>>;

export class QueryResource<
TData,
TVariables extends OperationVariables = OperationVariables,
TResultData = MaybeMasked<TData>,
> extends ObservableResource<
TData,
TVariables,
TemplateArgs<QueryPositionalArgs<TData, TVariables>>
> {
@tracked loading = false;
@tracked error?: ErrorLike;
@tracked data: MaybeMasked<TData> | undefined;
@tracked data: TResultData | undefined;
@tracked networkStatus: NetworkStatus = NetworkStatus.loading;
@tracked promise!: Promise<void>;

Expand Down Expand Up @@ -171,11 +192,9 @@ export class QueryResource<
const { loading, error, data, networkStatus } = result;

this.loading = loading;
// Cast: Apollo Client 4's result type includes DeepPartial<TData> to
// account for returnPartialData. We expose the stricter TData since
// consumers who opt into returnPartialData already expect partial shapes.
// If AC4 tightens this typing in a future version, revisit this cast.
this.data = data as MaybeMasked<TData> | undefined;
// Apollo types every result's data as complete | partial; the overload
// that built this resource decided which of the two TResultData is.
this.data = data as TResultData | undefined;
this.networkStatus = networkStatus;
this.error = error;

Expand All @@ -202,7 +221,10 @@ export class QueryResource<

const invoke = (): void => {
if (onComplete && !error) {
onComplete(data);
// args keep the default options type so a complete resource stays
// assignable to a partial one; the overload matched onComplete's
// parameter to TResultData already.
onComplete(data as MaybeMasked<TData> | undefined);
} else if (onError && error) {
onError(error);
}
Expand Down
43 changes: 39 additions & 4 deletions glimmer-apollo/src/-private/usables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
MutationResource,
} from './mutation.ts';
import {
type PartialQueryResource,
type QueryOptions,
type QueryPositionalArgs,
QueryResource,
Expand All @@ -13,11 +14,25 @@ import {
type SubscriptionPositionalArgs,
SubscriptionResource,
} from './subscription.ts';
import type { OperationVariables, TypedDocumentNode } from '@apollo/client';
import type {
NoInfer,
SignatureStyle,
} from '@apollo/client/utilities/internal';
DataValue,
MaybeMasked,
OperationVariables,
TypedDocumentNode,
} from '@apollo/client';
import type { SignatureStyle } from '@apollo/client/utilities/internal';

/**
* Options that select the partial overload. `returnPartialData: boolean`
* rather than `true` so a flag variable also lands here, as in Apollo's own
* `useQuery` overloads.
*/
type PartialQueryOptions<
TData,
TVariables extends OperationVariables,
> = QueryOptions<TData, TVariables, DataValue.Partial<MaybeMasked<TData>>> & {
returnPartialData: boolean;
};

/* eslint-disable @typescript-eslint/no-namespace, @typescript-eslint/no-empty-object-type --
Namespaces and the empty-extends interface mirror Apollo Client 4.2's own
Expand All @@ -28,6 +43,16 @@ import type {
export namespace useQuery {
export namespace Signatures {
export interface Classic {
<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
parentDestroyable: object,
args: () => [
QueryPositionalArgs<TData, TVariables>[0],
PartialQueryOptions<TData, TVariables>,
],
): PartialQueryResource<TData, TVariables>;
<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
Expand All @@ -37,6 +62,16 @@ export namespace useQuery {
): QueryResource<TData, TVariables>;
}
export interface Modern {
<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
parentDestroyable: object,
args: () => [
TypedDocumentNode<TData, TVariables>,
PartialQueryOptions<TData, NoInfer<TVariables>>,
],
): PartialQueryResource<TData, TVariables>;
<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
Expand Down
1 change: 1 addition & 0 deletions glimmer-apollo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type {
UseSubscription,
} from './-private/usables.ts';
export type {
PartialQueryResource,
QueryOptions,
QueryResource,
QueryPositionalArgs,
Expand Down
36 changes: 36 additions & 0 deletions test-app/tests/unit/query-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,42 @@ module('useQuery', function (hooks) {
assert.equal(query.data?.user?.id, '2');
});

test('it reports partial data from the cache, then complete', async function (assert) {
const partialClient = new ApolloClient({
cache: new InMemoryCache(),
link,
});
setClient(ctx, partialClient);
partialClient.writeQuery({
query: gql`
query UserFirstName($id: ID!) {
user(id: $id) {
id
firstName
}
}
`,
variables: { id: '1' },
data: { user: { __typename: 'User', id: '1', firstName: 'Cathaline' } },
});

const lastNames: (string | undefined)[] = [];
const query = useQuery<UserInfoQuery, UserInfoQueryVariables>(ctx, () => [
USER_INFO,
{
variables: { id: '1' },
returnPartialData: true,
onComplete: (data) => lastNames.push(data?.user?.lastName),
},
]);

assert.equal(query.data?.user?.firstName, 'Cathaline');
assert.equal(query.data?.user?.lastName, undefined);
await query.promise;
assert.equal(query.data?.user?.lastName, 'McCoy');
assert.deepEqual(lastNames, [undefined, 'McCoy']);
});

test('it returns error', async function (assert) {
const query = useQuery<UserInfoQuery, UserInfoQueryVariables>(ctx, () => [
USER_INFO,
Expand Down
67 changes: 65 additions & 2 deletions test-app/tests/unit/types/query-types-test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { module, test } from 'qunit';
import { useQuery } from 'glimmer-apollo';
import type { QueryResource } from 'glimmer-apollo';
import type { TypedDocumentNode } from '@apollo/client';
import type { PartialQueryResource, QueryResource } from 'glimmer-apollo';
import type { DataValue, TypedDocumentNode } from '@apollo/client';
import type {
UserInfoQuery,
UserInfoQueryVariables,
Expand Down Expand Up @@ -42,6 +42,69 @@ function _typeAssertions() {
expectTypeOf(qc).toEqualTypeOf<
QueryResource<UserInfoQuery, UserInfoQueryVariables>
>();

// returnPartialData: data may miss fields.
const qp = useQueryModern(ctx, () => [
USER_INFO,
{ variables: { id: '1' }, returnPartialData: true },
]);
expectTypeOf(qp).toEqualTypeOf<
PartialQueryResource<UserInfoQuery, UserInfoQueryVariables>
>();
expectTypeOf(qp.data).toEqualTypeOf<
DataValue.Partial<UserInfoQuery> | undefined
>();
if (qp.data?.user) {
// @ts-expect-error - a field of partial data may be missing
takesString(qp.data.user.firstName);
}
if (q.data?.user) {
takesString(q.data.user.firstName);
}

const qcp = useQueryClassic<UserInfoQuery, UserInfoQueryVariables>(
ctx,
() => [USER_INFO, { variables: { id: '1' }, returnPartialData: true }]
);
expectTypeOf(qcp.data).toEqualTypeOf<
DataValue.Partial<UserInfoQuery> | undefined
>();

// A boolean flag, not only the literal true, selects the partial shape.
const flag = Boolean(ctx);
const qf = useQueryModern(ctx, () => [
USER_INFO,
{ variables: { id: '1' }, returnPartialData: flag },
]);
expectTypeOf(qf.data).toEqualTypeOf<
DataValue.Partial<UserInfoQuery> | undefined
>();

// onComplete receives the same partial shape as data.
useQueryModern(ctx, () => [
USER_INFO,
{
variables: { id: '1' },
returnPartialData: true,
onComplete: (data) => {
expectTypeOf(data).toEqualTypeOf<
DataValue.Partial<UserInfoQuery> | undefined
>();
},
},
]);

// A complete resource fits where a partial one is expected, not the reverse.
expectTypeOf(q).toExtend<
PartialQueryResource<UserInfoQuery, UserInfoQueryVariables>
>();
expectTypeOf(qp).not.toExtend<
QueryResource<UserInfoQuery, UserInfoQueryVariables>
>();
}

function takesString(value: string) {
return value;
}

// Default (no TypeOverrides augmentation): the exported `useQuery` resolves to
Expand Down
Loading