Biblioteca de queries
Biblioteca de queriesSincronizar post entre sites

Sincronizar post entre sites

Esta query é demonstrada na demo Sincronizando um post entre 2 sites, incluindo metadados do Meta Box (e também do Slim SEO).

Esta query sincroniza um post de um site WordPress para outro, incluindo metadados.

Ela realiza as seguintes operações:

  1. Busca um post e todos os seus metadados do site de origem
  2. Cria um novo post ou atualiza um post existente no site de destino, copiando os dados do post e os metadados do site de origem

Esta query requer:

  • Gato GraphQL + extensões PRO no site de origem
  • Plugin Gato GraphQL gratuito no site de destino
  • Nested Mutations habilitadas no endpoint do site de destino

As variáveis necessárias são:

  • postType: O tipo de post personalizado do post a sincronizar entre os sites
  • postSlug: O slug do post a sincronizar entre os sites
  • downstreamServerGraphQLEndpointURL: A URL do endpoint GraphQL do site WordPress de destino
  • username: O nome de usuário da senha de aplicação para autenticação no site de destino
  • appPassword: A senha da senha de aplicação para autenticação no site de destino
  • update: Se deve atualizar um post existente (true) ou criar um novo (false)

Se estiver atualizando o post, o identificador comum entre os sites upstream e downstream é o slug do post.

A query GraphQL deve ser executada no site de origem.

query CheckHasCustomPost($postSlug: String!, $postType: String! = post)
{
  customPost(by: { slug: $postSlug }, status: any, customPostTypes: [$postType])
    @fail(
      message: "There is no post in the upstream site with the provided slug"
      data: {
        slug: $postSlug
      }
    )
  {
    rawTitle
      @export(as: "postTitle")
    rawContent
      @export(as: "postContent")
    rawExcerpt
      @export(as: "postExcerpt")
 
    metaKeys(filter: { exclude: [
      "_thumbnail_id",
      "_edit_last",
    ] })
    meta(keys: $__metaKeys) 
      @export(as: "postMeta")
  }
 
  isMissingPostInUpstream: _isNull(value: $__customPost)
    @export(as: "isMissingPostInUpstream")
}
 
query ExportCreateCustomPostOnTargetSiteGraphQLQuery(
  $update: Boolean! = false
)
  @depends(on: "CheckHasCustomPost")
  @skip(if: $isMissingPostInUpstream)
  @skip(if: $update)
{
  query: _echo(value: """
 
mutation CreateCustomPost(
  $postType: String! = post
  $postSlug: String!
  $postTitle: String!
  $postExcerpt: String!
  $postContent: String!
  $postMeta: NullableListValueJSONObject!
) {
  createCustomPost(input: {
    customPostType: $postType
    title: $postTitle,
    excerpt: $postExcerpt,
    slug: $postSlug,
    contentAs: { html: $postContent },
    status: draft,
    meta: $postMeta,
  }) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        customPostType
        title
        excerpt
        slug
        content
        status
      }
    }
  }
}
 
    """
  )
    @export(as: "query")
    @remove
}
 
query ExportUpdateCustomPostOnTargetSiteGraphQLQuery(
  $update: Boolean! = false
)
  @depends(on: "CheckHasCustomPost")
  @skip(if: $isMissingPostInUpstream)
  @include(if: $update)
{
  query: _echo(value: """
 
mutation UpdateCustomPost(
  $postType: String! = post
  $postSlug: String!
  $postTitle: String!
  $postContent: String!
  $postExcerpt: String!
  $postMeta: NullableListValueJSONObject!
) {
  customPost(by: { slug: $postSlug }, status: any, customPostTypes: [$postType]) {
    update(input: {
      title: $postTitle,
      excerpt: $postExcerpt,
      contentAs: { html: $postContent },
      meta: $postMeta,
    }) {
      status
      errors {
        __typename
        ...on ErrorPayload {
          message
        }
      }
      customPost {
        __typename
        ...on CustomPost {
          customPostType
          title
          excerpt
          slug
          content
          status
        }
      }
    }
  }
}
 
    """
  )
    @export(as: "query")
    @remove
}
 
query CreateOrUpdateCustomPostOnTargetSite(
  $downstreamServerGraphQLEndpointURL: String!
  $postSlug: String!
  $username: String!
  $appPassword: String!
  $postType: String! = post
)
  @depends(on: [
    "ExportCreateCustomPostOnTargetSiteGraphQLQuery",
    "ExportUpdateCustomPostOnTargetSiteGraphQLQuery",
  ])
  @skip(if: $isMissingPostInUpstream)
{
  loginCredentials: _sprintf(
    string: "%s:%s",
    values: [$username, $appPassword]
  )
    @remove
 
  base64EncodedLoginCredentials: _strBase64Encode(
    string: $__loginCredentials
  )
    @remove
 
  loginCredentialsHeaderValue: _sprintf(
    string: "Basic %s",
    values: [$__base64EncodedLoginCredentials]
  )
    @remove
 
  _sendGraphQLHTTPRequest(
    input: {
      endpoint: $downstreamServerGraphQLEndpointURL,
      query: $query,
      variables: [
        {
          name: "postSlug",
          value: $postSlug
        },
        {
          name: "postTitle",
          value: $postTitle
        },
        {
          name: "postContent",
          value: $postContent
        },
        {
          name: "postExcerpt",
          value: $postExcerpt
        },
        {
          name: "postMeta",
          value: $postMeta
        },
        {
          name: "postType",
          value: $postType
        }
      ],
      options: {
        headers: [
          {
            name: "Authorization",
            value: $__loginCredentialsHeaderValue
          }
        ]
      }
    }
  )
}

As variáveis seriam assim:

{
  "postType": "post",
  "postSlug": "hello-world",
  "downstreamServerGraphQLEndpointURL": "https://target-site.com/graphql",
  "update": false,
  "username": "admin",
  "appPassword": "{ application password, eg: cNEp BVPy QVxF eVqH lggt BTb4 }"
}