Skip to content

Instantly share code, notes, and snippets.

@taion
Last active May 7, 2019 21:48
Show Gist options
  • Save taion/d161a58b9f7381d8fa9c to your computer and use it in GitHub Desktop.
Save taion/d161a58b9f7381d8fa9c to your computer and use it in GitHub Desktop.
Relay type registry
import decamelize from 'decamelize';
import { fromGlobalId } from 'graphql-relay';
import pluralize from 'pluralize';
import getItem from '../api/getItem';
const types = {};
const endpoints = {};
const getItemOverrides = {};
export function getEndpoint(type) {
return endpoints[type];
}
function getDefaultEndpoint(type) {
const endpoint = pluralize(decamelize(type.name));
return id => id ? `${endpoint}/${id}` : endpoint;
}
export function registerType(type, endpoint, getItemOverride) {
types[type.name] = type;
endpoints[type] = endpoint || getDefaultEndpoint(type);
getItemOverrides[type] = getItemOverride;
// Allow e.g. `export default registerType(MyType);`.
return type;
}
export async function idFetcher(globalId, info) {
const { type, id } = fromGlobalId(globalId);
const getItemOverride = getItemOverrides[type];
let item;
if (getItemOverride) {
item = await getItemOverride(id, info);
} else {
item = await getItem(getEndpoint(type), id, info);
}
return { type, ...item };
}
export function typeResolver(obj) {
return types[obj.type];
}
@Naoto-Ida
Copy link

Hi, I was wondering what getItem is returning.
I'm currently trying to incorporate Relay with React Native.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment