Skip to content

Instantly share code, notes, and snippets.

@tibotiber
Created March 29, 2018 15:01
Show Gist options
  • Save tibotiber/df5f9867ed944e5fcc34227df48b1d11 to your computer and use it in GitHub Desktop.
Save tibotiber/df5f9867ed944e5fcc34227df48b1d11 to your computer and use it in GitHub Desktop.
const R = require('ramda')
const interfaces = {...}
const unpackSelectionFromAST = R.map(s => {
switch (s.kind) {
case 'Field':
if (!s.selectionSet) {
return s.name.value
} else {
return `${s.name.value} { ${unpackSelectionFromAST(
s.selectionSet.selections
)} }`
}
case 'InlineFragment':
switch (s.typeCondition.kind) {
case 'NamedType':
return R.compose(
R.map(field => `${R.toLower(s.typeCondition.name.value)}_${field}`),
R.reject(R.startsWith('__')), // apollo client compatibility (__typename)
unpackSelectionFromAST
)(s.selectionSet.selections)
default:
console.error(`${s.typeCondition.kind} unknown in selections AST`)
break
}
break
default:
console.error(`${s.kind} unknown in selections AST`)
break
}
})
const makeSelection = (info) =>
R.compose(
fields => `{ ${R.join(',')(fields)} }`,
R.reject(R.isNil),
R.flatten,
unpackSelectionFromAST,
R.prop('selections'),
R.prop('selectionSet'),
R.head,
R.prop('fieldNodes')
)(info)
const formatPrimitiveFields = R.map(
R.compose(
R.fromPairs,
R.map(([k, v]) => [R.replace(/^.*_/, '', k), v]),
R.toPairs
)
)
module.exports = { interfaces, makeSelection, formatPrimitiveFields }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment