Created
April 24, 2018 07:07
-
-
Save xialvjun/08645f0493d5ec03591a9171c6ef9318 to your computer and use it in GitHub Desktop.
an naive version of react-apollo Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext } from '@xialvjun/create-react-context'; | |
import { create_client } from '@xialvjun/tiny-graphql-client'; | |
import React, { Component } from 'react'; | |
const tiny_client = create_client(async (body, extra_headers) => { | |
const res = await fetch('http://127.0.0.1:3000/graphql', { | |
method: 'post', | |
body: JSON.stringify(body), | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${window.__TOKEN__}`, | |
...extra_headers, | |
}, | |
}); | |
const obj = await res.json(); | |
if (obj.error) { | |
throw obj.error; | |
} | |
return obj.data; | |
}); | |
const GraphqlState = createContext({ | |
state: { }, | |
key(query, variables) { | |
return query + JSON.stringify(variables); | |
}, | |
get(query, variables) { | |
const key = this.key(query, variables); | |
return this.state[key] || { loading: true }; | |
}, | |
async run(query, variables, network_only=false) { | |
const key = this.key(query, variables); | |
let value = this.state[key] || {}; | |
let { data, loading, error } = value; | |
if (!!loading) { | |
return loading; | |
} | |
if (network_only || !data) { | |
loading = tiny_client.run(query, variables); | |
this.setState({ [key]: { ...value, loading } }); | |
try { | |
data = await loading; | |
this.setState({ [key]: { data } }); | |
} catch (error) { | |
this.setState({ [key]: { data, error } }); | |
} | |
} | |
return data; | |
}, | |
}); | |
export class Client extends Component { | |
runed = {} | |
render() { | |
const { query, variables, network_only, children } = this.props; | |
const ctx = GraphqlState.getContext(); | |
if (!network_only) { | |
ctx.run(query, variables, network_only); | |
} else { | |
const key = ctx.key(query, variables); | |
if (network_only && !this.runed[key]) { | |
this.runed[key] = true; | |
ctx.run(query, variables, network_only); | |
} | |
} | |
return <GraphqlState> | |
{ctx => children(ctx.get(query, variables))} | |
</GraphqlState> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment