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

Eliminate cache.writeData. #5923

Merged
merged 3 commits into from
Mar 2, 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@
- **[BREAKING]** Apollo Client 2.x allowed `@client` fields to be passed into the `link` chain if `resolvers` were not set in the constructor. This allowed `@client` fields to be passed into Links like `apollo-link-state`. Apollo Client 3 enforces that `@client` fields are local only, meaning they are no longer passed into the `link` chain, under any circumstances. <br/>
[@hwillson](https://github.com/hwillson) in [#5982](https://github.com/apollographql/apollo-client/pull/5982)

- **[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)

- `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
2 changes: 1 addition & 1 deletion docs/shared/mutation-result.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@
| `loading` | boolean | A boolean indicating whether your mutation is in flight |
| `error` | ApolloError | Any errors returned from the mutation |
| `called` | boolean | A boolean indicating if the mutate function has been called |
| `client` | ApolloClient | Your `ApolloClient` instance. Useful for invoking cache methods outside the context of the update function, such as `client.writeData` and `client.readQuery`. |
| `client` | ApolloClient | Your `ApolloClient` instance. Useful for invoking cache methods outside the context of the update function, such as `client.writeQuery` and `client.readQuery`. |
212 changes: 130 additions & 82 deletions docs/source/data/local-state.mdx

Large diffs are not rendered by default.

22 changes: 22 additions & 0 deletions docs/source/migrating/apollo-client-3-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,25 @@ The following cache changes are **not** backward compatible. Take them into cons
* All cache results are now frozen/immutable, as promised in the [Apollo Client 2.6 blog post](https://blog.apollographql.com/whats-new-in-apollo-client-2-6-b3acf28ecad1) ([PR #5153](https://github.com/apollographql/apollo-client/pull/5153)).
* `FragmentMatcher`, `HeuristicFragmentMatcher`, and `IntrospectionFragmentMatcher` have all been removed. We recommend using the `InMemoryCache`’s `possibleTypes` option instead. For more information, see [Defining possibleTypes manually](../data/fragments/#defining-possibletypes-manually) ([PR #5073](https://github.com/apollographql/apollo-client/pull/5073)).
* The internal representation of normalized data in the cache has changed. If you’re using `apollo-cache-inmemory`’s public API, then these changes shouldn’t impact you. If you are manipulating cached data directly instead, review [PR #5146](https://github.com/apollographql/apollo-client/pull/5146) for details.
* `client|cache.writeData` have been fully removed. `client|cache.writeQuery`, `client|cache.writeFragment`, and/or `cache.modify` can be used to update the cache. For example:

```js
client.writeData({
data: {
cartItems: []
}
});
```

can be converted to:

```js
client.writeQuery({
query: gql`{ cartItems }`,
data: {
cartItems: []
}
});
```

For more details around why `writeData` has been removed, see [PR #5923](https://github.com/apollographql/apollo-client/pull/5923).
18 changes: 0 additions & 18 deletions src/ApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -427,24 +427,6 @@ export class ApolloClient<TCacheShape> implements DataProxy {
return result;
}

/**
* Sugar for writeQuery & writeFragment
* This method will construct a query from the data object passed in.
* If no id is supplied, writeData will write the data to the root.
* If an id is supplied, writeData will write a fragment to the object
* specified by the id in the store.
*
* Since you aren't passing in a query to check the shape of the data,
* you must pass in an object that conforms to the shape of valid GraphQL data.
*/
public writeData<TData = any>(
options: DataProxy.WriteDataOptions<TData>,
): void {
const result = this.cache.writeData<TData>(options);
this.queryManager.broadcastQueries();
return result;
}

public __actionHookForDevTools(cb: () => any) {
this.devToolsHookCb = cb;
}
Expand Down
165 changes: 0 additions & 165 deletions src/__tests__/ApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1422,171 +1422,6 @@ describe('ApolloClient', () => {
});
});

describe('writeData', () => {
it('lets you write to the cache by passing in data', () => {
const query = gql`
{
field
}
`;

const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
});

client.writeData({ data: { field: 1 } });

return client.query({ query }).then(({ data }) => {
expect(stripSymbols({ ...data })).toEqual({ field: 1 });
});
});

it('lets you write to an existing object in the cache using an ID', () => {
const query = gql`
{
obj {
field
}
}
`;

const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
});

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

client.writeData({ id: 'Object:uniqueId', data: { field: 2 } });

return client.query({ query }).then(({ data }: any) => {
expect(data.obj.field).toEqual(2);
});
});

it(`doesn't overwrite __typename when writing to the cache with an id`, () => {
const query = gql`
{
obj {
field {
field2
}
id
}
}
`;

const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
});

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

client.writeData({
id: 'Object:uniqueId',
data: { field: { field2: 2, __typename: 'Field' } },
});

return client
.query({ query })
.then(({ data }: any) => {
expect(data.obj.__typename).toEqual('Object');
expect(data.obj.field.__typename).toEqual('Field');
})
.catch(e => console.log(e));
});

it(`adds a __typename for an object without one when writing to the cache with an id`, () => {
const query = gql`
{
obj {
field {
field2
}
id
}
}
`;

// This would cause a warning to be printed because we don't have
// __typename on the obj field. But that's intentional because
// that's exactly the situation we're trying to test...

// Let's swap out console.warn to suppress this one message

const suppressString = '__typename';
const originalWarn = console.warn;
console.warn = (...args: any[]) => {
if (
args.find(element => {
if (typeof element === 'string') {
return element.indexOf(suppressString) !== -1;
}
return false;
}) != null
) {
// Found a thing in the args we told it to exclude
return;
}
originalWarn.apply(console, args);
};

const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
});

client.writeQuery({
query,
data: {
obj: {
__typename: 'Obj',
field: {
field2: 1,
__typename: 'Field',
},
id: 'uniqueId',
},
},
});

client.writeData({
id: 'Obj:uniqueId',
data: {
field: {
field2: 2,
__typename: 'Field',
},
},
});

return client
.query({ query })
.then(({ data }: any) => {
console.warn = originalWarn;
expect(data.obj.__typename).toEqual('Obj');
expect(data.obj.field.__typename).toEqual('Field');
})
.catch(e => console.log(e));
});
});

describe('write then read', () => {
it('will write data locally which will then be read back', () => {
const client = new ApolloClient({
Expand Down
48 changes: 35 additions & 13 deletions src/__tests__/local-state/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ describe('@client @export tests', () => {
link: ApolloLink.empty(),
resolvers: {},
});
cache.writeData({ data: { field: 1 } });

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

return client.query({ query }).then(({ data }: any) => {
expect({ ...data }).toMatchObject({ field: 1 });
Expand Down Expand Up @@ -54,7 +58,8 @@ describe('@client @export tests', () => {
resolvers: {},
});

cache.writeData({
cache.writeQuery({
query,
data: {
car: {
engine: {
Expand Down Expand Up @@ -106,7 +111,8 @@ describe('@client @export tests', () => {
},
});

cache.writeData({
cache.writeQuery({
query,
data: {
currentAuthorId: testAuthorId,
},
Expand Down Expand Up @@ -156,7 +162,8 @@ describe('@client @export tests', () => {
},
});

cache.writeData({
cache.writeQuery({
query,
data: {
currentAuthor: testAuthor,
},
Expand Down Expand Up @@ -206,7 +213,8 @@ describe('@client @export tests', () => {
resolvers: {},
});

cache.writeData({
cache.writeQuery({
query,
data: {
currentAuthor: testAuthor,
},
Expand Down Expand Up @@ -268,7 +276,8 @@ describe('@client @export tests', () => {
resolvers: {},
});

cache.writeData({
cache.writeQuery({
query,
data: {
appContainer,
},
Expand Down Expand Up @@ -371,7 +380,8 @@ describe('@client @export tests', () => {
resolvers: {},
});

cache.writeData({
cache.writeQuery({
query,
data: {
postRequiringReview: {
loggedInReviewerId,
Expand Down Expand Up @@ -450,7 +460,8 @@ describe('@client @export tests', () => {
},
});

cache.writeData({
cache.writeQuery({
query,
data: {
postRequiringReview: {
__typename: 'Post',
Expand Down Expand Up @@ -560,7 +571,8 @@ describe('@client @export tests', () => {
resolvers: {},
});

cache.writeData({
cache.writeQuery({
query: gql`{ topPost }`,
data: {
topPost: testPostId,
},
Expand Down Expand Up @@ -685,7 +697,8 @@ describe('@client @export tests', () => {
resolvers: {},
});

cache.writeData({
cache.writeQuery({
query,
data: {
primaryReviewerId,
secondaryReviewerId,
Expand Down Expand Up @@ -736,7 +749,10 @@ describe('@client @export tests', () => {
resolvers: {},
});

client.writeData({ data: { currentAuthorId: testAuthorId1 } });
client.writeQuery({
query,
data: { currentAuthorId: testAuthorId1 },
});

const obs = client.watchQuery({ query });
obs.subscribe({
Expand All @@ -746,7 +762,10 @@ describe('@client @export tests', () => {
currentAuthorId: testAuthorId1,
postCount: testPostCount1,
});
client.writeData({ data: { currentAuthorId: testAuthorId2 } });
client.writeQuery({
query,
data: { currentAuthorId: testAuthorId2 },
});
} else if (resultCount === 1) {
expect({ ...data }).toMatchObject({
currentAuthorId: testAuthorId2,
Expand Down Expand Up @@ -796,7 +815,10 @@ describe('@client @export tests', () => {
resolvers: {},
});

client.writeData({ data: { currentAuthorId: testAuthorId1 } });
client.writeQuery({
query,
data: { currentAuthorId: testAuthorId1 },
});

const obs = client.watchQuery({ query });
obs.subscribe({
Expand Down
Loading