@adobe/fastly-native-promises 中文文档教程

发布于 2 年前 浏览 10 项目主页 更新于 2 年前

fastly-native-promises

用于 Node.js

NPM 版本codecovCircleCIGitHub 许可证GitHub issues

Problem

基于回调的fastly 包仍然是最常用的客户端在 NPM 上。 但是,我需要一个客户端,它允许我按顺序和并行地执行请求,而不会陷入难以驾驭的回调地狱Philipp Schulte 的 fastly-native-promises 客户端看起来几乎是完美的,除了:

  • it uses Axios, which is an additional dependency we'd like to avoid, especially when running inside Adobe I/O Runtime
  • it has been missing features and pull requests were merged only slowly

这个分支解决了上述问题但破坏了与浏览器,使其只能在 Node JS 环境中使用。

Solution

fastly-native-promises 包使用基于 promise 的 HTTP 客户端 Request-Promise-Native 执行对 Fastly API 的请求。 Request-Promise-Native 支持原生 JavaScript Promise API 并自动将数据转换为 JSON。 每个 fastly-native-promises API 方法都会返回一个 Promise 表示请求完成或失败。

Table of Contents

Security

您需要一个 Fastly API Token 才能使用 fastly-native-promises 库. 我建议使用 global scope 的令牌,以便能够使用所有 fastly-native-promises API 方法。

Install

这是一个 Node.js 模块,可通过 npm 注册中心。 使用 npm install 命令 完成安装:

$ npm install @adobe/fastly-native-promises

Changes

参见变更日志

Usage

const fastly = require('@adobe/fastly-native-promises');

// create one or more instances
const service_1 = fastly('token', 'service_id_1');
const serivce_2 = fastly('token', 'service_id_2');

// make changes

service_1.transact(async () => {
  return this.writeS3('test-s3', {
    name: 'test-s3',
    bucket_name: 'my_corporate_bucket',
    access_key: 'AKIAIOSFODNN7EXAMPLE',
    secret_key: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
  });
});


service_2.transact(async () => {
  return this.writeBigquery('test-bq', {
    name: 'test-bq',
    format: '{\n "timestamp":"%{begin:%Y-%m-%dT%H:%M:%S}t",\n  "time_elapsed":%{time.elapsed.usec}V,\n  "is_tls":%{if(req.is_ssl, "true", "false")}V,\n  "client_ip":"%{req.http.Fastly-Client-IP}V",\n  "geo_city":"%{client.geo.city}V",\n  "geo_country_code":"%{client.geo.country_code}V",\n  "request":"%{req.request}V",\n  "host":"%{req.http.Fastly-Orig-Host}V",\n  "url":"%{json.escape(req.url)}V",\n  "request_referer":"%{json.escape(req.http.Referer)}V",\n  "request_user_agent":"%{json.escape(req.http.User-Agent)}V",\n  "request_accept_language":"%{json.escape(req.http.Accept-Language)}V",\n  "request_accept_charset":"%{json.escape(req.http.Accept-Charset)}V",\n  "cache_status":"%{regsub(fastly_info.state, "^(HIT-(SYNTH)|(HITPASS|HIT|MISS|PASS|ERROR|PIPE)).*", "\\\\2\\\\3") }V"\n}',
    user: 'fastly-bigquery-log@example-fastly-log.iam.gserviceaccount.com',
    project_id: 'example-fastly-log',
    dataset: 'fastly_log_test',
    table: 'fastly_logs',
    template_suffix: null,
    secret_key: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7bPG9yaIYd5AL\nmvOaYvNozFJB/VWS53KWBll769kJvlmgMks6r6Xrv8w6rjxWKjZeDrnXVf7UDa0F\nckPPIFvXRxahftWFMGArw0lIvQzgT4/BlndXU5RNxfah/8m7q/GIF6oNYWzfJwvv\nzodxDUqIRH2e2JWidNRjElHuogYHLhV4O/od5pAkfDwak/ihuuh/2VA3Auwb3nph\ndX2F0JBs14oPKZUTYUUSzUQY5IMxSxYUA4Q7W4v21x1EnJt+biXOrERk1rm4ieEE\nU3WkjR5c5gvG8xcWyYod87RNFELmIhCCytI1+t5C3Em/jPsQFtLzwHpbNhdW4oEm\nn7d06n75AgMBAAECggEAWRh26lNZfOwJS5sDRlbXgu/uAnSdI1JmxC6Mhz4cVGdq\nT57Y6DLrWuA4A4UkJYm3gorZiSXWF5PQthAVb/bf8bxXY7nZYpEWhnc09SD5aAAq\nREp0vMx8aWQ709K2YUJg+zDUo7u2d3YmVH8HH5TD43c7iDFJIIsNE3N4A0p+NxZ+\nw06FFW+fz/etrWiNyhrlTsbkMbSgU+GpFFBq1pCd0ni5d1YM1rsaAaUpmkwdjgjL\noDs+M/L/HtqfEhyZNdw8JF7EJXVE1bIl7/NL0rBInhyO28FcB56t/AG5nzXKFI/c\nc+IO7d6MOOqiGRLRWZItEpnyzuV8DZo461wy1hSvqQKBgQDhSsg2cHkTrtBW8x0A\n3BwB/ygdkkxm1OIvfioT+JBneRufUPvVIM2aPZBBGKEedDAmIGn/8f9XAHhKjs8B\nEsPRgE206s4+hnrTcK7AeWWPvM9FDkrkQCoJFuJrNy9mJt8gs7AnnoBa9u/J4naW\ne1tfC8fUfsa7kdzblDhcRQ8FhwKBgQDU+N4kPzIdUuJDadd6TkBbjUNPEfZzU5+t\nIike2VSRhApxAxviUnTDsTROwJRzKik9w7gIMka8Ek+nmLNMEtds77ttcGQRdu16\n+vT1iualiCJe+/iMbl+PiJtFwhEHECLU9QfgBVS6r2lDAlZA+w6nwCRiidlrObzO\nCXqVOzN3fwKBgAsrOuu//bClHP0ChnCReO38aU+1/gWnDiOOnKVq0DXhAiaOzD1P\nqAG6hZlEkFBDMPWzq62doKv+gPgpRkfmV0DenHuYnGrrHdG3p2IxYoCSuq/QupPA\nPpU+xjDMhpQI30zuu4/rQq+/yDl4+aoSKYB3xAtb0Zxg6dMU8QpZ/hmnAoGBAIFu\nIesbcQR7O8FGkMrmxZweNNrYCtQ57R/WU/FImWm6OnJGNmsMO6Q2jJiT12RKKjg8\nOxrYGz7vTfOIDOddyAiPhXPUSyyF/3uvCrIzUUsmeeUJ8xq9dVwQ5HS3pYuKVfDg\nXYHbG4w9UJaF1A+3xEdUsYglSLouo7z/67zH9tZXAoGBAKpsdjSd3R+llaAv2HQ8\nGMlN92UTr5i9w++QMXq4qspH5NEYqz3NHbKuYthZqxEsRUZbRP50eDWU4jvxFVJl\nLBFINp6B+3AsIme0YCyOaleB/Cy0347miSinSv2I6QiH6dQxHdHzrG+x1evS/76f\nKT0KS+ySjCAEWgg4v+mjUDUV\n-----END PRIVATE KEY-----\n',
    response_condition: '',
  });

  // optional, but speeds up end of process
  await service_1.discard();
  await service_2.discard();
});

Promises

清除活动版本的所有域:

  1. Get all the versions.
  2. Filter out the active version.
  3. Get all the domains for the active version.
  4. Purge all the domains.
  5. Log the status text for each purge request.
const fastly = require('fastly-native-promises');

const service = fastly('token', 'service_id');

function handler() {
  service.readVersions()
    .then(versions => {
      const active = versions.data.filter(version => version.active)[0];
      return service.readDomains(active.number);
    })
    .then(domains => {
      return Promise.all(domains.data.map(domain => service.purgeIndividual(domain.name)));
    })
    .then(purges => {
      purges.forEach(purge => console.log(purge.statusText));
    })
    .catch(e => {
      console.log('Shoot!');
    });
}

Async/Await

如果值小于 5000 毫秒,则更新每个后端和服务的 first_byte_timeout 属性:

  1. Get all the services associated with the Fastly API token.
  2. Filter out the service IDs.
  3. Iterate over all services synchronously.
  4. Get all the versions.
  5. Filter out the active version.
  6. Get all the backends for the active version.
  7. Filter out the affected backends.
  8. Continue with the next service if there are no affected backends.
  9. Clone the active version.
  10. Update all the affected backends parallelly.
  11. Activate the cloned version.
const fastly = require('fastly-native-promises');

const account = fastly('token');

async function handler() {
  try {
    const services = await account.readServices();
    const ids = services.data.map(service => service.id);

    for (const id of ids) {
      const service = fastly('token', id);
      const versions = await service.readVersions();
      const active = versions.data.filter(version => version.active)[0];
      const backends = await service.readBackends(active.number);
      const affected = backends.data.filter(backend => backend.first_byte_timeout < 5000);

      if (!affected.length) continue;

      const clone = await service.cloneVersion(active.number);
      await Promise.all(affected.map(backend => service.updateBackend(clone.data.number, backend.name, { first_byte_timeout: 5000 })));
      await service.activateVersion(clone.data.number);
    }
  } catch (e) {
    console.log('Shoot!');
  }
}

Response Schema

每个 fastly-native-promises API 方法返回以下内容响应对象:

{
  // the HTTP status code from the server response
  status: 200,

  // the HTTP status message from the server response
  statusText: 'OK',

  // the headers that the server responded with
  headers: {},

  // the options that were provided to request for the request
  config: {},

  // the request that generated the response
  request: {},

  // the response that was provided by the server
  data: {}
}

Retrieving Request Statistics

Fastly 实例有一个 requestmonitor 属性,可用于检索请求统计信息:

  • requestmonitor.count for the total number of requests.
  • requestmonitor.remaining for the number of requests remaining according to Fastly's API Rate limit for the hour or undefined (if no modifying requests have been made yet).
  • requestmonitor.edgedurations for an array of API processing durations (in milliseconds, measured from the edge).
  • requestmonitor.durations for an array of request durations (in milliseconds, measured from the client, i.e. including network latency).

使用 requestmonitor.stats 您可以获得所有这些在一个对象中,包括所有请求的最小、最大和平均持续时间。

Guarding against Rate Limits

使用 requestmonitor.remaining 属性,您可以确保在达到速率限制之前仍有足够的请求。

使用 instance.transact 方法时,您可以进一步提供必要的可用请求限制的最小值,以便在初始克隆版本后,如果超过 API 速率限制,则不会发出其他请求. 这允许您在出现速率限制问题时快速失败。

High-Level Helpers

虽然大多数功能是 Fastly API 的低级包装器,但我们在 Fastly 实例的属性中提供了几个高级辅助函数。

Conditions Helper in fastly.conditions

条件助手简化了条件的创建和管理。

const fastly = require('fastly-native-promises');

const instance = fastly('mykey', 'service-config');

const update = fastly.conditions.update(1, 'REQUEST', 'Created as an Example', 'example');

const conditions = await update('req.url.basename == "new.html"', 'req.url.basename == "index.html"');

console.log('Created a condition matching index.html with following name', conditions['req.url.basename == "index.html"'].name);

fastly.conditions.update 可以通过参数version(服务配置版本)、type(条件类型,REQUEST< /code>、RESPONSECACHE)、comment(将在 Fastly UI 中显示的注释)、nameprefix< /code>(条件名称的通用前缀)以获取执行更新的新函数 update

当使用 VCL 条件语言中的 statements 列表调用 update 时,它将把传入的条件列表与 Fastly 服务配置中已经存在的条件同步。 共享相同 nameprefix 但不再使用的所有条件将被删除,将创建尚不存在的新条件(不触及未更改的条件,减少更新时发出的请求数).

update 的返回值是一个将条件语句映射到条件对象的对象。 这允许在其他 Fastly API 调用中重用条件。

Header Helper in fastly.headers

标头助手简化了条件标头的创建和管理。

const fastly = require('fastly-native-promises');

const instance = fastly('mykey', 'service-config');

const update = fastly.headers.update(
  1,
  'REQUEST', // apply a request condition
  'Created as an Example', // use following comment for conditions
  'example', // name-prefix for all generated conditions and headers
  'set', // set the header
  'http.Location' // which header (Location)
  'request' // in the request handling
  );

await update(
    {
      condition: 'req.url.basename == "new.html"',
      expression: '"https://new.example.com"',
    },
    {
      condition: 'req.url.basename == "index.html"',
      expression: 'https://www.example.com',
    });

fastly.headers.update 可以通过参数version(服务配置版本),type(条件类型,REQUEST< /code>、RESPONSECACHE)、comment(将在 Fastly UI 中显示的注释)、nameprefix< /code>(条件名称的通用前缀)、action(对标头做什么,可以是setappend,或者delete), header (header 的名称——记得在值中包含 http.), sub (应用header的子程序,可以是requestfetchcache,或者response)得到执行更新的新函数 update

update 被一个 objects 列表调用时,看起来像 { condition: 'req.url ~ "foo/(.*)/bar"', expression : '"bar/" + re.group.1 + "/foo"'},即 condition(在 VCL 条件语言中)和 expression 对code>(也是有效的 VCL),它将同步传入的标头列表(和结果条件)与 Fastly 服务配置中已经存在的标头和条件。 共享相同 nameprefix 但不再使用的所有条件和标头将被删除,将创建尚不存在的新条件和标头(不会触及未更改的条件和标头,从而减少更新时发出的请求数)。

API

Classes

AccountAPI : AccountAPI

Fastly 账户 API。

AuthAPI : AuthAPI

快速验证 API。

DomainAPI : DomainAPI

Fastly 域 API。

HealthcheckAPI : HealthcheckAPI

快速健康检查 API。

PurgeAPI : PurgeAPI

快速清除 API。

Conditions

具有状态管理高级操作的助手类。

Headers

具有状态管理高级操作的助手类。

Fastly

Functions

repeat(responseOrError)boolean

确定响应或错误是否表明响应是可重复的。

Typedefs

CreateFunctionPromise

创建特定类型资源的函数。 如果那个资源 name 已经存在,它将拒绝返回的错误承诺。

UpdateFunctionPromise

更新特定类型的现有资源的函数。 如果不存在该名称的资源,它将拒绝返回的承诺并出错。

ReadFunctionPromise

检索特定类型资源表示的函数。 如果不存在该名称的资源,它将拒绝返回的承诺并出错。

ListFunctionPromise

检索特定类型资源列表的函数。

FastlyError : object

FastlyError 类描述了可能发生的最常见的错误 使用 Fastly API 时。 使用 error.status,底层 可以检索 HTTP 状态代码。 已知的错误状态代码包括:

  • 400: attempting to activate invalid VCL
  • 401: invalid credentials
  • 404: resource not found
  • 409: confict when trying to POST a resource that already exists
  • 422: attempting to modify a service config that is not checked out
  • 429: rate limit exceeded, try again later
Response : object
Versions : object

描述最相关的服务版本。

DictUpdate : object

指定字典更新操作。 在大多数情况下,upsert 是最好的方法 更新值,因为它适用于现有和不存在的项目。

Snippet : object
VCL : object

AccountAPI : AccountAPI

Fastly 账户 API。

种类:全局类
参见:https:

//docs.fastly.com/api/account#top

accountAPI.readCurrentUser() ⇒ Promise

获取当前登录的用户。

种类AccountAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https://docs.fastly.com/api/account#user_91db9d9178f3f4c7597899942bd3f941

accountAPI.readUsers() ⇒ Promise

获取当前客户的所有用户列表。

种类AccountAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https://docs.fastly.com/api/account#customer_12f4a69627ba3bbb1c8668aae03a60ad

accountAPI.readUser(id) ⇒ Promise

获取指定id的用户。

种类AccountAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
idstringThe User ID.

//docs.fastly.com/api/account#user_15a6c72980b9434ebb8253c7e882c26c

accountAPI.createUser(name, login) ⇒ Promise

创建一个用户。

种类AccountAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
namestringThe user name.
loginstringThe user login.

//docs.fastly.com/api/account#user_00b606002596bac1c652614de98bd260

accountAPI.readInvitations() ⇒ Promise

列出所有邀请。

种类AccountAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https://docs.fastly.com/api/account#invitations_6d8623de97ed7e50b7b6498e374bb657

accountAPI.createInvitation(email, role) ⇒ Promise

创建邀请。

种类AccountAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDefaultDescription
emailstringThe email address for the invitation.
rolestring&quot;engineer&quot;The user role. Defaults to {@code engineer}.

//docs.fastly.com/api/account#invitations_8c4da3ca11c75facd36cfaad024bd891

accountAPI.acceptInvitation(acceptCode, name, password) ⇒ Promise

接受邀请。

种类AccountAPI
的实例方法 ReturnsPromise - 表示完成或失败的响应对象。

ParamTypeDescription
acceptCodestringThe accept code retrieved in the email.
namestringName for the new user.
passwordstringPassword for the new user.

accountAPI.deleteInvitation(id) ⇒ Promise

删除邀请。

种类AccountAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
idstringThe invitation id.

//docs.fastly.com/api/account#invitations_d70a7460c7e1bd8dd660c6f5b3558c2e

AuthAPI : AuthAPI

Fastly Auth API。

种类:全局类
参见:https:

//docs.fastly.com/api/auth#top

authAPI.readTokens([customerId]) ⇒ Promise

列出客户的所有令牌。

种类AuthAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
[customerId]stringThe id of the customer.

//docs.fastly.com/api/auth#tokens_d59ff8612bae27a2317278abb048db0c

authAPI.readToken([id]) ⇒ Promise

获取指定id的token。 如果缺少 Id,则返回自身令牌。

种类AuthAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
[id]stringThe token id.

//docs.fastly.com/api/auth#tokens_bb00e7ed542cbcd7f32b5c908b8ce244

authAPI.deleteToken([id]) ⇒ Promise

删除具有指定 id 的令牌。

种类AuthAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
[id]stringThe token id.

//docs.fastly.com/api/auth#tokens_4a958ba69402500937f0d8570f7ce86f

authAPI.createToken(options) ⇒ Promise

创建 API 令牌。

种类AuthAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
optionsobjectThe token options.

//docs.fastly.com/api/auth#tokens_db4655a45a0107448eb0676577446e40

DomainAPI : DomainAPI

Fastly Domain API。

种类:全局类
参见:https:

//docs.fastly.com/api/config#domain

domainAPI.domainCheck(version, name) ⇒ Promise

检查特定服务和版本的所有域的状态.

种类DomainAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the domain.

//docs.fastly.com/api/config#domain_30a3f14c9a0ce5730757d39983ab7dc6

domainAPI.domainCheckAll(version) ⇒ Promise

检查特定服务和版本的所有域的状态.

种类DomainAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.

//docs.fastly.com/api/config#domain_e33a599694c3316f00b6b8d53a2db7d9 示例

instance.domainCheckAll('182')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

domainAPI.readDomains(version) ⇒ Promise

列出所有域对于特定的服务和版本。

种类DomainAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.

//docs.fastly.com/api/config#domain_6d340186666771f022ca20f81609d03d 示例

instance.readDomains('182')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

domainAPI.readDomain(version, name) ⇒ Promise

列出所有域对于特定的服务和版本。

种类DomainAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringThe domain name.

//docs.fastly.com/api/config#domain_f1b5fab17a0729daeeaf7594b47759c5

domainAPI.readServiceDomains([serviceId]) ⇒ Promise

列出服务中的域。

种类DomainAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
[serviceId]stringThe service id.

//docs.fastly.com/api/config#service_d5578a1e3bc75512711ddd0a58ce7a36

domainAPI.createDomain(version, name, comment) ⇒ Promise

为特定服务和版本创建域。

种类DomainAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringThe domain name.
commentstringOptional comment.

//docs.fastly.com/api/config#domain_90345101274774ff1b84f0a7dd010b01

domainAPI.updateDomain(version, oldName, name, comment) ⇒ Promise

更新特定服务和版本的域。

种类DomainAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
oldNamestringThe old name of the domain.
namestringThe domain name.
commentstringOptional comment.

//docs.fastly.com/api/config#domain_2ef42bd9b4c56c86b46dc0e36096ab10

domainAPI.deleteDomain(version, name) ⇒ Promise

删除特定服务和版本的域。

种类DomainAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringThe domain name.

//docs.fastly.com/api/config#domain_aab5a322f58df2b1db8dc276e8594a70

HealthcheckAPI : HealthcheckAPI

Fastly Healthcheck API。

种类:全局类
参见:https:

//docs.fastly.com/api/config#healthcheck

healthcheckAPI.readHealthchecks(version) ⇒ Promise

列出特定服务和版本的所有健康检查。

种类HealthcheckAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.

//docs.fastly.com/api/config#healthcheck_126cb37382d68583269420ba772ded36

healthcheckAPI.readHealthcheck(version, name) ⇒ Promise

获取单个命名健康检查的详细信息。

种类HealthcheckAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the healthcheck.

//docs.fastly.com/api/config#healthcheck_b54ea357a2377e62ae7649e609b94966

healthcheckAPI.createHealthcheck(version, data) ⇒ Promise

为特定服务和版本创建健康检查。

种类HealthcheckAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
dataobjectThe healthcheck definition.

//docs.fastly.com/api/config#healthcheck_8712be8923dd419c54393da3ac31f6d3

healthcheckAPI.updateHealthcheck(version, name, data) ⇒ Promise

更新特定服务和版本的健康检查。

种类HealthcheckAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the healthcheck to update.
dataobjectThe healthcheck definition.

//docs.fastly.com/api/config#healthcheck_9a60b6005125c4afeaa80111e69d7586

healthcheckAPI.deleteHealthcheck(version, name) ⇒ Promise

删除特定服务和版本的健康检查。

种类HealthcheckAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the healthcheck to delete.

//docs.fastly.com/api/config#healthcheck_a22900c40a2fd59db5028061dc5dfa36

PurgeAPI : PurgeAPI

快速清除 API。

种类:全局类
参见:https:

//docs.fastly.com/api/purge#purge

purgeAPI.purgeIndividual(url) ⇒ Promise

即时清除单个 URL。

种类PurgeAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
urlstringThe URL to purge.

//docs.fastly.com/api/purge#purge_3aa1d66ee81dbfed0b03deed0fa16a9a 示例

instance.purgeIndividual('www.example.com')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.purgeAll() ⇒ Promise

Instant Purge everything from一项服务。

种类PurgeAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https://docs.fastly.com/api/purge#purge_bee5ed1a0cfd541e8b9f970a44718546
示例

instance.purgeAll()
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.purgeKey(key) ⇒ Promise

即时清除带有代理键标记的项目的特定服务。

种类PurgeAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
keystringThe surrogate key to purge.

//docs.fastly.com/api/purge#purge_d8b8e8be84c350dd92492453a3df3230 示例

instance.purgeKey('key_1')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.purgeKeys(keys) ⇒ Promise

即时清除特定批量使用代理键标记的项目服务。

种类PurgeAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
keysArrayThe array of surrogate keys to purge.

//docs.fastly.com/api/purge#purge_db35b293f8a724717fcf25628d713583 示例

instance.purgeKeys(['key_2', 'key_3', 'key_4'])
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.softPurgeIndividual(url) ⇒ Promise

软清除个人网址。

种类PurgeAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
urlstringThe URL to soft purge.

//docs.fastly.com/api/purge#softpurge0c4f56f3d68e9bed44fb8b638b78ea36 示例

instance.softPurgeIndividual('www.example.com/images')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.softPurgeKey(key) ⇒ Promise

软清除标记有代理键的项目的特定服务。

种类PurgeAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
keystringThe surrogate key to soft purge.

//docs.fastly.com/api/purge#softpurge2e4d29085640127739f8467f27a5b549 示例

instance.softPurgeKey('key_5')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.softPurgeKeys(keys) ⇒ Promise

软清除批量标记有代理键的项目的特定服务。

种类PurgeAPI
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
keysArrayThe array of surrogate keys to purge.

//docs.fastly.com/api/purge#purge_db35b293f8a724717fcf25628d713583 Example

instance.softPurgeKeys(['key_2', 'key_3', 'key_4'])
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

Conditions

Helper class with high-level状态管理操作。

种类:全局类

conditions.multistepupdate(version, type, commentprefix, nameprefix) ⇒ Array.&lt;function()&gt;

创建多步创建缺失和删除的函数 多余的条件。

KindConditions
的实例方法 返回Array.&lt;function()&gt; - 一对创建和清理函数。

ParamTypeDescription
versionnumberService config version.
typestringCondition type, can be REQUEST, RESPONSE, or CACHE.
commentprefixstringThe prefix to be used for comments.
nameprefixstring- The prefix to be used for names.

Headers

具有状态管理高级操作的辅助类。

种类:全局类

headers.update(version, type, commentprefix, nameprefix, action, header, sub) ⇒ Array.&lt;function()&gt;

创建多步创建缺失和删除的函数 多余的条件标头。

KindHeaders
的实例方法 返回Array.&lt;function()&gt; - 一对创建和清理函数。

ParamTypeDescription
versionnumberService config version.
typestringCondition type, can be REQUEST, RESPONSE, or CACHE.
commentprefixstringThe prefix to be used for comments.
nameprefixstring- The prefix to be used for names.
actionstringWhat do do with the header, can be set, append, delete.
headerstringThe name of the header to set.
substringName of the subroutine where the header should be applied, can be request, fetch, cache, or response.

Fastly

Kind:全局类

new Fastly(token, service_id, timeout)

用于创建快速承诺实例的构造方法。

ParamTypeDefaultDescription
tokenstringThe Fastly API token.
service_idstringThe Fastly service ID.
timeoutnumber15000HTTP timeout for requests to the Fastly API, default: 15 seconds.

fastly.readLogsFn(service) ⇒ ListFunction

创建一个新函数,列出给定服务的所有日志配置 和版本。 该函数可以使用日志记录的名称进行参数化 服务。

KindFastly
的实例方法 返回ListFunction - 一个日志函数。

ParamTypeDescription
servicestringThe id of the logging service. Supported services are: s3, s3canary, azureblob, cloudfiles, digitalocean, ftp, bigquery, gcs, honeycomb, logshuttle, logentries, loggly, heroku, https, openstack, papertrail, scalyr, splunk, sumologic, syslog.

fastly.readLogFn(service) ⇒ ReadFunction

创建一个新函数,返回给定服务的命名日志配置 和版本。 该函数可以使用日志记录的名称进行参数化 服务。

KindFastly
的实例方法 返回ReadFunction - 一个日志函数。

ParamTypeDescription
servicestringThe id of the logging service. Supported services are: s3, s3canary, azureblob, cloudfiles, digitalocean, ftp, bigquery, gcs, honeycomb, logshuttle, logentries, loggly, heroku, https, openstack, papertrail, scalyr, splunk, sumologic, syslog.

fastly.createLogFn(service) ⇒ CreateFunction

创建一个新函数,为给定服务创建命名日志配置 和版本。 该函数可以使用日志记录的名称进行参数化 服务。

KindFastly
的实例方法 返回CreateFunction - 一个日志函数。

ParamTypeDescription
servicestringThe id of the logging service. Supported services are: s3, s3canary, azureblob, cloudfiles, digitalocean, ftp, bigquery, gcs, honeycomb, logshuttle, logentries, loggly, heroku, https, openstack, papertrail, scalyr, splunk, sumologic, syslog.

fastly.updateLogFn(service) ⇒ UpdateFunction

创建一个新函数来更新给定服务的命名日志配置 和版本。 该函数可以使用日志记录的名称进行参数化 服务。

KindFastly
的实例方法 返回UpdateFunction - 一个日志函数。

ParamTypeDescription
servicestringThe id of the logging service. Supported services are: s3, s3canary, azureblob, cloudfiles, digitalocean, ftp, bigquery, gcs, honeycomb, logshuttle, logentries, loggly, heroku, https, openstack, papertrail, scalyr, splunk, sumologic, syslog.

fastly.upsertFn(createFn, updateFn, readFn) ⇒ UpdateFunction

创建一个更新或创建或“安全创建”函数,该函数将创建 (如果不存在)或更新(如果存在)命名资源。 功能 将首先尝试检查资源是否存在(如果阅读器功能已被 提供),或者,它只会盲目地创建并回退 更新。

KindFastly
的实例方法 返回UpdateFunction - 不会因冲突而失败的更新函数。

ParamTypeDescription
createFnCreateFunctionA function that creates a resource.
updateFnUpdateFunctionA function that updates a resource.
readFnReadFunctionAn optional function that checks for the existence of a resource.

fastly.discard()

绑定到 HTTP 客户端的免费资源(挂起的会话/套接字) 并允许节点进程退出。

KindFastly
的实例方法 返回Promise - 当所有资源都被释放时解析的承诺。

fastly.dataCenters() ⇒ Promise

获取所有 Fastly 数据中心的列表。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https://docs.fastly.com/api/tools#datacenter_1c8d3b9dd035e301155b44eae05e0554
示例

instance.dataCenters()
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.publicIpList() ⇒ Promise

Fastly 的服务 IP 范围。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https://docs.fastly.com/api/tools#publiciplist_ef2e9900a1c9522b58f5abed92ec785e
示例

instance.publicIpList()
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.edgeCheck(url) ⇒ Promise

从每个 Fastly 边缘服务器检索特定 URL 的内容的标头和 MD5 哈希值。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
urlstringFull URL (host and path) to check on all nodes. If protocol is omitted, http will be assumed.

//docs.fastly.com/api/tools#content_4d2d4548b29c7661e17ebe7098872d6d 示例

instance.edgeCheck('api.example.com')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readServices() ⇒ Promise

列出所有服务。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https://docs.fastly.com/api/config#service_74d98f7e5d018256e44d1cf820388ef8
示例

instance.readServices()
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readServicesById() ⇒ Promise

读取服务并返回一个数据对象,其中包含服务 ID 所在的地图 钥匙。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。

fastly.readService([serviceId]) ⇒ Promise

通过id获取特定服务。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
[serviceId]stringThe service id.

//docs.fastly.com/api/config#service_a884a9abd5af9723f6fcbb1ed13ae4cc

fastly.readVersions() ⇒ Promise

列出特定服务的版本。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https://docs.fastly.com/api/config#version_dfde9093f4eb0aa2497bbfd1d9415987
示例

instance.readVersions()
   .then(res => {
     const active = res.data.filter(version => version.active);
     console.log(active);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.getVersions() ⇒ Versions

获取服务的版本足迹。

KindFastly
的实例方法 返回Versions - 服务的最新、当前和活动版本。

fastly.cloneVersion(version) ⇒ Promise

将当前配置克隆到新版本中。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe version to be cloned.

//docs.fastly.com/api/config#version_7f4937d0663a27fbb765820d4c76c709 示例

instance.cloneVersion('45')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.activateVersion(version) ⇒ Promise

激活当前版本.

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe version to be activated.

//docs.fastly.com/api/config#version_0b79ae1ba6aee61d64cc4d43fed1e0d5 示例

instance.activateVersion('23')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readDictItems(version, name) ⇒ Promise

列出所有字典项对于特定的服务和版本。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe version of the dictionary.
namestringThe name of the dictionary.

//docs.fastly.com/api/config#dictionaryitema48de28cd7e76c1ea58523f39bb7204b 示例

instance.readDictItems(1, 'my_dictionary')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readDictItem(version, name, key) ⇒ Promise

获取单个字典项的详细信息。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringName of the dictionary.
keystringThe key to retrieve values by.

//docs.fastly.com/api/config#dictionaryitem08f090cd03ed4602ae63f131087e2f29 示例

instance.readDictItem('12', 'extensions', 'some_key')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.createDictItem(version, name, key, value) ⇒ Promise

为特定服务和版本创建一个新的字典项。

KindFastly
的实例方法 返回Promise - 响应对象。
参见:https:

ParamTypeDescription
versionnumberThe version number (current if omitted).
nameobjectThe dictionary definition.
keystringThe key.
valuestringThe value to write.

//docs.fastly.com/api/config#dictionaryitem 6ec455c0ba1b21671789e1362bc7fe55

fastly.bulkUpdateDictItems(version, name, …items) ⇒ Promise

更新多个字典散装物品。

KindFastly
的实例方法 返回Promise - 响应对象。

ParamTypeDescription
versionnumberThe version numer (current if ommitted).
namestringName of the dictionary.
…itemsDictUpdateThe dictionary update operations.

示例

// single item
fastly.bulkUpdateDictItems(1, 'secret_dictionary',
  { item_key: 'some_key', item_value: 'some_value', op: 'upsert' });

// multiple items
fastly.bulkUpdateDictItems(1, 'secret_dictionary',
  { item_key: 'some_key', item_value: 'some_value', op: 'update' },
  { item_key: 'other_key', item_value: 'other_value', op: 'update' });

fastly.updateDictItem(version, name, key, value) ⇒ Promise

更新特定服务和版本的字典项值。

KindFastly
的实例方法 返回Promise - 表示完成或失败的响应对象。
参见:https:

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the dictionary.
keystringThe key to update data under.
valuestringThe value to update the dictionary with.

//docs.fastly.com/api/config#dictionaryitem34c884a7cdce84dfcfd38dac7a0b5bb0 示例

instance.updateDictItem(1, 'extensions', 'html', 'text/html')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.deleteDictItem(version, name, key) ⇒ Promise

删除特定服务和版本的字典项。

KindFastly
的实例方法 Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionaryitem664347e743b8eafc9a93c729d9da0427

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the dictionary.
keystringThe key to update data under.

Example

instance.deleteDictItem('34', 'extensions', 'html')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.writeDictItem(version, name, key, value) ⇒ Promise

Safely create, update or delete a dictionary item in a named dictionary.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.

ParamTypeDescription
versionnumberService version to use for dictionary lookup.
namestringName of the dictionary (not ID).
keystringKey to create, update or delete.
valuestringValue to update. Empty strings will delete the dictionary entry.

fastly.readDictionaries(version) ⇒ Promise

List all dictionaries for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionary_6d2cc293b994eb8c16d93e92e91f3915

ParamTypeDescription
versionstringThe current version of a service.

Example

instance.readDictionaries('12')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readDictionary(version, name) ⇒ Promise

Get details of a single dictionary.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionary_0e16df083830ed3b6c30b73dcef64014

ParamTypeDescription
versionstringThe current version of a service.
namestringName of the dictionary.

Example

instance.readDictionary('12', 'extensions')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.createDictionary(version, data) ⇒ Promise

Create a new dictionary for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The reponse object.
See: https://docs.fastly.com/api/config#dictionary_7d48b87bf82433162a3b209292722125

ParamTypeDescription
versionnumberThe version number (current if omitted).
dataobjectThe dictionary definition.

fastly.updateDictionary(version, name, data) ⇒ Promise

Update a dictionary for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionary_8c9da370b1591d99e5389143a5589a32

ParamTypeDescription
versionstringThe current version of a s

fastly-native-promises

Native Promise based Fastly API client for Node.js

NPM VersioncodecovCircleCIGitHub licenseGitHub issues

Problem

The callback-based fastly package is still the most used client on NPM. However, I needed a client which allows me to perform request sequentially and parallelly without ending up in an untamable callback hell. Philipp Schulte's fastly-native-promises client seemed almost perfect, except:

  • it uses Axios, which is an additional dependency we'd like to avoid, especially when running inside Adobe I/O Runtime
  • it has been missing features and pull requests were merged only slowly

This fork addresses the concerns above but breaks compatibility with Browsers, so that it can only be used in Node JS environments.

Solution

The fastly-native-promises package uses the promise-based HTTP client Request-Promise-Native to perform requests to the Fastly API. Request-Promise-Native supports the native JavaScript Promise API and automatically transforms the data into JSON. Each fastly-native-promises API method returns a Promise which represents either the completion or failure of the request.

Table of Contents

Security

You'll need a Fastly API Token to use the fastly-native-promises library. I recommend using a token with global scope to be able to use all fastly-native-promises API methods.

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install @adobe/fastly-native-promises

Changes

See the changelog.

Usage

const fastly = require('@adobe/fastly-native-promises');

// create one or more instances
const service_1 = fastly('token', 'service_id_1');
const serivce_2 = fastly('token', 'service_id_2');

// make changes

service_1.transact(async () => {
  return this.writeS3('test-s3', {
    name: 'test-s3',
    bucket_name: 'my_corporate_bucket',
    access_key: 'AKIAIOSFODNN7EXAMPLE',
    secret_key: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
  });
});


service_2.transact(async () => {
  return this.writeBigquery('test-bq', {
    name: 'test-bq',
    format: '{\n "timestamp":"%{begin:%Y-%m-%dT%H:%M:%S}t",\n  "time_elapsed":%{time.elapsed.usec}V,\n  "is_tls":%{if(req.is_ssl, "true", "false")}V,\n  "client_ip":"%{req.http.Fastly-Client-IP}V",\n  "geo_city":"%{client.geo.city}V",\n  "geo_country_code":"%{client.geo.country_code}V",\n  "request":"%{req.request}V",\n  "host":"%{req.http.Fastly-Orig-Host}V",\n  "url":"%{json.escape(req.url)}V",\n  "request_referer":"%{json.escape(req.http.Referer)}V",\n  "request_user_agent":"%{json.escape(req.http.User-Agent)}V",\n  "request_accept_language":"%{json.escape(req.http.Accept-Language)}V",\n  "request_accept_charset":"%{json.escape(req.http.Accept-Charset)}V",\n  "cache_status":"%{regsub(fastly_info.state, "^(HIT-(SYNTH)|(HITPASS|HIT|MISS|PASS|ERROR|PIPE)).*", "\\\\2\\\\3") }V"\n}',
    user: 'fastly-bigquery-log@example-fastly-log.iam.gserviceaccount.com',
    project_id: 'example-fastly-log',
    dataset: 'fastly_log_test',
    table: 'fastly_logs',
    template_suffix: null,
    secret_key: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7bPG9yaIYd5AL\nmvOaYvNozFJB/VWS53KWBll769kJvlmgMks6r6Xrv8w6rjxWKjZeDrnXVf7UDa0F\nckPPIFvXRxahftWFMGArw0lIvQzgT4/BlndXU5RNxfah/8m7q/GIF6oNYWzfJwvv\nzodxDUqIRH2e2JWidNRjElHuogYHLhV4O/od5pAkfDwak/ihuuh/2VA3Auwb3nph\ndX2F0JBs14oPKZUTYUUSzUQY5IMxSxYUA4Q7W4v21x1EnJt+biXOrERk1rm4ieEE\nU3WkjR5c5gvG8xcWyYod87RNFELmIhCCytI1+t5C3Em/jPsQFtLzwHpbNhdW4oEm\nn7d06n75AgMBAAECggEAWRh26lNZfOwJS5sDRlbXgu/uAnSdI1JmxC6Mhz4cVGdq\nT57Y6DLrWuA4A4UkJYm3gorZiSXWF5PQthAVb/bf8bxXY7nZYpEWhnc09SD5aAAq\nREp0vMx8aWQ709K2YUJg+zDUo7u2d3YmVH8HH5TD43c7iDFJIIsNE3N4A0p+NxZ+\nw06FFW+fz/etrWiNyhrlTsbkMbSgU+GpFFBq1pCd0ni5d1YM1rsaAaUpmkwdjgjL\noDs+M/L/HtqfEhyZNdw8JF7EJXVE1bIl7/NL0rBInhyO28FcB56t/AG5nzXKFI/c\nc+IO7d6MOOqiGRLRWZItEpnyzuV8DZo461wy1hSvqQKBgQDhSsg2cHkTrtBW8x0A\n3BwB/ygdkkxm1OIvfioT+JBneRufUPvVIM2aPZBBGKEedDAmIGn/8f9XAHhKjs8B\nEsPRgE206s4+hnrTcK7AeWWPvM9FDkrkQCoJFuJrNy9mJt8gs7AnnoBa9u/J4naW\ne1tfC8fUfsa7kdzblDhcRQ8FhwKBgQDU+N4kPzIdUuJDadd6TkBbjUNPEfZzU5+t\nIike2VSRhApxAxviUnTDsTROwJRzKik9w7gIMka8Ek+nmLNMEtds77ttcGQRdu16\n+vT1iualiCJe+/iMbl+PiJtFwhEHECLU9QfgBVS6r2lDAlZA+w6nwCRiidlrObzO\nCXqVOzN3fwKBgAsrOuu//bClHP0ChnCReO38aU+1/gWnDiOOnKVq0DXhAiaOzD1P\nqAG6hZlEkFBDMPWzq62doKv+gPgpRkfmV0DenHuYnGrrHdG3p2IxYoCSuq/QupPA\nPpU+xjDMhpQI30zuu4/rQq+/yDl4+aoSKYB3xAtb0Zxg6dMU8QpZ/hmnAoGBAIFu\nIesbcQR7O8FGkMrmxZweNNrYCtQ57R/WU/FImWm6OnJGNmsMO6Q2jJiT12RKKjg8\nOxrYGz7vTfOIDOddyAiPhXPUSyyF/3uvCrIzUUsmeeUJ8xq9dVwQ5HS3pYuKVfDg\nXYHbG4w9UJaF1A+3xEdUsYglSLouo7z/67zH9tZXAoGBAKpsdjSd3R+llaAv2HQ8\nGMlN92UTr5i9w++QMXq4qspH5NEYqz3NHbKuYthZqxEsRUZbRP50eDWU4jvxFVJl\nLBFINp6B+3AsIme0YCyOaleB/Cy0347miSinSv2I6QiH6dQxHdHzrG+x1evS/76f\nKT0KS+ySjCAEWgg4v+mjUDUV\n-----END PRIVATE KEY-----\n',
    response_condition: '',
  });

  // optional, but speeds up end of process
  await service_1.discard();
  await service_2.discard();
});

Promises

Purge all domains of the active version:

  1. Get all the versions.
  2. Filter out the active version.
  3. Get all the domains for the active version.
  4. Purge all the domains.
  5. Log the status text for each purge request.
const fastly = require('fastly-native-promises');

const service = fastly('token', 'service_id');

function handler() {
  service.readVersions()
    .then(versions => {
      const active = versions.data.filter(version => version.active)[0];
      return service.readDomains(active.number);
    })
    .then(domains => {
      return Promise.all(domains.data.map(domain => service.purgeIndividual(domain.name)));
    })
    .then(purges => {
      purges.forEach(purge => console.log(purge.statusText));
    })
    .catch(e => {
      console.log('Shoot!');
    });
}

Async/Await

Update first_byte_timeout property for every backend and service if the value is less than 5000 milliseconds:

  1. Get all the services associated with the Fastly API token.
  2. Filter out the service IDs.
  3. Iterate over all services synchronously.
  4. Get all the versions.
  5. Filter out the active version.
  6. Get all the backends for the active version.
  7. Filter out the affected backends.
  8. Continue with the next service if there are no affected backends.
  9. Clone the active version.
  10. Update all the affected backends parallelly.
  11. Activate the cloned version.
const fastly = require('fastly-native-promises');

const account = fastly('token');

async function handler() {
  try {
    const services = await account.readServices();
    const ids = services.data.map(service => service.id);

    for (const id of ids) {
      const service = fastly('token', id);
      const versions = await service.readVersions();
      const active = versions.data.filter(version => version.active)[0];
      const backends = await service.readBackends(active.number);
      const affected = backends.data.filter(backend => backend.first_byte_timeout < 5000);

      if (!affected.length) continue;

      const clone = await service.cloneVersion(active.number);
      await Promise.all(affected.map(backend => service.updateBackend(clone.data.number, backend.name, { first_byte_timeout: 5000 })));
      await service.activateVersion(clone.data.number);
    }
  } catch (e) {
    console.log('Shoot!');
  }
}

Response Schema

Each fastly-native-promises API method returns the following response object:

{
  // the HTTP status code from the server response
  status: 200,

  // the HTTP status message from the server response
  statusText: 'OK',

  // the headers that the server responded with
  headers: {},

  // the options that were provided to request for the request
  config: {},

  // the request that generated the response
  request: {},

  // the response that was provided by the server
  data: {}
}

Retrieving Request Statistics

The Fastly instance has a requestmonitor property that can be used to retrieve request statistics:

  • requestmonitor.count for the total number of requests.
  • requestmonitor.remaining for the number of requests remaining according to Fastly's API Rate limit for the hour or undefined (if no modifying requests have been made yet).
  • requestmonitor.edgedurations for an array of API processing durations (in milliseconds, measured from the edge).
  • requestmonitor.durations for an array of request durations (in milliseconds, measured from the client, i.e. including network latency).

With requestmonitor.stats you can get all of that in one object, including minimum, maximum and mean durations for all requests.

Guarding against Rate Limits

Using the requestmonitor.remaining property, you can make sure that you still have sufficient requests before you hit the rate limit.

When using the instance.transact method, you can furthermore provide a minimum for the necessary available request limit so that after the initial cloning of the version no additional requests will be made if the API rate limit will be exceeded. This allows you to fail fast in case of rate limit issues.

High-Level Helpers

While most functionality is a low-level wrapper of the Fastly, API, we provide a couple of higher-level helper functions in properties of the Fastly instance.

Conditions Helper in fastly.conditions

The conditions helper eases the creation and management of conditions.

const fastly = require('fastly-native-promises');

const instance = fastly('mykey', 'service-config');

const update = fastly.conditions.update(1, 'REQUEST', 'Created as an Example', 'example');

const conditions = await update('req.url.basename == "new.html"', 'req.url.basename == "index.html"');

console.log('Created a condition matching index.html with following name', conditions['req.url.basename == "index.html"'].name);

fastly.conditions.update can be called with the parameters version (service config version), type (condition type, either REQUEST, RESPONSE, or CACHE), comment (a comment that will be visible in the Fastly UI), nameprefix (a common prefix for the condition name) to get a new function update that performs the update.

When update is called with a list of statements in VCL condition language, it will synchronize the list of conditions passed in with the conditions that already exist in the Fastly service config. All conditions that share the same nameprefix, but are no longer used get deleted, new conditions that don't exist yet will get created (unchanged conditions aren't touched, reducing the number of requests made upon updates).

The return value of update is an object that maps condition statement to the condition object. This allows re-using the condition in other Fastly API calls.

Header Helper in fastly.headers

The headers helper eases the creation and management of conditional headers.

const fastly = require('fastly-native-promises');

const instance = fastly('mykey', 'service-config');

const update = fastly.headers.update(
  1,
  'REQUEST', // apply a request condition
  'Created as an Example', // use following comment for conditions
  'example', // name-prefix for all generated conditions and headers
  'set', // set the header
  'http.Location' // which header (Location)
  'request' // in the request handling
  );

await update(
    {
      condition: 'req.url.basename == "new.html"',
      expression: '"https://new.example.com"',
    },
    {
      condition: 'req.url.basename == "index.html"',
      expression: 'https://www.example.com',
    });

fastly.headers.update can be called with the parameters version (service config version), type (condition type, either REQUEST, RESPONSE, or CACHE), comment (a comment that will be visible in the Fastly UI), nameprefix (a common prefix for the condition name), action (what to do with the header, can be set, append, or delete), header (the name of the header – remember to include http. in the value), sub (the subroutine where the header is applied, can be request, fetch, cache, or response) to get a new function update that performs the update.

When update is called with a list of objects that looks like { condition: 'req.url ~ "foo/(.*)/bar"', expression: '"bar/" + re.group.1 + "/foo"'}, i.e. pairs of a condition (in VCL condition language) and an expression (also valid VCL), it will synchronize the list of headers (and resultant conditions) passed in with the headers and conditions that already exist in the Fastly service config. All conditions and headers that share the same nameprefix, but are no longer used get deleted, new conditions and headers that don't exist yet will get created (unchanged conditions and headers aren't touched, reducing the number of requests made upon updates).

API

Classes

AccountAPI : AccountAPI

The Fastly Account API.

AuthAPI : AuthAPI

The Fastly Auth API.

DomainAPI : DomainAPI

The Fastly Domain API.

HealthcheckAPI : HealthcheckAPI

The Fastly Healthcheck API.

PurgeAPI : PurgeAPI

The Fastly Purge API.

Conditions

Helper class with high-level operations for condition-management.

Headers

Helper class with high-level operations for condition-management.

Fastly

Functions

repeat(responseOrError)boolean

Determines if a response or error indicates that the response is repeatable.

Typedefs

CreateFunctionPromise

A function that creates a resource of a specific type. If a resource of that name already exists, it will reject the returned promise with an error.

UpdateFunctionPromise

A function that updates an already existing resource of a specific type. If no resource of that name exists, it will reject the returned promise with an error.

ReadFunctionPromise

A function that retrieves a representation of a resource of a specific type. If no resource of that name exists, it will reject the returned promise with an error.

ListFunctionPromise

A function that retrieves a list of resources of a specific type.

FastlyError : object

The FastlyError class describes the most common errors that can occur when working with the Fastly API. Using error.status, the underlying HTTP status code can be retrieved. Known error status codes include:

  • 400: attempting to activate invalid VCL
  • 401: invalid credentials
  • 404: resource not found
  • 409: confict when trying to POST a resource that already exists
  • 422: attempting to modify a service config that is not checked out
  • 429: rate limit exceeded, try again later
Response : object
Versions : object

Describes the most relevant versions of the service.

DictUpdate : object

Specifies a dictionary update operation. In most cases, upsert is the best way to update values, as it will work for existing and non-existing items.

Snippet : object
VCL : object

AccountAPI : AccountAPI

The Fastly Account API.

Kind: global class
See: https://docs.fastly.com/api/account#top

accountAPI.readCurrentUser() ⇒ Promise

Get the currently logged in user.

Kind: instance method of AccountAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/account#user_91db9d9178f3f4c7597899942bd3f941

accountAPI.readUsers() ⇒ Promise

Get a list of all users from the current customer.

Kind: instance method of AccountAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/account#customer_12f4a69627ba3bbb1c8668aae03a60ad

accountAPI.readUser(id) ⇒ Promise

Get the the user with the specific id.

Kind: instance method of AccountAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/account#user_15a6c72980b9434ebb8253c7e882c26c

ParamTypeDescription
idstringThe User ID.

accountAPI.createUser(name, login) ⇒ Promise

Create a user.

Kind: instance method of AccountAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/account#user_00b606002596bac1c652614de98bd260

ParamTypeDescription
namestringThe user name.
loginstringThe user login.

accountAPI.readInvitations() ⇒ Promise

List all invitations.

Kind: instance method of AccountAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/account#invitations_6d8623de97ed7e50b7b6498e374bb657

accountAPI.createInvitation(email, role) ⇒ Promise

Create an invitation.

Kind: instance method of AccountAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/account#invitations_8c4da3ca11c75facd36cfaad024bd891

ParamTypeDefaultDescription
emailstringThe email address for the invitation.
rolestring&quot;engineer&quot;The user role. Defaults to {@code engineer}.

accountAPI.acceptInvitation(acceptCode, name, password) ⇒ Promise

Accept an invitation.

Kind: instance method of AccountAPI
Returns: Promise - The response object representing the completion or failure.

ParamTypeDescription
acceptCodestringThe accept code retrieved in the email.
namestringName for the new user.
passwordstringPassword for the new user.

accountAPI.deleteInvitation(id) ⇒ Promise

Delete an invitation.

Kind: instance method of AccountAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/account#invitations_d70a7460c7e1bd8dd660c6f5b3558c2e

ParamTypeDescription
idstringThe invitation id.

AuthAPI : AuthAPI

The Fastly Auth API.

Kind: global class
See: https://docs.fastly.com/api/auth#top

authAPI.readTokens([customerId]) ⇒ Promise

List all tokens of a customer.

Kind: instance method of AuthAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/auth#tokens_d59ff8612bae27a2317278abb048db0c

ParamTypeDescription
[customerId]stringThe id of the customer.

authAPI.readToken([id]) ⇒ Promise

Get the token with the specified id. If the Id is missing, the self token is returned.

Kind: instance method of AuthAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/auth#tokens_bb00e7ed542cbcd7f32b5c908b8ce244

ParamTypeDescription
[id]stringThe token id.

authAPI.deleteToken([id]) ⇒ Promise

Delete the token with the specified id.

Kind: instance method of AuthAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/auth#tokens_4a958ba69402500937f0d8570f7ce86f

ParamTypeDescription
[id]stringThe token id.

authAPI.createToken(options) ⇒ Promise

Create an API token.

Kind: instance method of AuthAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/auth#tokens_db4655a45a0107448eb0676577446e40

ParamTypeDescription
optionsobjectThe token options.

DomainAPI : DomainAPI

The Fastly Domain API.

Kind: global class
See: https://docs.fastly.com/api/config#domain

domainAPI.domainCheck(version, name) ⇒ Promise

Checks the status of all domains for a particular service and version.

Kind: instance method of DomainAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#domain_30a3f14c9a0ce5730757d39983ab7dc6

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the domain.

domainAPI.domainCheckAll(version) ⇒ Promise

Checks the status of all domains for a particular service and version.

Kind: instance method of DomainAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#domain_e33a599694c3316f00b6b8d53a2db7d9

ParamTypeDescription
versionstringThe current version of a service.

Example

instance.domainCheckAll('182')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

domainAPI.readDomains(version) ⇒ Promise

List all the domains for a particular service and version.

Kind: instance method of DomainAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#domain_6d340186666771f022ca20f81609d03d

ParamTypeDescription
versionstringThe current version of a service.

Example

instance.readDomains('182')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

domainAPI.readDomain(version, name) ⇒ Promise

List all the domains for a particular service and version.

Kind: instance method of DomainAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#domain_f1b5fab17a0729daeeaf7594b47759c5

ParamTypeDescription
versionstringThe current version of a service.
namestringThe domain name.

domainAPI.readServiceDomains([serviceId]) ⇒ Promise

List the domains within a service.

Kind: instance method of DomainAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#service_d5578a1e3bc75512711ddd0a58ce7a36

ParamTypeDescription
[serviceId]stringThe service id.

domainAPI.createDomain(version, name, comment) ⇒ Promise

Create a domain for a particular service and version.

Kind: instance method of DomainAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#domain_90345101274774ff1b84f0a7dd010b01

ParamTypeDescription
versionstringThe current version of a service.
namestringThe domain name.
commentstringOptional comment.

domainAPI.updateDomain(version, oldName, name, comment) ⇒ Promise

Update a domain for a particular service and version.

Kind: instance method of DomainAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#domain_2ef42bd9b4c56c86b46dc0e36096ab10

ParamTypeDescription
versionstringThe current version of a service.
oldNamestringThe old name of the domain.
namestringThe domain name.
commentstringOptional comment.

domainAPI.deleteDomain(version, name) ⇒ Promise

Delete the domain for a particular service and version.

Kind: instance method of DomainAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#domain_aab5a322f58df2b1db8dc276e8594a70

ParamTypeDescription
versionstringThe current version of a service.
namestringThe domain name.

HealthcheckAPI : HealthcheckAPI

The Fastly Healthcheck API.

Kind: global class
See: https://docs.fastly.com/api/config#healthcheck

healthcheckAPI.readHealthchecks(version) ⇒ Promise

List all healthchecks for a particular service and version.

Kind: instance method of HealthcheckAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#healthcheck_126cb37382d68583269420ba772ded36

ParamTypeDescription
versionstringThe current version of a service.

healthcheckAPI.readHealthcheck(version, name) ⇒ Promise

Get details of a single named healthcheck.

Kind: instance method of HealthcheckAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#healthcheck_b54ea357a2377e62ae7649e609b94966

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the healthcheck.

healthcheckAPI.createHealthcheck(version, data) ⇒ Promise

Create a healthcheck for a particular service and version.

Kind: instance method of HealthcheckAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#healthcheck_8712be8923dd419c54393da3ac31f6d3

ParamTypeDescription
versionstringThe current version of a service.
dataobjectThe healthcheck definition.

healthcheckAPI.updateHealthcheck(version, name, data) ⇒ Promise

Update the healthcheck for a particular service and version.

Kind: instance method of HealthcheckAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#healthcheck_9a60b6005125c4afeaa80111e69d7586

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the healthcheck to update.
dataobjectThe healthcheck definition.

healthcheckAPI.deleteHealthcheck(version, name) ⇒ Promise

Delete the healthcheck for a particular service and version.

Kind: instance method of HealthcheckAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#healthcheck_a22900c40a2fd59db5028061dc5dfa36

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the healthcheck to delete.

PurgeAPI : PurgeAPI

The Fastly Purge API.

Kind: global class
See: https://docs.fastly.com/api/purge#purge

purgeAPI.purgeIndividual(url) ⇒ Promise

Instant Purge an individual URL.

Kind: instance method of PurgeAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/purge#purge_3aa1d66ee81dbfed0b03deed0fa16a9a

ParamTypeDescription
urlstringThe URL to purge.

Example

instance.purgeIndividual('www.example.com')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.purgeAll() ⇒ Promise

Instant Purge everything from a service.

Kind: instance method of PurgeAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/purge#purge_bee5ed1a0cfd541e8b9f970a44718546
Example

instance.purgeAll()
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.purgeKey(key) ⇒ Promise

Instant Purge a particular service of items tagged with a Surrogate Key.

Kind: instance method of PurgeAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/purge#purge_d8b8e8be84c350dd92492453a3df3230

ParamTypeDescription
keystringThe surrogate key to purge.

Example

instance.purgeKey('key_1')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.purgeKeys(keys) ⇒ Promise

Instant Purge a particular service of items tagged with Surrogate Keys in a batch.

Kind: instance method of PurgeAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/purge#purge_db35b293f8a724717fcf25628d713583

ParamTypeDescription
keysArrayThe array of surrogate keys to purge.

Example

instance.purgeKeys(['key_2', 'key_3', 'key_4'])
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.softPurgeIndividual(url) ⇒ Promise

Soft Purge an individual URL.

Kind: instance method of PurgeAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/purge#softpurge0c4f56f3d68e9bed44fb8b638b78ea36

ParamTypeDescription
urlstringThe URL to soft purge.

Example

instance.softPurgeIndividual('www.example.com/images')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.softPurgeKey(key) ⇒ Promise

Soft Purge a particular service of items tagged with a Surrogate Key.

Kind: instance method of PurgeAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/purge#softpurge2e4d29085640127739f8467f27a5b549

ParamTypeDescription
keystringThe surrogate key to soft purge.

Example

instance.softPurgeKey('key_5')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

purgeAPI.softPurgeKeys(keys) ⇒ Promise

Soft Purge a particular service of items tagged with Surrogate Keys in a batch.

Kind: instance method of PurgeAPI
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/purge#purge_db35b293f8a724717fcf25628d713583

ParamTypeDescription
keysArrayThe array of surrogate keys to purge.

Example

instance.softPurgeKeys(['key_2', 'key_3', 'key_4'])
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

Conditions

Helper class with high-level operations for condition-management.

Kind: global class

conditions.multistepupdate(version, type, commentprefix, nameprefix) ⇒ Array.&lt;function()&gt;

Creates functions for multi-step creation of missing and deletion of superflous conditions.

Kind: instance method of Conditions
Returns: Array.&lt;function()&gt; - A pair of a create and cleanup function.

ParamTypeDescription
versionnumberService config version.
typestringCondition type, can be REQUEST, RESPONSE, or CACHE.
commentprefixstringThe prefix to be used for comments.
nameprefixstring- The prefix to be used for names.

Headers

Helper class with high-level operations for condition-management.

Kind: global class

headers.update(version, type, commentprefix, nameprefix, action, header, sub) ⇒ Array.&lt;function()&gt;

Creates functions for multi-step creation of missing and deletion of superflous conditional headers.

Kind: instance method of Headers
Returns: Array.&lt;function()&gt; - A pair of a create and cleanup function.

ParamTypeDescription
versionnumberService config version.
typestringCondition type, can be REQUEST, RESPONSE, or CACHE.
commentprefixstringThe prefix to be used for comments.
nameprefixstring- The prefix to be used for names.
actionstringWhat do do with the header, can be set, append, delete.
headerstringThe name of the header to set.
substringName of the subroutine where the header should be applied, can be request, fetch, cache, or response.

Fastly

Kind: global class

new Fastly(token, service_id, timeout)

The constructor method for creating a fastly-promises instance.

ParamTypeDefaultDescription
tokenstringThe Fastly API token.
service_idstringThe Fastly service ID.
timeoutnumber15000HTTP timeout for requests to the Fastly API, default: 15 seconds.

fastly.readLogsFn(service) ⇒ ListFunction

Create a new function that lists all log configurations for a given service and version. The function can be parametrized with the name of the logging service.

Kind: instance method of Fastly
Returns: ListFunction - A logging function.

ParamTypeDescription
servicestringThe id of the logging service. Supported services are: s3, s3canary, azureblob, cloudfiles, digitalocean, ftp, bigquery, gcs, honeycomb, logshuttle, logentries, loggly, heroku, https, openstack, papertrail, scalyr, splunk, sumologic, syslog.

fastly.readLogFn(service) ⇒ ReadFunction

Create a new function that returns a named log configuration for a given service and version. The function can be parametrized with the name of the logging service.

Kind: instance method of Fastly
Returns: ReadFunction - A logging function.

ParamTypeDescription
servicestringThe id of the logging service. Supported services are: s3, s3canary, azureblob, cloudfiles, digitalocean, ftp, bigquery, gcs, honeycomb, logshuttle, logentries, loggly, heroku, https, openstack, papertrail, scalyr, splunk, sumologic, syslog.

fastly.createLogFn(service) ⇒ CreateFunction

Create a new function that creates a named log configuration for a given service and version. The function can be parametrized with the name of the logging service.

Kind: instance method of Fastly
Returns: CreateFunction - A logging function.

ParamTypeDescription
servicestringThe id of the logging service. Supported services are: s3, s3canary, azureblob, cloudfiles, digitalocean, ftp, bigquery, gcs, honeycomb, logshuttle, logentries, loggly, heroku, https, openstack, papertrail, scalyr, splunk, sumologic, syslog.

fastly.updateLogFn(service) ⇒ UpdateFunction

Create a new function that updates a named log configuration for a given service and version. The function can be parametrized with the name of the logging service.

Kind: instance method of Fastly
Returns: UpdateFunction - A logging function.

ParamTypeDescription
servicestringThe id of the logging service. Supported services are: s3, s3canary, azureblob, cloudfiles, digitalocean, ftp, bigquery, gcs, honeycomb, logshuttle, logentries, loggly, heroku, https, openstack, papertrail, scalyr, splunk, sumologic, syslog.

fastly.upsertFn(createFn, updateFn, readFn) ⇒ UpdateFunction

Creates an update-or-create or "safe create" function that will either create (if it does not exist) or update (if it does) a named resource. The function will attempt to check if the resource exists first (if a reader function has been provided), alternatively, it will just blindly create and fall back with an update.

Kind: instance method of Fastly
Returns: UpdateFunction - An update function that does not fail on conflict.

ParamTypeDescription
createFnCreateFunctionA function that creates a resource.
updateFnUpdateFunctionA function that updates a resource.
readFnReadFunctionAn optional function that checks for the existence of a resource.

fastly.discard()

Free resources bound to the HTTP client (pending sessions/sockets) and allow the node process to quit.

Kind: instance method of Fastly
Returns: Promise - A promise which resolves when all resources have been freed.

fastly.dataCenters() ⇒ Promise

Get a list of all Fastly datacenters.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/tools#datacenter_1c8d3b9dd035e301155b44eae05e0554
Example

instance.dataCenters()
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.publicIpList() ⇒ Promise

Fastly's services IP ranges.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/tools#publiciplist_ef2e9900a1c9522b58f5abed92ec785e
Example

instance.publicIpList()
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.edgeCheck(url) ⇒ Promise

Retrieve headers and MD5 hash of the content for a particular URL from each Fastly edge server.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/tools#content_4d2d4548b29c7661e17ebe7098872d6d

ParamTypeDescription
urlstringFull URL (host and path) to check on all nodes. If protocol is omitted, http will be assumed.

Example

instance.edgeCheck('api.example.com')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readServices() ⇒ Promise

List all services.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#service_74d98f7e5d018256e44d1cf820388ef8
Example

instance.readServices()
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readServicesById() ⇒ Promise

Reads the services and returns a data object that contains a map where the service id is the key.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.

fastly.readService([serviceId]) ⇒ Promise

Get a specific service by id.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#service_a884a9abd5af9723f6fcbb1ed13ae4cc

ParamTypeDescription
[serviceId]stringThe service id.

fastly.readVersions() ⇒ Promise

List the versions for a particular service.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#version_dfde9093f4eb0aa2497bbfd1d9415987
Example

instance.readVersions()
   .then(res => {
     const active = res.data.filter(version => version.active);
     console.log(active);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.getVersions() ⇒ Versions

Gets the version footprint for the service.

Kind: instance method of Fastly
Returns: Versions - The latest, current, and active versions of the service.

fastly.cloneVersion(version) ⇒ Promise

Clone the current configuration into a new version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#version_7f4937d0663a27fbb765820d4c76c709

ParamTypeDescription
versionstringThe version to be cloned.

Example

instance.cloneVersion('45')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.activateVersion(version) ⇒ Promise

Activate the current version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#version_0b79ae1ba6aee61d64cc4d43fed1e0d5

ParamTypeDescription
versionstringThe version to be activated.

Example

instance.activateVersion('23')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readDictItems(version, name) ⇒ Promise

List all dictionary items for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionaryitema48de28cd7e76c1ea58523f39bb7204b

ParamTypeDescription
versionstringThe version of the dictionary.
namestringThe name of the dictionary.

Example

instance.readDictItems(1, 'my_dictionary')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readDictItem(version, name, key) ⇒ Promise

Get details of a single dictionary item.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionaryitem08f090cd03ed4602ae63f131087e2f29

ParamTypeDescription
versionstringThe current version of a service.
namestringName of the dictionary.
keystringThe key to retrieve values by.

Example

instance.readDictItem('12', 'extensions', 'some_key')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.createDictItem(version, name, key, value) ⇒ Promise

Create a new dictionary item for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The reponse object.
See: https://docs.fastly.com/api/config#dictionaryitem6ec455c0ba1b21671789e1362bc7fe55

ParamTypeDescription
versionnumberThe version number (current if omitted).
nameobjectThe dictionary definition.
keystringThe key.
valuestringThe value to write.

fastly.bulkUpdateDictItems(version, name, …items) ⇒ Promise

Updates multiple dictionary items in bulk.

Kind: instance method of Fastly
Returns: Promise - The response object.

ParamTypeDescription
versionnumberThe version numer (current if ommitted).
namestringName of the dictionary.
…itemsDictUpdateThe dictionary update operations.

Example

// single item
fastly.bulkUpdateDictItems(1, 'secret_dictionary',
  { item_key: 'some_key', item_value: 'some_value', op: 'upsert' });

// multiple items
fastly.bulkUpdateDictItems(1, 'secret_dictionary',
  { item_key: 'some_key', item_value: 'some_value', op: 'update' },
  { item_key: 'other_key', item_value: 'other_value', op: 'update' });

fastly.updateDictItem(version, name, key, value) ⇒ Promise

Update a dictionary item value for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionaryitem34c884a7cdce84dfcfd38dac7a0b5bb0

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the dictionary.
keystringThe key to update data under.
valuestringThe value to update the dictionary with.

Example

instance.updateDictItem(1, 'extensions', 'html', 'text/html')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.deleteDictItem(version, name, key) ⇒ Promise

Delete a dictionary item for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionaryitem664347e743b8eafc9a93c729d9da0427

ParamTypeDescription
versionstringThe current version of a service.
namestringThe name of the dictionary.
keystringThe key to update data under.

Example

instance.deleteDictItem('34', 'extensions', 'html')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.writeDictItem(version, name, key, value) ⇒ Promise

Safely create, update or delete a dictionary item in a named dictionary.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.

ParamTypeDescription
versionnumberService version to use for dictionary lookup.
namestringName of the dictionary (not ID).
keystringKey to create, update or delete.
valuestringValue to update. Empty strings will delete the dictionary entry.

fastly.readDictionaries(version) ⇒ Promise

List all dictionaries for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionary_6d2cc293b994eb8c16d93e92e91f3915

ParamTypeDescription
versionstringThe current version of a service.

Example

instance.readDictionaries('12')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.readDictionary(version, name) ⇒ Promise

Get details of a single dictionary.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionary_0e16df083830ed3b6c30b73dcef64014

ParamTypeDescription
versionstringThe current version of a service.
namestringName of the dictionary.

Example

instance.readDictionary('12', 'extensions')
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message);
   });

fastly.createDictionary(version, data) ⇒ Promise

Create a new dictionary for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The reponse object.
See: https://docs.fastly.com/api/config#dictionary_7d48b87bf82433162a3b209292722125

ParamTypeDescription
versionnumberThe version number (current if omitted).
dataobjectThe dictionary definition.

fastly.updateDictionary(version, name, data) ⇒ Promise

Update a dictionary for a particular service and version.

Kind: instance method of Fastly
Returns: Promise - The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionary_8c9da370b1591d99e5389143a5589a32

ParamTypeDescription
versionstringThe current version of a s
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文