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-global-id-directive

v0.0.7

Published

graphql-global-id-directive is a package that includes a GlobalIdDirective class, which offers two directives: globalIdEncodeDirective and globalIdDecodeDirective. These directives handle the encoding and decoding of global IDs, making it a breeze to inte

Downloads

20

Readme

Graphql Global Id Directive

While transitioning to the use of global IDs (commonly known as node IDs), I found that encoding and decoding these IDs was a necessary step in various parts of my application, especially when using database IDs for queries and mutations. I sought a way to simplify this process by decoding the IDs before they reached the resolvers and encoding them on their way out. To address this, I created this package to make the use of global IDs straightforward and efficient. This package includes a GlobalIdDirective class, which offers two directives: globalIdEncodeDirective and globalIdDecodeDirective. These directives handle the encoding and decoding of global IDs, making the integration of global IDs into any GraphQL application a breeze.

Installation

npm install graphql-global-id-directive

Usage

First, import and create an instance of the GlobalIdDirective class:

import { GlobalIdDirective } from "graphql-global-id-directive";
const globalIdDirective = new GlobalIdDirective();

Define your schema

const typeDefs = `
  interface Node {
    id: ID!
  }

  type Query {
    user(id: ID! @decodeGlobalId): User
    node(id: ID! @decodeGlobalId(returnIdOnly: false)): Node
  }

  type User implements Node {
    id: ID! @encodeGlobalId(typeName: "User")
    name: String
    email: String
  }
`;

In the type definition of the node query, use the @decodeGlobalId directive with the returnIdOnly option set to false. This ensures that the stringified decoded global ID object is returned instead of just the underlying id which is the default behavior, allowing you to parse and use both the underlying id and __typename in your resolver.

Apply the directives to your schema

const { globalIdEncodeDirectiveTypeDefs, globalIdEncodeDirectiveTransformer } =
  globalIdDirective.globalIdEncodeDirective("encodeGlobalId"); // Use any name of your choice but avoid collisions with other directive names

const { globalIdDecodeDirectiveTypeDefs, globalIdDecodeDirectiveTransformer } =
  globalIdDirective.globalIdDecodeDirective("decodeGlobalId");

let schema = makeExecutableSchema({
  typeDefs: [
    typeDefs,
    globalIdEncodeDirectiveTypeDefs,
    globalIdDecodeDirectiveTypeDefs,
  ],
});

const directiveTransformers = [
  globalIdEncodeDirectiveTransformer,
  globalIdDecodeDirectiveTransformer,
];

schema = directiveTransformers.reduce(
  (currentSchema, transformer) => transformer(currentSchema),
  schema
);

Using GlobalIdDirective with Node Resolver

You can utilize the decoded global IDs in your node resolver to retrieve any instance of a node. Here's an example of how you can do this:

node: async (_, args, { dataSources }) => {
  // Parse the stringified ID back into an object
  const { id, __typename } = JSON.parse(args.id.toString());

  let node;
  switch (__typename) {
    case "User":
      node = await dataSources.userDb.getUser({ userId: id }); // Or fetch the user directly with the model. EG: UserModel.findById(id)
      break;
    case "Product":
      node = await dataSources.productDb.getProduct({ productId: id });
      break;
    case "Order":
      node = await dataSources.orderDb.getOrder({ orderId: id });
      break;
    // Add more cases as needed for other typenames
    default:
      throw new Error(`Unsupported typename: ${__typename}`); //Or perform another action
  }

  return { ...node.toObject({ virtuals: true }), __typename }; // I used a Mongoose document for this example
};

Customization

The GlobalIdDirective class is designed to be easily customizable. You can extend the class and override the encodeFn and decodeFn methods to provide your own implementation for encoding and decoding global IDs.

Here's an example of how you can do this:

class CustomGlobalIdDirective extends GlobalIdDirective {
  encodeFn(id, typeName) {
    // Your custom encoding logic here
  }

  decodeFn(globalId) {
    // Your custom decoding logic here
  }
}

const customGlobalIdDirective = new CustomGlobalIdDirective();

In this example, CustomGlobalIdDirective is a subclass of GlobalIdDirective. It overrides the encodeFn and decodeFn methods with custom logic for encoding and decoding global IDs.

Contributing

Want to make this package even better? Fork the repository and submit a pull request to contribute.

License

MIT License - see the LICENSE file for details.