subspace-docs/apollo-client.md

75 lines
2.2 KiB
Markdown
Raw Normal View History

2019-09-10 15:40:19 -04:00
# apollo-client
To use Phoenix with `apollo-client`, a composed `ApolloLink` must be defined using the `apollo-link-rxjs` and `reactive-graphl` npm packages. Notice that the `addTypename` option of `InMemoryCache` must be set `false`.
2019-09-04 21:42:27 -04:00
```js
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
2019-09-10 15:40:19 -04:00
import { ApolloLink } from "apollo-link";
import { rxjs as rxJsLink } from "apollo-link-rxjs";
import { graphql } from "reactive-graphql";
2019-09-04 21:42:27 -04:00
2019-09-10 15:40:19 -04:00
const client = new ApolloClient({
// If addTypename:true, the query will fail due to __typename
// being added to the schema. reactive-graphql does not
// support __typename at this moment.
cache: new InMemoryCache({ addTypename: false }),
link: ApolloLink.from([
rxJsLink({}),
new ApolloLink(operation => graphql(schema, operation.query))
])
});
```
### Example
```js{32-45}
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloLink } from "apollo-link";
import { rxjs as rxJsLink } from "apollo-link-rxjs";
import { graphql } from "reactive-graphql";
2019-09-04 21:42:27 -04:00
2019-09-10 15:40:19 -04:00
// ...
2019-09-04 21:42:27 -04:00
2019-09-10 15:40:19 -04:00
// Initialize Phoenix
const eventSyncer = new Phoenix(web3.currentProvider); // Use a valid websocket provider (geth, parity, infura...)
await eventSyncer.init();
2019-09-04 21:42:27 -04:00
2019-09-10 15:40:19 -04:00
const MyContractInstance = ...; // TODO: obtain a web3.eth.contract instance
2019-09-04 21:42:27 -04:00
2019-09-10 15:40:19 -04:00
const typeDefs = `
type MyEvent {
someValue: Int
anotherValue: String
}
type Query {
myEvents: MyEvent!
}
`;
const resolvers = {
Query: {
myEvents: () => {
return eventSyncer.trackEvent(MyContractInstance, 'MyEvent', {filter: {}, fromBlock: 1})
}
}
};
2019-09-04 21:42:27 -04:00
2019-09-10 15:40:19 -04:00
const schema = makeExecutableSchema({ typeDefs, resolvers });
2019-09-04 21:42:27 -04:00
2019-09-10 15:40:19 -04:00
const client = new ApolloClient({
// If addTypename:true, the query will fail due to __typename
// being added to the schema. reactive-graphql does not
// support __typename at this moment.
cache: new InMemoryCache({ addTypename: false }),
link: ApolloLink.from([
rxJsLink({}),
new ApolloLink(operation => graphql(schema, operation.query))
])
});
```
2019-09-04 21:42:27 -04:00
2019-09-10 15:40:19 -04:00
::: tip Using react-apollo
A practical example can also be found in `examples/react-apollo`.
:::