cultofcoders:grapher-schema-directives

v0.1.0Published 7 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

Grapher and GraphQL Schema Directives

Wouldn't it be sweet if we could setup our collections and links in our GraphQL type definitions?

Yes, it would be very sweet.

Install

meteor add cultofcoders:grapher-schema-directives

Sample

1type User @mongo(name: "users") {
2    comments: [Comment] @link(to: "user")
3}
4
5type Comment @mongo(name: "comments") {
6   user: User @link(field: "userId")
7   post: Post @link(field: "commentId")
8   createdAt: Date @map("created_at")
9}
10
11type Post @mongo(name: "posts") {
12    comments: [Comment] @link(to="post")
13}

In the background, the schema directives analyze our types and create propper links, when we have a field present, that's going to be a main link, that's the collection we are going to store it in, when we have to present, that's going to be an inversed link.

Each ObjectType needs to have the propper @mongo directive to work.

The @map directive makes a database field be aliased. The reason for this is that when we query with Grapher's GraphQL abilities to properly adapt that field to the correspondant db field. In the backscene, we basically have a reducer.

Usage

1import {
2  directives, // the full map of the directive, as mentioned in the sample above
3  directiveDefinitions, // the definitions
4  MapToDirective, // the actual directive classes
5  LinkDirective,
6  MongoDirective,
7} from 'meteor/cultofcoders:grapher-schema-directives';
8
9// Add them to your graphql servers

If you are using cultofcoders:apollo package:

1import { load } from 'graphql-load';
2import { Config } from 'meteor/cultofcoders:apollo';
3import {
4  directives,
5  directiveDefinitions,
6} from 'meteor/cultofcoders:grapher-schema-directives';
7
8load({ typeDefs: directiveDefinitions });
9
10Config.GRAPHQL_SCHEMA_DIRECTIVES = {
11  ...directives,
12};

Another quick trick you could use:

1import { db } from 'meteor/cultofcoders:grapher';
2import { Config } from 'meteor/cultofcoders:apollo';
3
4Object.assign(Config.CONTEXT, { db });

Which basically allows you to do:

1export default {
2  Query: {
3    users(_, args, context, ast) {
4      // Where db.`mongoCollectionName`
5      return context.db.users.astToQuery(ast).fetch();
6    },
7  },
8};