Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api-headless-cms): content entry traverser #4072

Merged
merged 5 commits into from
Apr 9, 2024

Conversation

Pavel910
Copy link
Collaborator

@Pavel910 Pavel910 commented Apr 5, 2024

Changes

This PR adds a utility to convert Content Model fields hierarchy into a traversable AST, and another utility, to traverse the content entry values.

One of the improvements to the codebase is splitting of the giant types.ts file into smaller, more focused, types files, for example: types/model.ts, types/modelField.ts, etc.

Example of Content Entry Traversal

// Get traverser instance.
const traverser = await context.cms.getEntryTraverser("article");

// Create a container for your custom output.
const output: Record<string, any> = {};

// We will skip values of the following field types.
const skipFieldTypes = ["object", "dynamicZone"];

// Traverse and create a flat object with value path as object key.
traverser.traverse(entry, ({ field, value, path }) => {
    /**
     * Most of the time you won't care about complex fields like "object" and "dynamicZone", but only their child fields.
     * The traverser will still go into the child fields, but this way you can conditionally apply your logic.
     */
    if (skipFieldTypes.includes(field.type)) {
        return;
    }

    output[path] = value;
});

expect(output).toEqual({
    title: "Article #1",
    body: richTextValue,
    categories: [{ modelId: "category", entryId: "12345678" }],
    "content.0.title": "Hero #1",
    "content.1.settings.title": "Title",
    "content.1.settings.seo.0.title": "title-0",
    "content.1.settings.seo.1.title": "title-1"
});

How Has This Been Tested?

Jest.

Documentation

TODO.

@Pavel910 Pavel910 added this to the 5.40.0 milestone Apr 5, 2024
@Pavel910 Pavel910 self-assigned this Apr 5, 2024
@Pavel910 Pavel910 marked this pull request as ready for review April 8, 2024 17:50
@Pavel910 Pavel910 changed the title feat(api-headless-cms): model to AST converter feat(api-headless-cms): content entry traverser Apr 8, 2024
@Pavel910 Pavel910 merged commit 5b01770 into next Apr 9, 2024
84 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant