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

global-relay-id-mongoose

v1.0.1

Published

Mongoose helpers to add relay compatible object identification to your GraphQL Schema.

Downloads

5

Readme

global-relay-id-mongoose

Mongoose helpers to add relay compatible object identification to your GraphQL Schema.

What

The two core assumptions that Relay makes about a GraphQL server are that it provides:

  1. A mechanism for refetching an object.
  2. A description of how to page through connections.

This library achieves number 1 with mongoose (looking for how to achieve number 2 with mongoose? Check out my other library: mongoose-relay-paginate.)

The number 1 part of the above is known in the relay docs as Object Identification.

Object Identification involves sending identifiers about any collection to the client and being able to refetch them using a single endpoint. This library provides such a way to send an identifier which is globally unique across your schemas and which may be refetched using this library.

⚠️ WARNING ⚠️ It also creates a dataloader to load the node from, so do remember to create a new context per request by calling the default exported function atleast once per request or you could get data meant for one user sent to another.

Why

Object identification in relay allows you to refetch a given node from your server. If you are using relay-client this is useful, because it will help relay to have simple caching object lookups for updating UI.

How

Simple example:

import GlobalRelayIdMongoose from "global-relay-id-mongoose";
// WARNING!!! Make sure to create a handler once for every seperate request since it has a dataloader!!!!!! 
// Otherwise you could get data meant for one user sent to another...
const handler = GlobalRelayIdMongoose([UserModel]);
const user = await UserModel.findOne({});
if (!user?._id) throw new Error("No _id!");

// This should happen on the server to send a response to the client
const id = handler.toID(UserModel, user._id);
// This should happen on the server when getting a request from the client with the identifier.
const node = await handler.node(id);

expect(node).toStrictEqual(user);

TypeGraphQL example

The below examples uses type-graphql. TypeGraphQL is not required, but it is my preferred graphql implementation. Feel free to contribute to this readme to add your graphql implementation.

Here's our resolver this returns the ID identifier. We have to set this up for each Node that implements our node interface:

@Resolver(_type => Recipe)
export class RecipeResolver {
	@FieldResolver(_type => ID, {
		description:
			"This field brings relay's node interface to our schema, and it acts as the id for our schema!",
	})
	id(
		@Root() root: Recipe,
    // The library is sent in via context on the `node` prop.
		@Ctx() { db, node }: MyContext
	): string {
    // notice the use of the library here since this is the 
    // ID field resolver we will send back the globally unique ID.
		return node.toID(db.models.Recipe, root._id);
	}
}

Then we make the node's queryable through a node query with the identifier as an argument:

@ArgsType()
export class NodeArgs {
	@Field(() => CustomScalars.ID)
	id!: IDInput;
}

@Resolver(_type => NodeInterface)
export class NodeResolver {
	@Query(_type => NodeInterface, {
		description: "This field queries any given node in our schema!",
	})
	node(
		@MyRoot() root: NodeInterface,
		@Args() { id }: NodeArgs,
		@Ctx() { node }: MyContext
	) {
		return node.node(id);
	}
}

Finally we setup our context:

import GlobalRelayIdMongoose, {MongooseGlobalIDReturn} from "global-relay-id-mongoose";

const db = {
  models: {
    // A mongoose model
    Recipe: RecipeModel
  }
} as const;


interface MyContext {
  db: typeof db;
  node: MongooseGlobalIDReturn<(typeof db)["models"][string]>;
}


const schema = new ApolloServer({
  schema: await buildSchema({
    resolvers: [RecipeResolver, NodeResolver],
  }),
  context (context): MyContext {
    return {
      db,
      // Using this libraries primary default export 
      node: GlobalRelayIdMongoose(Object.values(db.models)),
      // etc...
    }
  },
});