Tutorial dello schema
Tutorial dello schemaLezione 27: Inviare ping a servizi esterni

Lezione 27: Inviare ping a servizi esterni

Possiamo inviare ping a servizi esterni riguardo alle nuove risorse aggiunte al nostro sito web, trasmettendo dati memorizzati nel sito e/o forniti tramite parametri o intestazioni.

In questa query, recuperiamo gli ID dei commenti aggiunti nelle ultime 24 ore e, per ciascuno, inviamo un ping a un servizio esterno, passando il loro ID come parametro nell'URL e inoltrandone alcune intestazioni dalla richiesta HTTP corrente:

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

Se il servizio esterno è in grado di ricevere i dati per più risorse, possiamo raccoglierli tutti e quindi inviare un unico 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
  }
}