Use null-safe access in processTextBlock
Closed this issue · 4 comments
I am using Gatsby along with gatsby-source-prismic
to import my Prismic repository data into a static site. Gatsby processes the JSON from Prismic into a GraphQL API.
Everything works well, except when a RichText field contains no spans (i.e. no special formatting). GraphQL removes any empty properties/arrays, so Array.prototype.map
on undefined
or null
throws an error.
When processing a RichTextBlock
in processTextBlock
, Array.prototype.map
is called on block.spans
to process the spans data. In my case, block.spans
could potentially be undefined
or null
.
The line in question is here: https://github.com/prismicio/prismic-richtext/blob/master/src/tree.ts#L163
Could the function instead be something like the following?
function processTextBlock(block: RichTextBlock): SpanNode[] {
+ const nodes = (block.spans || []).map((span) => {
const text = block.text.slice(span.start, span.end);
return new SpanNode(span.start, span.end, span.type, text, [], span);
});
const boundaries = { lower: 0, upper: block.text.length };
return buildTreeAndFill(block.text, nodes, boundaries);
}
Hi @angeloashmore,
I see you're the gatsby-source-prismic
's creator. Could you show me where you lose the spans
in the gatsby-source-prismic
code so I can fully understand your issue?
Not totally sure if this is relevant, but I see a similar issue in asText
, rich text can be returned as null, and it errors out.
query {
allArticles{
edges {
node {
summary
}
}
}
}
Can return
{
"data": {
"allArticles": {
"edges": [
{
"node": {
"summary": null
}
},
...
asText assumes not null
prismic-richtext/src/astext.ts
Lines 3 to 6 in 2839277
I came to this through prismic-reactjs
, which has no type definitions to prevent this kind of thing through typechecking.
@angeloashmore can you close if fixed now?
Got fixed actually 🚀