Skip to content

Instantly share code, notes, and snippets.

@cahnory
Last active February 4, 2018 10:40
Show Gist options
  • Save cahnory/f0db5e7a691601aec990960108d3b059 to your computer and use it in GitHub Desktop.
Save cahnory/f0db5e7a691601aec990960108d3b059 to your computer and use it in GitHub Desktop.
Create relay node field
import { nodeDefinitions } from './nodeDefinitions.js';
const { nodeField, nodeFields, nodeInterface, defineNodeType } = nodeDefinitions();
export { nodeField, nodeFields, nodeInterface, defineNodeType };
import {
fromGlobalId as fromRelayId,
nodeDefinitions as relayNodeDefinitions,
} from 'graphql-relay';
const UNREGISTERED_NODE_TYPE = 'UNREGISTERED_NODE_TYPE';
export const nodeDefinitions = () => {
const definitions = {};
const { nodeInterface, nodeField, nodeFields } = relayNodeDefinitions(
(...args) => resolveNodeObject(definitions, ...args),
(...args) => resolveNodeType(definitions, ...args),
);
const defineNodeType = ({ type, resolve }) => {
definitions[type.name] = { type, resolve, ResolveType: () => {} };
};
return { nodeInterface, nodeField, nodeFields, defineNodeType };
};
export const resolveNodeObject = async (definitions, globalId, ...rest) => {
const { type: name, id } = fromRelayId(globalId);
if (!definitions[name]) {
throw new Error(UNREGISTERED_NODE_TYPE);
}
const { resolve, ResolveType } = definitions[name];
const obj = await resolve(id, ...rest);
return obj ? Object.assign(new ResolveType(), obj) : null;
};
export const resolveNodeType = (definitions, obj) => {
const definition = Object.values(definitions).find(
({ ResolveType }) => obj instanceof ResolveType,
);
if (!definition) {
throw new Error(UNREGISTERED_NODE_TYPE);
}
return definition.type;
};
import { GraphQLObjectType } from 'graphql';
import { globalIdField } from 'graphql-relay';
import { nodeInterface, defineNodeType } from './node';
import { findById } from '../models/User';
export const UserType = new GraphQLObjectType({
name: 'User',
fields: {
id: globalIdField('User')
},
interfaces: [nodeInterface],
});
export default UserType;
defineNodeType({
type: UserType,
resolve: findById,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment