UNPKG

graphql-typed-client

Version:

A tool that generates a strongly typed client library for any GraphQL endpoint. The client allows writing GraphQL queries as plain JS objects (with type safety, awesome code completion experience, custom scalar type mapping, type guards and more)

41 lines (29 loc) 1.11 kB
import { LinkedField, LinkedType } from './linkTypeMap' import { startsWith } from 'lodash' export const getFieldFromPath = (root: LinkedType | undefined, path: string[]) => { let current: LinkedField | undefined if (!root) throw new Error('root type is not provided') if (path.length === 0) throw new Error(`path is empty`) path.forEach(f => { const type = current ? current.type : root if (!type.fields) throw new Error(`type \`${type.name}\` does not have fields`) const possibleTypes = Object.keys(type.fields) .filter(i => startsWith(i, 'on_')) .reduce( (types, fieldName) => { const field = type.fields && type.fields[fieldName] if (field) types.push(field.type) return types }, [type], ) let field: LinkedField | null = null possibleTypes.forEach(type => { const found = type.fields && type.fields[f] if (found) field = found }) if (!field) throw new Error(`type \`${type.name}\` does not have a field \`${f}\``) current = field }) return <LinkedField>current }