Skip to content

Commit

Permalink
introduce renderRichText function
Browse files Browse the repository at this point in the history
  • Loading branch information
axe312ger committed Jun 19, 2020
1 parent cce9c6b commit e432498
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
5 changes: 1 addition & 4 deletions packages/gatsby-source-contentful/src/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ const fixId = id => {
if (!_.isString(id)) {
id = id.toString()
}
if (!isNaN(id.slice(0, 1))) {
return `c${id}`
}
return id
return `c${id}`
}
exports.fixId = fixId

Expand Down
47 changes: 47 additions & 0 deletions packages/gatsby-source-contentful/src/rich-text.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
// import { fixId } from "./normalize"
import { documentToReactComponents } from "@contentful/rich-text-react-renderer"
import resolveResponse from "contentful-resolve-response"

const _ = require(`lodash`)
const { BLOCKS, INLINES } = require(`@contentful/rich-text-types`)

Expand Down Expand Up @@ -182,3 +186,46 @@ const getNormalizedRichTextField = ({
}

exports.getNormalizedRichTextField = getNormalizedRichTextField

// Copied for now as normalize.js has node dependencies. Will move it to a separate file later.
const fixId = id => {
if (!_.isString(id)) {
id = id.toString()
}
return `c${id}`
}

function renderRichText({ raw, references }, options = {}) {
const richText = JSON.parse(raw)

// If no references are given, there is no need to resolve them
if (!references) {
return documentToReactComponents(richText, options)
}

// Create dummy response so we can use official libraries for resolving the entries
const dummyResponse = {
items: [
{
sys: { type: `Entry` },
richText,
},
],
includes: {
Entry: references.map(reference => {
return {
...reference,
sys: { type: `Entry`, id: fixId(reference.contentful_id) },
}
}),
},
}

const resolved = resolveResponse(dummyResponse, {
removeUnresolved: true,
})

return documentToReactComponents(resolved[0].richText, options)
}

exports.renderRichText = renderRichText

0 comments on commit e432498

Please sign in to comment.