gridsome icon indicating copy to clipboard operation
gridsome copied to clipboard

@gridsome/source-contentful - handle cyclic references when using JSON.stringify() on Rich Text

Open jacobsteenstenersen opened this issue 3 years ago • 1 comments

Summary

Currently, the gridsome build/develop scripts will throw errors and exit when encountering an object with circular references passed to JSON.stringify(). This is normal functioning for JSON.stringify().

Contentful allows for content with references. These references can cause cyclic errors such as a content item referencing itself.

I've attached a PR adds some extra error handling to the Gridsome contentful plugin to deal with cyclic errors. This PR contains a changed code snippet which will 'decycle' an object which can then be passed to JSON.stringify(). The code that the code snippet is based on is Public Domain.

Basic example

const foo = { beta: 'beta'}
foo.check = foo // this is a circular reference
JSON.stringify(foo)

Throws TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' --- property 'check' closes the circle at JSON.stringify (<anonymous>)

If we take the above example, and use the decycle() in the attached PR, we get this: {"beta":"beta","check":{"$ref":"$"}}. Although there is a data loss/change, this is acceptable as gridsome processes would exit before.

Motivation

Contentful allows for references that can cause cyclic errors. A basic example is 2 blog posts that reference each other. This is functionality supported by Contentful, and should be supported by @gridsome/source-contentful

jacobsteenstenersen avatar Jan 18 '22 08:01 jacobsteenstenersen

Thanks for the fix ! It works on my side and it is indeed a important fix when the rich-text field is in use.

felixdenoix avatar Feb 17 '22 15:02 felixdenoix