npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@wildcards/eth-permit

v0.0.0-placeholder

Published

<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->

Downloads

4

Readme

reason-apollo-hooks

All Contributors

Reason bindings for the official @apollo/react-hooks

Table of contents

Installation :arrow_up:

yarn add reason-apollo-hooks [email protected] @apollo/react-hooks

BuckleScript <= 5.0.0

yarn add [email protected] [email protected] @apollo/react-hooks

Follow the installation instructions of graphql_ppx_re.

Then update your bsconfig.json

"bs-dependencies": [
  ...
+ "reason-apollo-hooks",
+ "reason-apollo"
]

Setting up :arrow_up:

Add the provider in the top of the tree

/* Create an InMemoryCache */
let inMemoryCache = ApolloInMemoryCache.createInMemoryCache();

/* Create an HTTP Link */
let httpLink =
  ApolloLinks.createHttpLink(~uri="http://localhost:3010/graphql", ());

let client =
  ReasonApollo.createApolloClient(~link=httpLink, ~cache=inMemoryCache, ());

let app =
 <ApolloHooks.Provider client>
   ...
 </ApolloHooks.Provider>

Usage with reason-apollo :arrow_up:

To use with reason-apollo's ReasonApollo.Provider already present in your project:

let client = ... // create Apollo client

ReactDOMRe.renderToElementWithId(
  <ReasonApollo.Provider client>
    <ApolloHooks.Provider client>
      <App />
    </ApolloHooks.Provider>
  </ReasonApollo.Provider>,
  "root",
);

Available hooks :arrow_up:

useQuery :arrow_up:

open ApolloHooks

module UserQuery = [%graphql {|
  query UserQuery {
    currentUser {
      name
    }
  }
|}];

[@react.component]
let make = () => {
  /* Both variant and records available */
  let (simple, _full) = useQuery(UserQuery.definition);

  <div>
  {
    switch(simple) {
      | Loading => <p>{React.string("Loading...")}</p>
      | Data(data) =>
        <p>{React.string(data##currentUser##name)}</p>
      | NoData
      | Error(_) => <p>{React.string("Get off my lawn!")}</p>
    }
  }
  </div>
}

Using the full record for more advanced cases

[@react.component]
let make = () => {
  /* Both variant and records available */
  let (_simple, full) = useQuery(UserQuery.definition);

  <div>
  {
    switch(full) {
      | { loading: true }=> <p>{React.string("Loading...")}</p>
      | { data: Some(data) } =>
        <p>{React.string(data##currentUser##name)}</p>
      | any other possibilities =>
      | { error: Some(_) } => <p>{React.string("Get off my lawn!")}</p>
    }
  }
  </div>
}

Using fetchPolicy to change interactions with the apollo cache, see apollo docs.

let (_simple, full) = useQuery(~fetchPolicy=NetworkOnly, UserQuery.definition);

Using errorPolicy to change how errors are handled, see apollo docs.

let (simple, _full) = useQuery(~errorPolicy=All, UserQuery.definition);

Using skip to skip query entirely, see apollo docs.

let (simple, _full) =
  useQuery(
    ~skip=
      switch (value) {
      | None => true
      | _ => false
      },
    UserQuery.definition,
  );

useMutation :arrow_up:

module ScreamMutation = [%graphql {|
  mutation ScreamMutation($screamLevel: Int!) {
    scream(level: $screamLevel) {
      error
    }
  }
|}];

[@react.component]
let make = () => {
  /* Both variant and records available */
  let ( screamMutation, _simple, _full ) = useMutation(~variables=ScreamMutation.makeVariables(~screamLevel=10, ()), ScreamMutation.definition);
  let scream = (_) => {
    screamMutation()
      |> Js.Promise.then_(result => {
          switch(result) {
            | Data(data) => ...
            | Error(error) => ...
            | NoData => ...
          }
          Js.Promise.resolve()
        })
      |> ignore
  }

  <div>
    <button onClick={scream}>
      {React.string("You kids get off my lawn!")}
    </button>
  </div>
}

If you don't know the value of the variables yet you can pass them in later

[@react.component]
let make = () => {
  /* Both variant and records available */
  let ( screamMutation, _simple, _full ) = useMutation(ScreamMutation.definition);
  let scream = (_) => {
    screamMutation(~variables=ScreamMutation.makeVariables(~screamLevel=10, ()), ())
      |> Js.Promise.then_(result => {
          switch(result) {
            | Data(data) => ...
            | Error(error) => ...
            | NoData => ...
          }
          Js.Promise.resolve()
        })
      |> ignore
  }

  <div>
    <button onClick={scream}>
      {React.string("You kids get off my lawn!")}
    </button>
  </div>
}

useSubscription :arrow_up:

In order to use subscriptions, you first need to set up your websocket link:

/* Create an InMemoryCache */
let inMemoryCache = ApolloInMemoryCache.createInMemoryCache();

/* Create an HTTP Link */
let httpLink =
  ApolloLinks.createHttpLink(~uri="http://localhost:3010/graphql", ());
+
+/* Create a WS Link */
+let webSocketLink =
+  ApolloLinks.webSocketLink({
+    uri: "wss://localhost:3010/graphql",
+    options: {
+      reconnect: true,
+      connectionParams: None,
+    },
+  });
+
+/* Using the ability to split links, you can send data to each link
+   depending on what kind of operation is being sent */
+let link =
+  ApolloLinks.split(
+    operation => {
+      let operationDefition =
+        ApolloUtilities.getMainDefinition(operation.query);
+      operationDefition.kind == "OperationDefinition"
+      && operationDefition.operation == "subscription";
+    },
+    webSocketLink,
+    httpLink,
+  );

let client =
-  ReasonApollo.createApolloClient(~link=httpLink, ~cache=inMemoryCache, ());
+  ReasonApollo.createApolloClient(~link, ~cache=inMemoryCache, ());

let app =
 <ApolloHooks.Provider client>
   ...
 </ApolloHooks.Provider>

Then, you can implement useSubscription in a similar manner to useQuery

module UserAdded = [%graphql {|
  subscription userAdded {
    userAdded {
      id
      name
    }
  }
|}];


[@react.component]
let make = () => {
  let (userAddedSubscription, _full) = ApolloHooks.useSubscription(UserAdded.definition);

  switch (userAddedSubscription) {
    | Loading => <div> {ReasonReact.string("Loading")} </div>
    | Error(error) => <div> {ReasonReact.string(error##message)} </div>
    | Data(_response) =>
      <audio autoPlay=true>
      <source src="notification.ogg" type_="audio/ogg" />
      <source src="notification.mp3" type_="audio/mpeg" />
    </audio>
  };
};

Cache :arrow_up:

There are a couple of caveats with manual cache updates.

TL;DR

  1. If you need to remove items from cached data, it is enough to just filter them out and save the result into cache as is.
  2. If you need to add the result of a mutation to a list of items with the same shape, you simply concat it with the list and save into cache as it.
  3. When you need to update a field, you have to resort to raw javascript to use spread operator on Js.t object in order to preserve __typename that apollo adds to all queries by default.

An example of cache update could look like this:

module PersonsQuery = [%graphql
{|
  query getAllPersons  {
    allPersons  {
      id
      age
      name
    }
  }
|}
];

module PersonsReadQuery = ApolloClient.ReadQuery(PersonsQuery);
module PersonsWriteQuery = ApolloClient.WriteQuery(PersonsQuery);

external cast: Js.Json.t => PersonsQuery.t = "%identity";

let updatePersons = (~client, ~name, ~age) => {
  let query = PersonsQuery.make();
  let readQueryOptions = ApolloHooks.Utils.toReadQueryOptions(query);

  // can throw exception of cache is empty
  switch (PersonsReadQuery.readQuery(client, readQueryOptions)) {
  | exception _ => ()
  | cachedResponse =>
    switch (cachedResponse |> Js.Nullable.toOption) {
    | None => ()
    | Some(cachedPersons) =>
      // readQuery will return unparsed data with __typename field, need to cast it since
      // it has type Json.t, but we know it will have the same type as PersonsReadQuery.t
      let persons = cast(cachedPersons);

      // to remove items, simply filter them out
      let updatedPersons = {
        "allPersons":
          Belt.Array.keep(persons##allPersons, person => person##age !== age),
      };

      // when updating items, __typename must be preserved, but since it is not a record,
      // can't use spread, so use JS to update items
      let updatedPersons = {
        "allPersons":
          Belt.Array.map(persons##allPersons, person =>
            person##name === name ? [%bs.raw {| {...person, age } |}] : person
          ),
      };

      PersonsWriteQuery.make(
        ~client,
        ~variables=query##variables,
        ~data=updatedPersons,
        (),
      );
    }
  };
};

reason-apollo-hooks parses response data from a query or mutation using parse function created by graphql_ppx. For example, when using @bsRecord directive, the response object will be parsed from a Js.t object to a reason record. In this case, the response data in reason code is not the same object that is stored in cache, since react-apollo saves data in cache before it is parsed and returned to the component. However, when updating cache, the data must be in the same format or apollo cache won't work correctly and throw errors.

If using directives like @bsRecord, @bsDecoder or @bsVariant in graphql_ppx, the data needs to be serialized back to JS object before it is written in cache. Since there is currently no way to serialize this data (see this issue in graphql_ppx), queries that will be updated in cache shouldn't use any of those directive, unless you will take care of the serialization yourself.

By default, apollo will add field __typename to the queries and will use it to normalize data and manipulate cache (see normalization). This field won't exist on parsed reason objects, since it is not included in the actual query you write, but is added by apollo before sending the query. Since __typename is crucial for the cache to work correctly, we need to read data from cache in its raw unparsed format, which is achieved with readQuery from ApolloClient.ReadQuery defined in reason-apollo.

Getting it running

yarn
yarn start

Contributors ✨

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!