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

graphql-relay-node

v1.0.1

Published

Simplify managing global ids used in graphql-relay

Downloads

2

Readme

GraphQL-relay-node

Simplify managing global ids used in graphql-relay

A basic understanding of GraphQL and relay-compliant schemas is needed to provide context for this library.

Graphql-relay creates a global id for use in the graphql schema by concatenating the graphql type and the id of the node using the methods fromGlobalId and toGlobalId.

In a relay compliant schema it is common to use these global ids in order to perform mutations on specific node. Consider the following mutation:

type Mutation {
    editUser(userId: ID!, newName: String!) User
}

type User implements Node {
    id: ID!
    name: String!
}

As input this mutation expects a userId which is a global id.

Typically the resolver for this mutation would be implemented as follows:

resolve = async (_, args) => {
  const { userId, newName } = args;

  const { type, id } = fromGlobalId(userId);

  if (type !== "User" || !id) {
    throw new Error("Invalid user id");
  }

  const user = await fetchUser(id);

  if (!user) {
    throw new Error("No user found");
  }

  // ...mutate data

  return user;
};

The example above shows that there is quite a lot of code involved to parse the userId and perform all the relevant checks. These checks can get quite tedious and become inconsistent when implemented across many different mutations.

This library aims to solve this problem by creating a simple API for retrieving a node from a global id.

The first step is define a NodeFetcher instance. This class performs all the necessary error handling when working with global ids and will return the node to the mutation resolver.

//nodeFetcher.js

import { fromGlobalId } from "graphql-relay";
import NodeFetcher from "graphql-relay-node";

const idFetcher = ({ type, id }) => {
  if (type === "User") {
    return fetchUser(id);
  }
};

const nodeFetcher = new NodeFetcher({
  fromGlobalId,
  idFetcher
});

export default nodeFetcher;

Next, we import the nodeFetcher in the resolver of the mutation and pass the global id and the expected Node type ("User" in this case). The fetch method returns the node associated with the global id. All the error handling is done by the NodeFetcher class.

import nodeFetcher from "./nodeFetcher";

resolve = async (_, args) => {
  const user = await nodeFetcher.fetch(userId, "User");

  // ...mutate data

  return user;
};

This instance of nodeFetcher can be used to retrieve nodes of a specific type in each mutation. This ensures that error handling is consistent and implemented only once.

Finally, you can use the nodeFetcher in the resolver for the node query. In this case we don't pass an expected node type as the second argument to the fetch function.

type Query {
  node(id: ID!): Node
}
import { nodeDefinitions } from "graphql-relay";
import nodeFetcher from "./nodeFetcher";

const nodeDefinition = nodeDefinitions((globalId, context, info) => {
  return nodeFetcher.fetch(globalId);
});

API

This library exports the NodeHelper class.

Constructor

The constructor takes a Config object with the following properties:

type Config = {
  idFetcher: (resolvedId: ResolvedGlobalId) => any,
  fromGlobalId: (globalId: string) => ResolvedGlobalId,
  customError?: Class<Error>
};

type ResolvedGlobalId = {
  type: string,
  id: string
};
  • idFetcher: Responsible for fetching a node associated with a type and id.
  • fromGlobalId: Converts a globalId to a type and error (you would typically pass graphql-relay's default implementation but you can use your own).
  • customError: By default this library throws an instance of Error when an error occurs parsing the global id. However, some libraries (such as graphql-errors) introduce custom errors to distinguish between internal server errors and errors that need to be displayed to users of the API. Pass a custom error to allow for this use case.

fetch(globalId: String, expectedNodeType?: ?String): Promise

The fetch call retrieves the node associated with the globalId.

  • globalId: The global id of the node
  • expectedNodeType: Optional string representing the expected node type that must be fetched.