Biblioteca de queries
Biblioteca de queriesSincronizar post entre sitios

Sincronizar post entre sitios

Esta consulta se demuestra en la demo Sincronizando un post entre 2 sitios, incluyendo metadatos de Meta Box (y también Slim SEO).

Esta consulta sincroniza un post desde un sitio WordPress a otro, incluyendo los metadatos.

Realiza las siguientes operaciones:

  1. Obtiene un post y todos sus metadatos del sitio de origen
  2. Crea un nuevo post o actualiza un post existente en el sitio de destino, copiando los datos del post y los metadatos del sitio de origen

Esta consulta requiere:

  • Gato GraphQL + extensiones PRO en el sitio de origen
  • El plugin gratuito de Gato GraphQL en el sitio de destino
  • Mutaciones Anidadas habilitadas en el endpoint del sitio de destino

Las variables requeridas son:

  • postType: El tipo de post personalizado a sincronizar entre sitios
  • postSlug: El slug del post a sincronizar entre sitios
  • downstreamServerGraphQLEndpointURL: La URL del endpoint GraphQL del sitio WordPress de destino
  • username: Nombre de usuario de la application password para autenticarse en el sitio de destino
  • appPassword: Contraseña de la application password para autenticarse en el sitio de destino
  • update: Si actualizar un post existente (true) o crear uno nuevo (false)

Si se actualiza el post, el identificador común entre los sitios upstream y downstream es el slug del post.

La consulta GraphQL debe ejecutarse en el sitio de origen.

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
          }
        ]
      }
    }
  )
}

Las variables se verían así:

{
  "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 }"
}