Travailler avec
Travailler avecBricks

Bricks

Nous pouvons modifier les données Bricks d'un post et les mettre à jour selon les besoins, en interrogeant, itérant, transformant et stockant le meta JSON Bricks de ce post.

Travailler avec Bricks. Regarder sur YouTube

Interroger les données Bricks

Interrogez le champ bricksData, qui retourne le JSON de tous les éléments du post Bricks.

query GetBricksData($customPostId: ID!) {
  customPost(by: { id: $customPostId }, status: any) {
    ...on BricksMaybeEnabledForCustomPostType {
      bricksData
    }
  }
}

La réponse ressemblera à ceci :

{
  "data": {
    "post": {
      "bricksData": [
        {
          "id": "oleqdy",
          "name": "section",
          "parent": 0,
          "children": [
            "uuiyqj"
          ],
          "settings": []
        },
        {
          "id": "uuiyqj",
          "name": "container",
          "parent": "oleqdy",
          "children": [
            "ejfwpo",
            "czivwt",
            "ucuzdk",
            "wzcyug",
            "ipoorm",
            "zvgqxx",
            "yrambp",
            "hywkos",
            "gdoiqo",
            "tyksto",
            "nquple",
            "typize",
            "fjiwqp"
          ],
          "settings": []
        },
        {
          "id": "ejfwpo",
          "name": "post-title",
          "parent": "uuiyqj",
          "children": [],
          "settings": {
            "tag": "h1"
          }
        },
        {
          "id": "czivwt",
          "name": "post-excerpt",
          "parent": "uuiyqj",
          "children": [],
          "settings": []
        },
        {
          "id": "hywkos",
          "name": "post-comments",
          "parent": "uuiyqj",
          "children": [],
          "settings": {
            "title": true,
            "avatar": true,
            "formTitle": true,
            "label": true,
            "submitButtonStyle": "primary"
          }
        },
        {
          "id": "yrambp",
          "name": "post-author",
          "parent": "uuiyqj",
          "children": [],
          "settings": {
            "avatar": true,
            "name": true,
            "website": true,
            "bio": true,
            "postsLink": true,
            "postsStyle": "primary"
          }
        },
        {
          "id": "zvgqxx",
          "name": "related-posts",
          "parent": "uuiyqj",
          "children": [],
          "settings": {
            "taxonomies": [
              "category",
              "post_tag"
            ],
            "content": [
              {
                "dynamicData": "{post_title:link}",
                "tag": "h3",
                "dynamicMargin": {
                  "top": 10
                },
                "id": "a667d0"
              },
              {
                "dynamicData": "{post_date}",
                "id": "5bb1b2"
              },
              {
                "dynamicData": "{post_excerpt:20}",
                "dynamicMargin": {
                  "top": 10
                },
                "id": "80e288"
              }
            ]
          }
        }
      ]
    }
  }
}

Nous pouvons également filtrer les éléments par nom via le paramètre filterBy (qui accepte include et exclude).

En exécutant cette requête :

query GetBricksData($customPostId: ID!) {
  customPost(by: { id: $customPostId }, status: any) {
    ...on BricksMaybeEnabledForCustomPostType {
      bricksData(filterBy: {
        include: [
          "post-comments",
          "post-author"
        ]
      })
    }
  }
}

...cela produira cette réponse :

{
  "data": {
    "post": {
      "bricksData": [
        {
          "id": "hywkos",
          "name": "post-comments",
          "parent": "uuiyqj",
          "children": [],
          "settings": {
            "title": true,
            "avatar": true,
            "formTitle": true,
            "label": true,
            "submitButtonStyle": "primary"
          }
        },
        {
          "id": "yrambp",
          "name": "post-author",
          "parent": "uuiyqj",
          "children": [],
          "settings": {
            "avatar": true,
            "name": true,
            "website": true,
            "bio": true,
            "postsLink": true,
            "postsStyle": "primary"
          }
        }
      ]
    }
  }
}

Vous pouvez remplacer n'importe quel composant global Bricks par les éléments Bricks correspondants, en passant le paramètre replaceComponents: true :

{
  post(by: { id: 1 }) {
    bricksData(replaceComponents: true)
  }
}

Pour interroger les composants Bricks, utilisez le champ bricksComponents, qui retourne le JSON de tous les composants (tels qu'ils sont stockés sous l'option bricks_components dans la BDD).

{
  bricksComponents
}

La réponse ressemblera à ceci :

{
  "data": {
    "bricksComponents": [
      {
        "id": "flgizw",
        "category": "",
        "desc": "",
        "elements": [
          {
            "id": "flgizw",
            "name": "container",
            "settings": {
              "_padding": {
                "right": 50
              },
              "_padding:mobile_landscape": {
                "right": "0"
              },
              "_alignItems:mobile_portrait": "center",
              "_width:tablet_portrait": "100%",
              "_padding:tablet_portrait": {
                "right": "0"
              },
              "_margin:tablet_portrait": {
                "bottom": "60"
              },
              "_margin:mobile_portrait": {
                "bottom": "30"
              }
            },
            "children": [
              "9029cb",
              "9a5e42"
            ],
            "parent": 0,
            "label": "Text Component"
          },
          {
            "id": "9029cb",
            "name": "heading",
            "settings": {
              "text": "Exceptional Furniture for Every Residence",
              "tag": "h2",
              "_typography:mobile_portrait": {
                "text-align": "center"
              }
            },
            "children": [],
            "parent": "flgizw"
          },
          {
            "id": "9a5e42",
            "name": "text",
            "settings": {
              "text": "Explore our vast selection of high-quality furniture crafted to elevate the ambiance of every room in your residence. From cozy sofas and sophisticated dining tables to practical storage options, our offerings blend style, durability, and value. Each piece is thoughtfully chosen to uphold the highest quality standards while accommodating diverse budgets and design tastes.",
              "_margin": {
                "top": "25"
              },
              "_typography:mobile_portrait": {
                "text-align": "center"
              }
            },
            "children": [],
            "parent": "flgizw"
          }
        ],
        "properties": [],
        "_created": 1750821473,
        "_user_id": 1,
        "_version": "2.0-beta"
      }
    ]
  }
}

Vous pouvez également filtrer les composants Bricks par leurs ID : bricksComponents(filter: {ids: ["flgizw"]}).

Modifier et stocker les données Bricks

Itérez les éléments du JSON produit par bricksData, modifiez-les selon les besoins, et stockez le JSON modifié dans le meta du post, via l'une de ces mutations :

  • bricksSetCustomPostElementData
  • bricksMergeCustomPostElementDataItem

Utiliser bricksSetCustomPostElementData

Après avoir modifié les éléments, exportez l'intégralité du JSON modifié sous une variable dynamique (pour l'injecter dans la mutation).

Par exemple, cette requête transformera tous les éléments heading du JSON en majuscules, et exportera le JSON modifié (sous la variable dynamique $modifiedBricksData) :

query GetAndModifyBricksData($customPostId: ID!) {
  customPost(by: { id: $customPostId }, status: any) {
    ...on BricksMaybeEnabledForCustomPostType {
      bricksData
        @underEachArrayItem(
          passValueOnwardsAs: "elementJSON"
          affectDirectivesUnderPos: [1, 2, 3]
        )
          @applyField(
            name: "_objectProperty",
            arguments: {
              object: $elementJSON,
              by: { key: "name" }
              failIfNonExistingKeyOrPath: false,
            },
            passOnwardsAs: "elementName"
          )
          @applyField(
            name: "_equals",
            arguments: {
              value1: $elementName,
              value2: "heading"
            },
            passOnwardsAs: "isMatch"
          )
          @if(condition: $isMatch)
            @underJSONObjectProperty(
              by: { path: "settings.text" }
              failIfNonExistingKeyOrPath: false
            )
              @strUpperCase
        @export(as: "modifiedBricksData")
    }
  }
}

Notez que le JSON contiendra tous les éléments, y compris ceux qui n'ont pas été modifiés.

Ensuite, utilisez la mutation bricksSetCustomPostElementData pour stocker le JSON modifié dans le meta du post :

mutation StoreBricksData($customPostId: ID!)
  @depends(on: "GetAndModifyBricksData")
{
  bricksSetCustomPostElementData(input: {
    customPostID: $customPostId
    data: $modifiedBricksData
  }) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        id
        bricksData
      }
    }
  }
}

Utiliser bricksMergeCustomPostElementDataItem

Alternativement, vous pouvez exporter uniquement les éléments modifiés.

Dans cette requête, nous filtrons les éléments par nom, et exportons les headings modifiés (sous la variable dynamique $modifiedBricksHeadings) ainsi que leurs ID (sous la variable dynamique $modifiedBricksHeadingIDs) :

query GetAndModifyBricksData($customPostId: ID!) {
  customPost(by: { id: $customPostId }, status: any) {
    ...on BricksMaybeEnabledForCustomPostType {
      bricksData(filterBy: {include: ["heading"]})
        @underEachArrayItem(affectDirectivesUnderPos: [1, 3])
          @underJSONObjectProperty(by: { key: "id" })
            @export(as: "modifiedBricksHeadingIDs")
          @underJSONObjectProperty(
            by: { path: "settings.text" }
            failIfNonExistingKeyOrPath: false
            affectDirectivesUnderPos: [1, 2]
          )
            @strUpperCase
            @export(as: "modifiedBricksHeadings")
    }
  }
}

Ensuite, utilisez la mutation bricksMergeCustomPostElementDataItem pour fusionner ces entrées dans le JSON meta du post.

Pour ce faire, vous devez d'abord générer l'input à injecter dans la mutation, sous forme de tableau avec l'ID et les paramètres de chaque élément modifié :

query GenerateBricksMergeDataItemInputs
  @depends(on: "GetAndModifyBricksData")
{
  bricksMergeDataItemInputs: _echo(value: $modifiedBricksHeadingIDs)
    @underEachArrayItem(
      passIndexOnwardsAs: "index",
      passValueOnwardsAs: "id"
      affectDirectivesUnderPos: [1, 2]
    )
      @applyField(
        name: "_arrayItem",
        arguments: {
          array: $modifiedBricksHeadings,
          position: $index
        },
        passOnwardsAs: "heading"
      )
      @applyField(
        name: "_echo",
        arguments: {
          value: {
            id: $id,
            settings: {
              text: $heading
            }
          }
        }
        setResultInResponse: true
      )
    @export(as: "bricksMergeDataItemInputs")
}
 
mutation StoreBricksData($customPostId: ID!)
  @depends(on: "GenerateBricksMergeDataItemInputs")
{
  bricksMergeCustomPostElementDataItem(input: {
    customPostID: $customPostId
    elements: $bricksMergeDataItemInputs
  }) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        id
        bricksData
      }
    }
  }
}