Skip to content

Commit

Permalink
return null when data from an id cannot be found
Browse files Browse the repository at this point in the history
  • Loading branch information
calebmer committed Feb 22, 2017
1 parent 37cd7b9 commit b716e19
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/ApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,13 +385,23 @@ export default class ApolloClient {
fragment: DocumentNode,
fragmentName?: string,
variables?: Object,
): FragmentType {
): FragmentType | null {
this.initStore();

const query = getFragmentQuery(fragment, fragmentName);
const reduxRootSelector = this.reduxRootSelector || defaultReduxRootSelector;
const store = reduxRootSelector(this.store.getState()).data;

// If we could not find an item in the store with the provided id then we
// just return `null`.
if (typeof store[id] === 'undefined') {
return null;
}

return readQueryFromStore<FragmentType>({
rootId: id,
store: reduxRootSelector(this.store.getState()).data,
query: getFragmentQuery(fragment, fragmentName),
store,
query,
variables,
returnPartialData: false,
});
Expand Down
26 changes: 26 additions & 0 deletions test/ApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,32 @@ describe('ApolloClient', () => {
},
), { a: 1, b: 2 });
});

it('will return null when an id that can’t be found is provided', () => {
const client1 = new ApolloClient();
const client2 = new ApolloClient({
initialState: {
apollo: {
data: {
'bar': { __typename: 'Type1', a: 1, b: 2, c: 3 },
},
},
},
});
const client3 = new ApolloClient({
initialState: {
apollo: {
data: {
'foo': { __typename: 'Type1', a: 1, b: 2, c: 3 },
},
},
},
});

assert.equal(client1.readFragment('foo', gql`fragment fooFragment on Foo { a b c }`), null);
assert.equal(client2.readFragment('foo', gql`fragment fooFragment on Foo { a b c }`), null);
assert.deepEqual(client3.readFragment('foo', gql`fragment fooFragment on Foo { a b c }`), { a: 1, b: 2, c: 3 });
});
});

describe('writeQuery', () => {
Expand Down

0 comments on commit b716e19

Please sign in to comment.