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

Reinstate cache.modify with improved API. #6350

Merged
merged 16 commits into from
May 28, 2020
Merged
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
22 changes: 17 additions & 5 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
- **[BREAKING]** `InMemoryCache` now _throws_ when data with missing or undefined query fields is written into the cache, rather than just warning in development. <br/>
[@benjamn](https://github.com/benjamn) in [#6055](https://github.com/apollographql/apollo-client/pull/6055)

- **[BREAKING]** The `client|cache.writeData` methods have been fully removed, as `writeData` is one of the easiest ways to turn faulty assumptions about how the cache represents data internally into cache inconsistency and corruption. Instead, use `client|cache.writeQuery` or `client|cache.writeFragment` to update the cache. <br/>
- **[BREAKING]** `client|cache.writeData` have been fully removed. `writeData` usage is one of the easiest ways to turn faulty assumptions about how the cache represents data internally, into cache inconsistency and corruption. `client|cache.writeQuery`, `client|cache.writeFragment`, and/or `cache.modify` can be used to update the cache. <br/>
[@benjamn](https://github.com/benjamn) in [#5923](https://github.com/apollographql/apollo-client/pull/5923)

- **[BREAKING]** Apollo Client will no longer deliver "stale" results to `ObservableQuery` consumers, but will instead log more helpful errors about which cache fields were missing. <br/>
Expand All @@ -56,9 +56,6 @@
- **[BREAKING?]** Refactor `QueryManager` to make better use of observables and enforce `fetchPolicy` more reliably. <br/>
[@benjamn](https://github.com/benjamn) in [#6221](https://github.com/apollographql/apollo-client/pull/6221)

- **[beta-BREAKING]** The experimental `cache.modify` method, first introduced in [PR #5909](https://github.com/apollographql/apollo-client/pull/5909), has been removed. <br/>
[@benjamn](https://github.com/benjamn) in [#6289](https://github.com/apollographql/apollo-client/pull/6289)

- `InMemoryCache` now supports tracing garbage collection and eviction. Note that the signature of the `evict` method has been simplified in a potentially backwards-incompatible way. <br/>
[@benjamn](https://github.com/benjamn) in [#5310](https://github.com/apollographql/apollo-client/pull/5310)

Expand Down Expand Up @@ -89,6 +86,21 @@
- The result caching system (introduced in [#3394](https://github.com/apollographql/apollo-client/pull/3394)) now tracks dependencies at the field level, rather than at the level of whole entity objects, allowing the cache to return identical (`===`) results much more often than before. <br/>
[@benjamn](https://github.com/benjamn) in [#5617](https://github.com/apollographql/apollo-client/pull/5617)

- `InMemoryCache` now has a method called `modify` which can be used to update the value of a specific field within a specific entity object:
```ts
cache.modify({
id: cache.identify(post),
fields: {
comments(comments: Reference[], { readField }) {
return comments.filter(comment => idToRemove !== readField("id", comment));
},
},
});
```
This API gracefully handles cases where multiple field values are associated with a single field name, and also removes the need for updating the cache by reading a query or fragment, modifying the result, and writing the modified result back into the cache. Behind the scenes, the `cache.evict` method is now implemented in terms of `cache.modify`. <br/>
[@benjamn](https://github.com/benjamn) in [#5909](https://github.com/apollographql/apollo-client/pull/5909)
and [#6178](https://github.com/apollographql/apollo-client/pull/6178)

- `InMemoryCache` provides a new API for storing client state that can be updated from anywhere:
```ts
const v = cache.makeVar(123)
Expand Down Expand Up @@ -141,7 +153,7 @@
- Make sure `ApolloContext` plays nicely with IE11 when storing the shared context. <br/>
[@ms](https://github.com/ms) in [#5840](https://github.com/apollographql/apollo-client/pull/5840)

- Expose `cache.identify` to the mutation `update` function. <br/>
- Expose cache `modify` and `identify` to the mutate `update` function. <br/>
[@hwillson](https://github.com/hwillson) in [#5956](https://github.com/apollographql/apollo-client/pull/5956)

- Add a default `gc` implementation to `ApolloCache`. <br/>
Expand Down
16 changes: 8 additions & 8 deletions docs/source/data/local-state.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,13 @@ const client = new ApolloClient({
resolvers: {
Mutation: {
toggleTodo: (_root, variables, { cache }) => {
const id = cache.identify({
__typename: 'TodoItem',
id: variables.id,
});
cache.modify(id, {
completed(value) {
return !value;
cache.modify({
id: cache.identify({
__typename: 'TodoItem',
id: variables.id,
}),
modifiers: {
completed: value => !value,
},
});
return null;
Expand Down Expand Up @@ -1095,7 +1095,7 @@ const client = new ApolloClient({
};
```

The `cache.writeQuery` and `cache.writeFragment` methods should cover most of your needs; however, there are some cases where the data you're writing to the cache depends on the data that's already there. In that scenario, you should use `cache.modify(id, modifiers)` to update specific fields within the entity object identified by `id`.
The `cache.writeQuery` and `cache.writeFragment` methods should cover most of your needs; however, there are some cases where the data you're writing to the cache depends on the data that's already there. In that scenario, you can either use a combination of `cache.read{Query,Fragment}` followed by `cache.write{Query,Fragment}`, or use `cache.modify({ id, modifiers })` to update specific fields within the entity object identified by `id`.

### writeQuery and readQuery

Expand Down
6 changes: 2 additions & 4 deletions src/ApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,8 @@ export class ApolloClient<TCacheShape> implements DataProxy {
public writeQuery<TData = any, TVariables = OperationVariables>(
options: DataProxy.WriteQueryOptions<TData, TVariables>,
): void {
const result = this.cache.writeQuery<TData, TVariables>(options);
this.cache.writeQuery<TData, TVariables>(options);
this.queryManager.broadcastQueries();
return result;
}

/**
Expand All @@ -422,9 +421,8 @@ export class ApolloClient<TCacheShape> implements DataProxy {
public writeFragment<TData = any, TVariables = OperationVariables>(
options: DataProxy.WriteFragmentOptions<TData, TVariables>,
): void {
const result = this.cache.writeFragment<TData, TVariables>(options);
this.cache.writeFragment<TData, TVariables>(options);
this.queryManager.broadcastQueries();
return result;
}

public __actionHookForDevTools(cb: () => any) {
Expand Down
16 changes: 16 additions & 0 deletions src/__tests__/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2942,6 +2942,21 @@ describe('@connection', () => {
checkLastResult(abResults, a456bOyez);
checkLastResult(cResults, { c: "see" });

cache.modify({
fields: {
c(value) {
expect(value).toBe("see");
return "saw";
},
},
});
await wait();

checkLastResult(aResults, a456);
checkLastResult(bResults, bOyez);
checkLastResult(abResults, a456bOyez);
checkLastResult(cResults, { c: "saw" });

client.cache.evict("ROOT_QUERY", "c");
await wait();

Expand Down Expand Up @@ -2978,6 +2993,7 @@ describe('@connection', () => {
expect(cResults).toEqual([
{},
{ c: "see" },
{ c: "saw" },
{},
]);

Expand Down
63 changes: 27 additions & 36 deletions src/__tests__/local-state/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -546,21 +546,21 @@ describe('Writing cache data from resolvers', () => {
resolvers: {
Mutation: {
start() {
const obj = {
__typename: 'Object',
id: 'uniqueId',
field: 1,
};

cache.writeQuery({
query,
data: { obj },
data: {
obj: { field: 1, id: 'uniqueId', __typename: 'Object' },
},
});

cache.writeFragment({
id: cache.identify(obj)!,
fragment: gql`fragment Field on Object { field }`,
data: { field: 2 },
cache.modify({
id: 'Object:uniqueId',
fields: {
field(value) {
expect(value).toBe(1);
return 2;
},
},
});

return { start: true };
Expand All @@ -577,7 +577,7 @@ describe('Writing cache data from resolvers', () => {
});
});

itAsync('should not overwrite __typename when writing to the cache with an id', (resolve, reject) => {
it('should not overwrite __typename when writing to the cache with an id', () => {
const query = gql`
{
obj @client {
Expand All @@ -603,35 +603,25 @@ describe('Writing cache data from resolvers', () => {
resolvers: {
Mutation: {
start() {
const obj = {
__typename: 'Object',
id: 'uniqueId',
field: {
__typename: 'Field',
field2: 1,
},
};

cache.writeQuery({
query,
data: { obj },
});

cache.writeFragment({
id: cache.identify(obj)!,
fragment: gql`fragment FieldField2 on Object {
field {
field2
}
}`,
data: {
field: {
__typename: 'Field',
field2: 2,
obj: {
field: { field2: 1, __typename: 'Field' },
id: 'uniqueId',
__typename: 'Object',
},
},
});

cache.modify({
id: 'Object:uniqueId',
fields: {
field(value: { field2: number }) {
expect(value.field2).toBe(1);
return { ...value, field2: 2 };
},
},
})
return { start: true };
},
},
Expand All @@ -644,7 +634,8 @@ describe('Writing cache data from resolvers', () => {
.then(({ data }: any) => {
expect(data.obj.__typename).toEqual('Object');
expect(data.obj.field.__typename).toEqual('Field');
}).then(resolve, reject);
})
.catch(e => console.log(e));
});
});

Expand Down
6 changes: 5 additions & 1 deletion src/cache/core/__tests__/cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import gql from 'graphql-tag';
import { ApolloCache } from '../cache';
import { Cache, DataProxy } from '../..';
import { Reference } from '../../../utilities/graphql/storeUtils';

class TestCache extends ApolloCache<unknown> {
constructor() {
Expand Down Expand Up @@ -45,7 +46,10 @@ class TestCache extends ApolloCache<unknown> {
};
}

public write<TResult = any, TVariables = any>(write: Cache.WriteOptions<TResult, TVariables>): void {
public write<TResult = any, TVariables = any>(
_: Cache.WriteOptions<TResult, TVariables>,
): Reference | undefined {
return;
}
}
const query = gql`{ a }`;
Expand Down
12 changes: 6 additions & 6 deletions src/cache/core/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { DocumentNode } from 'graphql';
import { wrap } from 'optimism';

import { getFragmentQueryDocument } from '../../utilities/graphql/fragments';
import { StoreObject } from '../../utilities/graphql/storeUtils';
import { StoreObject, Reference } from '../../utilities/graphql/storeUtils';
import { DataProxy } from './types/DataProxy';
import { Cache } from './types/Cache';

Expand All @@ -16,7 +16,7 @@ export abstract class ApolloCache<TSerialized> implements DataProxy {
): T | null;
public abstract write<TResult = any, TVariables = any>(
write: Cache.WriteOptions<TResult, TVariables>,
): void;
): Reference | undefined;
public abstract diff<T>(query: Cache.DiffOptions): Cache.DiffResult<T>;
public abstract watch(watch: Cache.WatchOptions): () => void;
public abstract reset(): Promise<void>;
Expand Down Expand Up @@ -124,8 +124,8 @@ export abstract class ApolloCache<TSerialized> implements DataProxy {

public writeQuery<TData = any, TVariables = any>(
options: Cache.WriteQueryOptions<TData, TVariables>,
): void {
this.write({
): Reference | undefined {
return this.write({
dataId: options.id || 'ROOT_QUERY',
result: options.data,
query: options.query,
Expand All @@ -136,8 +136,8 @@ export abstract class ApolloCache<TSerialized> implements DataProxy {

public writeFragment<TData = any, TVariables = any>(
options: Cache.WriteFragmentOptions<TData, TVariables>,
): void {
this.write({
): Reference | undefined {
return this.write({
dataId: options.id,
result: options.data,
variables: options.variables,
Expand Down
2 changes: 1 addition & 1 deletion src/cache/core/types/Cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export namespace Cache {

export interface WriteOptions<TResult = any, TVariables = any>
extends DataProxy.Query<TVariables> {
dataId: string;
dataId?: string;
result: TResult;
broadcast?: boolean;
}
Expand Down
2 changes: 1 addition & 1 deletion src/cache/core/types/DataProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export namespace DataProxy {
* value returned by your `dataIdFromObject` function. If a value with your
* id does not exist in the store, `null` will be returned.
*/
id: string;
id?: string;

/**
* A GraphQL document created using the `gql` template string tag from
Expand Down
6 changes: 2 additions & 4 deletions src/cache/core/types/common.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { DocumentNode } from 'graphql';

// The Readonly<T> type only really works for object types, since it marks
// all of the object's properties as readonly, but there are many cases when
// a generic type parameter like TExisting might be a string or some other
Expand All @@ -13,7 +11,7 @@ export class MissingFieldError {
constructor(
public readonly message: string,
public readonly path: (string | number)[],
public readonly query: DocumentNode,
public readonly variables: Record<string, any>,
public readonly query: import('graphql').DocumentNode,
public readonly variables?: Record<string, any>,
) {}
}
Loading