https://github.com/drawbotics/urql-computed-exchange
An URQL exchange to compute data from resolvers in domain entities
https://github.com/drawbotics/urql-computed-exchange
Last synced: 6 months ago
JSON representation
An URQL exchange to compute data from resolvers in domain entities
- Host: GitHub
- URL: https://github.com/drawbotics/urql-computed-exchange
- Owner: Drawbotics
- License: unlicense
- Created: 2019-07-12T19:34:30.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2023-01-05T12:22:09.000Z (over 2 years ago)
- Last Synced: 2023-02-26T11:16:06.859Z (over 2 years ago)
- Language: TypeScript
- Size: 999 KB
- Stars: 13
- Watchers: 1
- Forks: 2
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# URQL Computed Exchange
An [URQL](https://github.com/FormidableLabs/urql) exchange to compute data using resolvers and entities.
## Installation
```bash
$ npm i urql-computed-exchange
```## Usage
First, create your entities and their resolvers:
```javascript
// entities.js
import { createEntity, mergeEntities } from 'urql-computed-exchange';const Pokemon = createEntity('Pokemon', {
numberOfEvolutions: {
dependencies: gql`
fragment _ on Pokemon {
evolutions {
id
}
}
`,
resolver: (pokemon) => {
return (pokemon.evolutions && pokemon.evolutions.length) ?? 0;
},
},
});export default mergeEntities(Pokemon);
```Then, add it to the list of exchanges in URQL when setting up the client:
```javascript
// client.jsimport { computedExchange } from 'urql-computed-exchange';
import {
createClient,
cacheExchange,
dedupExchange,
fetchExchange,
} from 'urql';import entities from './entities';
const client = createClient({
url: 'https://graphql-pokemon.now.sh/',
exchanges: [
dedupExchange,
cacheExchange,
computedExchange({ entities }),
fetchExchange,
],
});export default client;
```Finally, use the `@computed` directive when declaring your GraphQL queries. Don't forget to indicate the corresponding `type`:
```javascript
// App.jsimport React from 'react';
import { useQuery } from 'urql';
import gql from 'graphql-tag';const PokemonQuery = gql`
query PokemonQuery {
pokemon(name: "charmander") {
id
name
numberOfEvolutions @computed(type: Pokemon)
}
}
`;const App = () => {
const [ res ] = useQuery({
query: PokemonQuery,
});if (res.fetching) {
return 'Loading...';
}return (
{JSON.stringify(res.data, null, 2)}
);
};export default App;
```