Add an option to avoid circular references in the object returned by `getEntries()`
See original GitHub issueCurrently I’m loading page’s data (from Contentful) in a next.js getStaticProps
function. After that, I’m returning that data as a prop to my react page component.
However, getStaticProps
function must not return JSON with circular references. If you do that, you end up with “circular references cannot be expressed in JSON” error.
To go around it I had to call .stringifySafe()
on the entries and then parse that stringified string, so I could end up with the same JSON object, but without the circular references in it:
function removeEntryCollectionCircularReferences<T>(
entries: EntryCollection<T>
): EntryCollection<T> {
return JSON.parse(entries.stringifySafe()) as typeof entries;
}
export const getStaticProps: GetStaticProps = async context => {
const pages = await contentfulClient.getEntries<IPageFields>({
content_type: 'page',
'fields.urlSlug': context.params.id
});
const page = removeEntryCollectionCircularReferences(pages).items[0];
return { props: { page } };
};
However it is not ideal, as I’m stringifying and then parsing that whole JSON needlessly, also it requires me to have that util function. (I suspect more people will end up with similar problem soon.)
Ideally, maybe we could tell the Contentful Client not to fully serialize the linked entry, if it has been already included in the tree above it? It could be configured with a resolveCircularReferences: boolean
option passed to the client or getEntries()
method.
What do you think?
Environment
- contentful.js 7.14.0
- next 9.3.0
Issue Analytics
- State:
- Created 4 years ago
- Reactions:14
- Comments:16 (1 by maintainers)
Top GitHub Comments
After checking who was responsible for transforming the result, I found it to be : contentful-resolve-response.
Maybe that package should accept an option to go deep until a certain level.
In most cases, that deep level is the
include
parameter value. Although an option likeresolveLinksDepth
could be very useful to avoid circular references from a certain point.Thank you @maapteh for providing your solution. I’m closing this issue for now since it seems that there are solutions and/or workarounds for this issue given in the thread. If anything pops up again we can definitely open it up again.