# global-relay-id-mongoose

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

Latest version **1.0.1** (published 2023-03-04) · MIT license · 0 weekly downloads

## Install

```sh
npm install global-relay-id-mongoose
pnpm add global-relay-id-mongoose
yarn add global-relay-id-mongoose
bun add global-relay-id-mongoose
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.1 |
| Published | 2023-03-04 |
| First published | 2023-03-04 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 11.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Maintainers | johnsonjo4531 |
| Keywords | global, object, identifier, relay, mongoose |

## Links

- npm: https://www.npmjs.com/package/global-relay-id-mongoose
- Repository: https://github.com/johnsonjo4531/global-relay-id-mongoose
- Issues: https://github.com/johnsonjo4531/global-relay-id-mongoose/issues
- npm.io page: https://npm.io/package/global-relay-id-mongoose

## Dependencies (1)

- [dataloader](https://npm.io/package/dataloader.md) ^2.2.2

## Alternatives

- [angular-pipes](https://npm.io/package/angular-pipes.md) — 5.6K weekly downloads
- [@ng-web-apis/midi](https://npm.io/package/@ng-web-apis/midi.md) — 2.6K weekly downloads
- [happn-3](https://npm.io/package/happn-3.md) — 1.6K weekly downloads
- [@opensip-cli/lang-go](https://npm.io/package/@opensip-cli/lang-go.md) — 1.2K weekly downloads
- [mongoose-typescript](https://npm.io/package/mongoose-typescript.md) — 85 weekly downloads

## Recent versions

- 1.0.1 (latest) — 2023-03-04
- 1.0.0 — 2023-03-04

## 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.
> - [GraphQL Relay Server Specification Docs](https://relay.dev/docs/guides/graphql-server-specification/)

This library achieves number 1 with mongoose (looking for how to achieve number 2 with mongoose? Check out my other library: [mongoose-relay-paginate](https://www.npmjs.com/package/mongoose-relay-paginate).)

The number 1 part of the above is known in the relay docs as [Object Identification](https://relay.dev/docs/guides/graphql-server-specification/#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:

```ts
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:


```ts
@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:

```ts
@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:

```ts
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...
    }
  },
});
```

---
_Source: https://npm.io/package/global-relay-id-mongoose · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
