Hướng dẫn schema
Hướng dẫn schemaBài 27: Gửi ping đến các dịch vụ bên ngoài

Bài 27: Gửi ping đến các dịch vụ bên ngoài

Chúng ta có thể gửi ping đến các dịch vụ bên ngoài về các tài nguyên mới được thêm vào trang web của mình, truyền kèm dữ liệu được lưu trữ trong trang web và/hoặc được cung cấp qua các tham số hoặc tiêu đề.

Trong query này, chúng ta lấy ID của các bình luận được thêm trong 24 giờ qua và, với mỗi bình luận, gửi một ping đến một dịch vụ bên ngoài, truyền ID của chúng làm tham số trong URL và chuyển tiếp một số tiêu đề từ yêu cầu HTTP hiện tại:

{
  timeNow: _time  
  time24HsAgo: _intSubtract(subtract: 86400, from: $__timeNow)
  date24HsAgo: _date(format: "Y-m-d\\TH:i:sO", timestamp: $__time24HsAgo)
 
  comments(filter: { dateQuery: { after: $__date24HsAgo } } ) {
    commentID: id
    url: _urlAddParams(
      url: "https://somewebsite.com/ping-new-comment",
      params: {
        commentID: $__commentID
      }
    )
    headers: _httpRequestHeaders
      @remove
    requiredHeaders: _objectKeepProperties(
      object: $__headers,
      keys: ["user-agent", "origin"]
    )
      @remove
    headerNameValueEntryList: _objectConvertToNameValueEntryList(
      object: $__requiredHeaders
    )
    _sendHTTPRequest(input: {
      url: $__url
      method: GET
      options: {
        headers: $__headerNameValueEntryList
      }
    }) {
      statusCode
      contentType
      body
    }
  }
}

Nếu dịch vụ bên ngoài có thể nhận dữ liệu cho nhiều tài nguyên cùng lúc, chúng ta có thể thu thập tất cả chúng và sau đó gửi một ping duy nhất:

query ExportData {
  timeNow: _time  
  time24HsAgo: _intSubtract(subtract: 86400, from: $__timeNow)
  date24HsAgo: _date(format: "Y-m-d\\TH:i:sO", timestamp: $__time24HsAgo)
 
  comments(filter: { dateQuery: { after: $__date24HsAgo } } )
    @export(as: "commentIDs")
  {
    id
  }
 
  hasComments: _notEmpty(value: $__comments)
    @export(as: "hasComments")
    @remove
}
 
query SendPing
  @depends(on: "ExportData")
  @include(if: $hasComments)
{
  url: _urlAddParams(
    url: "https://somewebsite.com/ping-new-comments",
    params: {
      commentIDs: $commentIDs
    }
  )
  headers: _httpRequestHeaders
    @remove
  requiredHeaders: _objectKeepProperties(
    object: $__headers,
    keys: ["user-agent", "origin"]
  )
    @remove
  headerNameValueEntryList: _objectConvertToNameValueEntryList(
    object: $__requiredHeaders
  )
  _sendHTTPRequest(input: {
    url: $__url
    method: GET
    options: {
      headers: $__headerNameValueEntryList
    }
  }) {
    statusCode
    contentType
    body
  }
}