Grafoo is a GraphQL client that tries to be different by adopting a simpler API, without giving up of a good caching strategy.
Some useful information
It's a multiple paradigm library. So far we have view layer integrations for react and preact and there are more to come.
It's not just a HTTP client. It comes with a sophisticated caching system under the hood to make sure your data is consistent across your app.
It's build time dependent. A important piece of Grafoo is it's babel plugin that compiles your queries based on the schema your app consumes.
It's environment agnostic. Apart from the browser you can run Grafoo on the server and even on native with react.
Why should I use this
Many of the work that has been put into this project came from borrowed ideas and concepts that are present in the GraphQL clients we have today. Grafoo wants to stand apart from the others trying to be in that sweet spot between simplicity and usability. Moreover, most of the benefits this library brings to the table are related to the fact that it does a lot at build time. It's fast, because it spares runtime computation and it's really small (something like ~1.6kb for core and react) because it does not ship with a GraphQL parser.
The basic packages you'll have to install in order to use Grafoo are core and babel-plugin.
$ npm i @grafoo/core && npm i -D @grafoo/babel-plugin
Configure babel
In @grafoo/babel-plugin the option schema is a path to a GraphQL schema in your file system relative to the root of your project and idFields is an array of strings that represent the fields that Grafoo will automatically insert on your queries to build unique identifiers in order to normalize the cache. Both options are required.
From @grafoo/core you will import the factory that creates the client instance and from submodule @grafoo/core/tag you'll import the graphql or gql tag that will be compiled at build time.
importcreateClientfrom"@grafoo/core";importgqlfrom"@grafoo/core/tag";functionfetchQuery(query,variables){constinit={method: "POST",body: JSON.stringify({ query, variables }),headers: {"content-type": "application/json"}};returnfetch("http://some.graphql.api",init).then(res=>res.json());}constclient=createClient(fetchQuery);constUSER_QUERY=gql` query($id: ID!) { user(id: $id) { name } }`;constvariables={id: 123};client.execute(USER_QUERY,variables).then(data=>{// Write to cacheclient.write(USER_QUERY,variables,data);// Do whatever with returned dataconsole.log(data);// Read from cache at a later stageconsole.log(client.read(USER_QUERY,variables));});// If you wish to reset (clear) the cache:client.reset();
With a framework
Here is how it would go for you to write a simple react app.
请发表评论