Skip to content

Commit

Permalink
Add ability to resolve references within raw fields (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Feb 17, 2019
1 parent 66e41e7 commit 7b301e2
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 9 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,20 @@ Remember to use the GraphiQL interface to help write the queries you need - it's

Arrays and object types at the root of documents will get an additional "raw JSON" representation in a field called `_raw<FieldName>`. For instance, a field named `body` will be mapped to `_rawBody`. It's important to note that this is only done for top-level nodes (documents).

Quite often, you'll want to replace reference fields (eg `_ref: '<documentId>'`, or `someField___NODE: '<documentId>'`), with the actual document that is referenced. This is done automatically for regular fields, but within raw fields, you have to explicitly enable this behavior, by using the field-level `resolveReferences` argument:

```graphql
{
allSanityProject {
edges {
node {
_rawTasks(resolveReferences: {maxDepth: 5})
}
}
}
}
```

## Portable Text / Block Content

Rich text in Sanity is usually represented as [Portable Text](https://www.portabletext.org/) (previously known as "Block Content").
Expand Down
105 changes: 97 additions & 8 deletions src/gatsby-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@ import * as through from 'through2'
import {copy} from 'fs-extra'
import {camelCase} from 'lodash'
import {filter} from 'rxjs/operators'
import {GraphQLJSON, GraphQLFieldConfig} from 'gatsby/graphql'
import {
GraphQLJSON,
GraphQLFieldConfig,
GraphQLInt,
GraphQLInputObjectType,
GraphQLNonNull
} from 'gatsby/graphql'
import SanityClient = require('@sanity/client')
import {GatsbyContext, GatsbyReporter, GatsbyNode, GatsbyOnNodeTypeContext} from './types/gatsby'
import {SanityDocument} from './types/sanity'
import {pump} from './util/pump'
import {rejectOnApiError} from './util/rejectOnApiError'
import {processDocument} from './util/normalize'
import {processDocument, unprefixDraftId} from './util/normalize'
import {getDocumentStream} from './util/getDocumentStream'
import {getCacheKey, CACHE_KEYS} from './util/cache'
import {removeSystemDocuments} from './util/removeSystemDocuments'
Expand Down Expand Up @@ -164,6 +170,16 @@ export const onPreExtractQueries = async (context: GatsbyContext, pluginConfig:
await createTemporaryMockNodes(context, pluginConfig, stateCache)
}

const resolveReferencesConfig = new GraphQLInputObjectType({
name: 'SanityResolveReferencesConfiguration',
fields: {
maxDepth: {
type: new GraphQLNonNull(GraphQLInt),
description: 'Max depth to resolve references to'
}
}
})

export const setFieldsOnGraphQLNodeType = async (
context: GatsbyContext & GatsbyOnNodeTypeContext,
pluginConfig: PluginConfig
Expand Down Expand Up @@ -191,9 +207,15 @@ export const setFieldsOnGraphQLNodeType = async (
const aliasName = '_' + camelCase(`raw ${field.aliasFor}`)
acc[aliasName] = {
type: GraphQLJSON,
resolve: (obj: {[key: string]: {}}) => {
const raw = `_${camelCase(`raw_data_${field.aliasFor}`)}`
return obj[raw] || obj[fieldName] || obj[aliasFor]
args: {
resolveReferences: {type: resolveReferencesConfig}
},
resolve: (obj: {[key: string]: {}}, args) => {
const raw = `_${camelCase(`raw_data_${field.aliasFor || fieldName}`)}`
const value = obj[raw] || obj[fieldName] || obj[aliasFor]
return args.resolveReferences
? resolveReferences(value, 0, args.resolveReferences.maxDepth, context, pluginConfig)
: value
}
}
return acc
Expand All @@ -204,15 +226,82 @@ export const setFieldsOnGraphQLNodeType = async (
const aliasName = '_' + camelCase(`raw ${fieldName}`)
acc[aliasName] = {
type: GraphQLJSON,
resolve: (obj: {[key: string]: {}}) => {
const raw = `_${camelCase(`raw_data_${field.aliasFor}`)}`
return obj[raw] || obj[aliasName] || obj[fieldName]
args: {
resolveReferences: {type: resolveReferencesConfig}
},
resolve: (obj: {[key: string]: {}}, args) => {
const raw = `_${camelCase(`raw_data_${field.aliasFor || fieldName}`)}`
const value = obj[raw] || obj[aliasName] || obj[fieldName]
return args.resolveReferences
? resolveReferences(value, 0, args.resolveReferences.maxDepth, context, pluginConfig)
: value
}
}
return acc
}, fields)
}

function resolveReferences(
obj: any,
depth: number,
maxDepth: number,
context: GatsbyContext,
pluginConfig: PluginConfig
): any {
const {createNodeId, getNode} = context
const {overlayDrafts} = pluginConfig

if (Array.isArray(obj)) {
return depth <= maxDepth
? obj.map(item => resolveReferences(item, depth + 1, maxDepth, context, pluginConfig))
: obj
}

if (obj === null || typeof obj !== 'object') {
return obj
}

if (typeof obj._ref === 'string') {
const id = obj._ref
const node = getNode(createNodeId(overlayDrafts ? unprefixDraftId(id) : id))
return node && depth <= maxDepth
? resolveReferences(node, depth + 1, maxDepth, context, pluginConfig)
: obj
}

const initial: {[key: string]: any} = {}
return Object.keys(obj).reduce((acc, key) => {
const isGatsbyRef = key.endsWith('___NODE')
const isRawDataField = key.startsWith('_rawData')
let targetKey = isGatsbyRef && depth <= maxDepth ? key.slice(0, -7) : key

let value = obj[key]
if (isGatsbyRef && depth <= maxDepth) {
value = resolveGatsbyReference(obj[key], context)
}

value = resolveReferences(value, depth + 1, maxDepth, context, pluginConfig)

if (isRawDataField) {
targetKey = `_raw${key.slice(8)}`
}

acc[targetKey] = value
return acc
}, initial)
}

function resolveGatsbyReference(value: string | string[], context: GatsbyContext) {
const {getNode} = context
if (typeof value === 'string') {
return getNode(value)
} else if (Array.isArray(value)) {
return value.map(id => getNode(id))
} else {
throw new Error(`Unknown Gatsby node reference: ${value}`)
}
}

function validateConfig(config: PluginConfig, reporter: GatsbyReporter) {
if (!config.projectId) {
throw new Error('[sanity] `projectId` must be specified')
Expand Down
2 changes: 1 addition & 1 deletion src/util/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export function processDocument(doc: SanityDocument, options: ProcessingOptions)
}

// `drafts.foo-bar` => `foo.bar`
function unprefixDraftId(id: string) {
export function unprefixDraftId(id: string) {
return id.replace(/^drafts\./, '')
}

Expand Down

0 comments on commit 7b301e2

Please sign in to comment.