Last active
May 7, 2019 21:48
-
-
Save taion/d161a58b9f7381d8fa9c to your computer and use it in GitHub Desktop.
Relay type registry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I was wondering what
getItem
is returning.I'm currently trying to incorporate Relay with React Native.