prismicio/prismic-richtext

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-prismiccode 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

function asText(richtext: RichTextBlock[], joinString: string | null | undefined) {
const join = typeof joinString === 'string' ? joinString : ' ';
return richtext.map(block => block.text).join(join);
}

I came to this through prismic-reactjs, which has no type definitions to prevent this kind of thing through typechecking.

lihbr commented

@angeloashmore can you close if fixed now?

lihbr commented

Got fixed actually 🚀