graphbrainz/src/util.js

51 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-08-20 05:59:32 +00:00
import util from 'util'
export const ONE_DAY = 24 * 60 * 60 * 1000
export function getFields(info, fragments = info.fragments) {
2016-08-20 05:59:32 +00:00
if (info.kind !== 'Field') {
2016-11-26 01:38:32 +00:00
info = info.fieldNodes[0]
2016-08-20 05:59:32 +00:00
}
const selections = info.selectionSet.selections
2016-11-30 07:53:01 +00:00
const reducer = (fields, selection) => {
if (selection.kind === 'FragmentSpread') {
const name = selection.name.value
const fragment = fragments[name]
if (!fragment) {
throw new Error(`Fragment '${name}' was not passed to getFields()`)
}
fragment.selectionSet.selections.reduce(reducer, fields)
} else if (selection.kind === 'InlineFragment') {
selection.selectionSet.selections.reduce(reducer, fields)
2016-11-30 07:53:01 +00:00
} else {
fields[selection.name.value] = selection
}
2016-08-08 07:54:06 +00:00
return fields
2016-11-30 07:53:01 +00:00
}
return selections.reduce(reducer, {})
2016-08-08 07:54:06 +00:00
}
2016-08-20 05:59:32 +00:00
export function prettyPrint(
obj,
{ depth = 5, colors = true, breakLength = 120 } = {}
) {
2016-08-20 05:59:32 +00:00
console.log(util.inspect(obj, { depth, colors, breakLength }))
}
export function toFilteredArray(obj) {
2016-08-20 05:59:32 +00:00
return (Array.isArray(obj) ? obj : [obj]).filter(x => x)
}
export function extendIncludes(includes, moreIncludes) {
2016-08-20 05:59:32 +00:00
includes = toFilteredArray(includes)
moreIncludes = toFilteredArray(moreIncludes)
const seen = {}
return includes.concat(moreIncludes).filter(x => {
if (seen[x]) {
return false
}
seen[x] = true
return true
})
}