Schema 教程
Schema 教程第27课:向外部服务发送 ping

第27课:向外部服务发送 ping

我们可以向外部服务发送 ping,通知其网站新增的资源,同时传递存储在网站中的数据和/或通过参数或请求头提供的数据。

在这个 query 中,我们获取过去24小时内新增评论的 ID,并为每条评论向外部服务发送 ping,将评论 ID 作为参数附加在 URL 中,同时转发当前 HTTP 请求的部分请求头:

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

如果外部服务能够接收多个资源的数据,我们可以将所有数据汇总后,通过一次 ping 统一发送:

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