@adobe/fastly-native-promises 中文文档教程
fastly-native-promises
用于 Node.js
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
清除活动版本的所有域:
- Get all the versions.
- Filter out the active version.
- Get all the domains for the active version.
- Purge all the domains.
- 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
属性:
- Get all the services associated with the Fastly API token.
- Filter out the service IDs.
- Iterate over all services synchronously.
- Get all the versions.
- Filter out the active version.
- Get all the backends for the active version.
- Filter out the affected backends.
- Continue with the next service if there are no affected backends.
- Clone the active version.
- Update all the affected backends parallelly.
- 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 orundefined
(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>、
RESPONSE
或 CACHE
)、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>、
RESPONSE
或 CACHE
)、comment
(将在 Fastly UI 中显示的注释)、nameprefix< /code>(条件名称的通用前缀)、
action
(对标头做什么,可以是set
、append
,或者delete
), header
(header 的名称——记得在值中包含 http.
), sub
(应用header的子程序,可以是request
,fetch
,cache
,或者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
- CreateFunction ⇒
Promise
创建特定类型资源的函数。 如果那个资源 name 已经存在,它将拒绝返回的错误承诺。
- UpdateFunction ⇒
Promise
更新特定类型的现有资源的函数。 如果不存在该名称的资源,它将拒绝返回的承诺并出错。
- ReadFunction ⇒
Promise
检索特定类型资源表示的函数。 如果不存在该名称的资源,它将拒绝返回的承诺并出错。
- ListFunction ⇒
Promise
检索特定类型资源列表的函数。
- 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:
- AccountAPI :
AccountAPI
- .readCurrentUser() ⇒
Promise
- .readUsers() ⇒
Promise
- .readUser(id) ⇒
Promise
- .createUser(name, login) ⇒
Promise
- .readInvitations() ⇒
Promise
- .createInvitation(email, role) ⇒
Promise
- .acceptInvitation(acceptCode, name, password) ⇒
Promise
- .deleteInvitation(id) ⇒
Promise
- .readCurrentUser() ⇒
//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:
Param | Type | Description |
---|---|---|
id | string | The User ID. |
//docs.fastly.com/api/account#user_15a6c72980b9434ebb8253c7e882c26c
accountAPI.createUser(name, login) ⇒ Promise
创建一个用户。
种类:AccountAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
name | string | The user name. |
login | string | The 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:
Param | Type | Default | Description |
---|---|---|---|
string | The email address for the invitation. | ||
role | string | "engineer" | The user role. Defaults to {@code engineer}. |
//docs.fastly.com/api/account#invitations_8c4da3ca11c75facd36cfaad024bd891
accountAPI.acceptInvitation(acceptCode, name, password) ⇒ Promise
接受邀请。
种类:AccountAPI
的实例方法 Returns:Promise
- 表示完成或失败的响应对象。
Param | Type | Description |
---|---|---|
acceptCode | string | The accept code retrieved in the email. |
name | string | Name for the new user. |
password | string | Password for the new user. |
accountAPI.deleteInvitation(id) ⇒ Promise
删除邀请。
种类:AccountAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
id | string | The invitation id. |
//docs.fastly.com/api/account#invitations_d70a7460c7e1bd8dd660c6f5b3558c2e
AuthAPI : AuthAPI
Fastly Auth API。
种类:全局类
参见:https:
- AuthAPI :
AuthAPI
- .readTokens([customerId]) ⇒
Promise
- .readToken([id]) ⇒
Promise
- .deleteToken([id]) ⇒
Promise
- .createToken(options) ⇒
Promise
- .readTokens([customerId]) ⇒
//docs.fastly.com/api/auth#top
authAPI.readTokens([customerId]) ⇒ Promise
列出客户的所有令牌。
种类:AuthAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
[customerId] | string | The id of the customer. |
//docs.fastly.com/api/auth#tokens_d59ff8612bae27a2317278abb048db0c
authAPI.readToken([id]) ⇒ Promise
获取指定id的token。 如果缺少 Id,则返回自身令牌。
种类:AuthAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
[id] | string | The token id. |
//docs.fastly.com/api/auth#tokens_bb00e7ed542cbcd7f32b5c908b8ce244
authAPI.deleteToken([id]) ⇒ Promise
删除具有指定 id 的令牌。
种类:AuthAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
[id] | string | The token id. |
//docs.fastly.com/api/auth#tokens_4a958ba69402500937f0d8570f7ce86f
authAPI.createToken(options) ⇒ Promise
创建 API 令牌。
种类:AuthAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
options | object | The token options. |
//docs.fastly.com/api/auth#tokens_db4655a45a0107448eb0676577446e40
DomainAPI : DomainAPI
Fastly Domain API。
种类:全局类
参见:https:
- DomainAPI :
DomainAPI
- .domainCheck(version, name) ⇒
Promise
- .domainCheckAll(version) ⇒
Promise
- .readDomains(version) ⇒
Promise
- .readDomain(version, name) ⇒
Promise
- .readServiceDomains([serviceId]) ⇒
Promise
- .createDomain(version, name, comment) ⇒
Promise
- .updateDomain(version, oldName, name, comment) ⇒
Promise
- .deleteDomain(version, name) ⇒
Promise
- .domainCheck(version, name) ⇒
//docs.fastly.com/api/config#domain
domainAPI.domainCheck(version, name) ⇒ Promise
检查特定服务和版本的所有域的状态.
种类:DomainAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the domain. |
//docs.fastly.com/api/config#domain_30a3f14c9a0ce5730757d39983ab7dc6
domainAPI.domainCheckAll(version) ⇒ Promise
检查特定服务和版本的所有域的状态.
种类:DomainAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The 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:
Param | Type | Description |
---|---|---|
version | string | The 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:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The domain name. |
//docs.fastly.com/api/config#domain_f1b5fab17a0729daeeaf7594b47759c5
domainAPI.readServiceDomains([serviceId]) ⇒ Promise
列出服务中的域。
种类:DomainAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
[serviceId] | string | The service id. |
//docs.fastly.com/api/config#service_d5578a1e3bc75512711ddd0a58ce7a36
domainAPI.createDomain(version, name, comment) ⇒ Promise
为特定服务和版本创建域。
种类:DomainAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The domain name. |
comment | string | Optional comment. |
//docs.fastly.com/api/config#domain_90345101274774ff1b84f0a7dd010b01
domainAPI.updateDomain(version, oldName, name, comment) ⇒ Promise
更新特定服务和版本的域。
种类:DomainAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
oldName | string | The old name of the domain. |
name | string | The domain name. |
comment | string | Optional comment. |
//docs.fastly.com/api/config#domain_2ef42bd9b4c56c86b46dc0e36096ab10
domainAPI.deleteDomain(version, name) ⇒ Promise
删除特定服务和版本的域。
种类:DomainAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The domain name. |
//docs.fastly.com/api/config#domain_aab5a322f58df2b1db8dc276e8594a70
HealthcheckAPI : HealthcheckAPI
Fastly Healthcheck API。
种类:全局类
参见:https:
- HealthcheckAPI :
HealthcheckAPI
- .readHealthchecks(version) ⇒
Promise
- .readHealthcheck(version, name) ⇒
Promise
- .createHealthcheck(version, data) ⇒
Promise
- .updateHealthcheck(version, name, data) ⇒
Promise
- .deleteHealthcheck(version, name) ⇒
Promise
- .readHealthchecks(version) ⇒
//docs.fastly.com/api/config#healthcheck
healthcheckAPI.readHealthchecks(version) ⇒ Promise
列出特定服务和版本的所有健康检查。
种类:HealthcheckAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
//docs.fastly.com/api/config#healthcheck_126cb37382d68583269420ba772ded36
healthcheckAPI.readHealthcheck(version, name) ⇒ Promise
获取单个命名健康检查的详细信息。
种类:HealthcheckAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the healthcheck. |
//docs.fastly.com/api/config#healthcheck_b54ea357a2377e62ae7649e609b94966
healthcheckAPI.createHealthcheck(version, data) ⇒ Promise
为特定服务和版本创建健康检查。
种类:HealthcheckAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
data | object | The healthcheck definition. |
//docs.fastly.com/api/config#healthcheck_8712be8923dd419c54393da3ac31f6d3
healthcheckAPI.updateHealthcheck(version, name, data) ⇒ Promise
更新特定服务和版本的健康检查。
种类:HealthcheckAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the healthcheck to update. |
data | object | The healthcheck definition. |
//docs.fastly.com/api/config#healthcheck_9a60b6005125c4afeaa80111e69d7586
healthcheckAPI.deleteHealthcheck(version, name) ⇒ Promise
删除特定服务和版本的健康检查。
种类:HealthcheckAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the healthcheck to delete. |
//docs.fastly.com/api/config#healthcheck_a22900c40a2fd59db5028061dc5dfa36
PurgeAPI : PurgeAPI
快速清除 API。
种类:全局类
参见:https:
- PurgeAPI :
PurgeAPI
- .purgeIndividual(url) ⇒
Promise
- .purgeAll() ⇒
Promise
- .purgeKey(key) ⇒
Promise
- .purgeKeys(keys) ⇒
Promise
- .softPurgeIndividual(url) ⇒
Promise
- .softPurgeKey(key) ⇒
Promise
- .softPurgeKeys(keys) ⇒
Promise
- .purgeIndividual(url) ⇒
//docs.fastly.com/api/purge#purge
purgeAPI.purgeIndividual(url) ⇒ Promise
即时清除单个 URL。
种类:PurgeAPI
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
url | string | The 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:
Param | Type | Description |
---|---|---|
key | string | The 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:
Param | Type | Description |
---|---|---|
keys | Array | The 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:
Param | Type | Description |
---|---|---|
url | string | The 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:
Param | Type | Description |
---|---|---|
key | string | The 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:
Param | Type | Description |
---|---|---|
keys | Array | The 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.<function()>
创建多步创建缺失和删除的函数 多余的条件。
Kind:Conditions
的实例方法 返回:Array.<function()>
- 一对创建和清理函数。
Param | Type | Description |
---|---|---|
version | number | Service config version. |
type | string | Condition type, can be REQUEST , RESPONSE , or CACHE . |
commentprefix | string | The prefix to be used for comments. |
nameprefix | string | - The prefix to be used for names. |
Headers
具有状态管理高级操作的辅助类。
headers.update(version, type, commentprefix, nameprefix, action, header, sub) ⇒ Array.<function()>
创建多步创建缺失和删除的函数 多余的条件标头。
Kind:Headers
的实例方法 返回:Array.<function()>
- 一对创建和清理函数。
Param | Type | Description |
---|---|---|
version | number | Service config version. |
type | string | Condition type, can be REQUEST , RESPONSE , or CACHE . |
commentprefix | string | The prefix to be used for comments. |
nameprefix | string | - The prefix to be used for names. |
action | string | What do do with the header, can be set , append , delete . |
header | string | The name of the header to set. |
sub | string | Name of the subroutine where the header should be applied, can be request , fetch , cache , or response . |
Fastly
Kind:全局类
- Fastly
- new Fastly(token, service_id, timeout)
- .readLogsFn(service) ⇒
ListFunction
- .readLogFn(service) ⇒
ReadFunction
- .createLogFn(service) ⇒
CreateFunction
- .updateLogFn(service) ⇒
UpdateFunction
- .upsertFn(createFn, updateFn, readFn) ⇒
UpdateFunction
- .discard()
- .dataCenters() ⇒
Promise
- .publicIpList() ⇒
Promise
- .edgeCheck(url) ⇒
Promise
- .readServices() ⇒
Promise
- .readServicesById() ⇒
Promise
- .readService([serviceId]) ⇒
Promise
- .readVersions() ⇒
Promise
- .getVersions() ⇒
Versions
- .cloneVersion(version) ⇒
Promise
- .activateVersion(version) ⇒
Promise
- .readDictItems(version, name) ⇒
Promise
- .readDictItem(version, name, key) ⇒
Promise
- .createDictItem(version, name, key, value) ⇒
Promise
- .bulkUpdateDictItems(version, name, …items) ⇒
Promise
- .updateDictItem(version, name, key, value) ⇒
Promise
- .deleteDictItem(version, name, key) ⇒
Promise
- .writeDictItem(version, name, key, value) ⇒
Promise
- .readDictionaries(version) ⇒
Promise
- .readDictionary(version, name) ⇒
Promise
- .createDictionary(version, data) ⇒
Promise
- .updateDictionary(version, name, data) ⇒
Promise
- .deleteDictionary(version, name) ⇒
Promise
- .readConditions(version) ⇒
Promise
- .readCondition(version, name) ⇒
Promise
- .readSnippet(version, name) ⇒
Promise
- .createCondition(version, data) ⇒
Promise
- .updateCondition(version, name, data) ⇒
Promise
- .deleteCondition(version, name) ⇒
Promise
- .readHeaders(version) ⇒
Promise
- .readHeader(version, name) ⇒
Promise
- .createHeader(version, data) ⇒
Promise
- .updateHeader(version, name, data) ⇒
Promise
- .deleteHeader(version, name) ⇒
Promise
- .readBackends(version) ⇒
Promise
- .updateBackend(version, name, data) ⇒
Promise
- .createBackend(version, data) ⇒
Promise
- .readSnippets(version) ⇒
Promise
- .createSnippet(version, data) ⇒
Promise
- .updateSnippet(version, name, data) ⇒
Promise
- .createVCL(version, data) ⇒
Promise
- .updateVCL(version, name, data) ⇒
Promise
- .setMainVCL(version, name) ⇒
Promise
- .transact(operations, activate, limit) ⇒
object
- .dryrun(operations) ⇒
object
new Fastly(token, service_id, timeout)
用于创建快速承诺实例的构造方法。
Param | Type | Default | Description |
---|---|---|---|
token | string | The Fastly API token. | |
service_id | string | The Fastly service ID. | |
timeout | number | 15000 | HTTP timeout for requests to the Fastly API, default: 15 seconds. |
fastly.readLogsFn(service) ⇒ ListFunction
创建一个新函数,列出给定服务的所有日志配置 和版本。 该函数可以使用日志记录的名称进行参数化 服务。
Kind:Fastly
的实例方法 返回:ListFunction
- 一个日志函数。
Param | Type | Description |
---|---|---|
service | string | The 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
创建一个新函数,返回给定服务的命名日志配置 和版本。 该函数可以使用日志记录的名称进行参数化 服务。
Kind:Fastly
的实例方法 返回:ReadFunction
- 一个日志函数。
Param | Type | Description |
---|---|---|
service | string | The 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
创建一个新函数,为给定服务创建命名日志配置 和版本。 该函数可以使用日志记录的名称进行参数化 服务。
Kind:Fastly
的实例方法 返回:CreateFunction
- 一个日志函数。
Param | Type | Description |
---|---|---|
service | string | The 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
创建一个新函数来更新给定服务的命名日志配置 和版本。 该函数可以使用日志记录的名称进行参数化 服务。
Kind:Fastly
的实例方法 返回:UpdateFunction
- 一个日志函数。
Param | Type | Description |
---|---|---|
service | string | The 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
创建一个更新或创建或“安全创建”函数,该函数将创建 (如果不存在)或更新(如果存在)命名资源。 功能 将首先尝试检查资源是否存在(如果阅读器功能已被 提供),或者,它只会盲目地创建并回退 更新。
Kind:Fastly
的实例方法 返回:UpdateFunction
- 不会因冲突而失败的更新函数。
Param | Type | Description |
---|---|---|
createFn | CreateFunction | A function that creates a resource. |
updateFn | UpdateFunction | A function that updates a resource. |
readFn | ReadFunction | An optional function that checks for the existence of a resource. |
fastly.discard()
绑定到 HTTP 客户端的免费资源(挂起的会话/套接字) 并允许节点进程退出。
Kind:Fastly
的实例方法 返回:Promise
- 当所有资源都被释放时解析的承诺。
fastly.dataCenters() ⇒ Promise
获取所有 Fastly 数据中心的列表。
Kind:Fastly
的实例方法 返回: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 范围。
Kind:Fastly
的实例方法 返回: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 哈希值。
Kind:Fastly
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
url | string | Full 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
列出所有服务。
Kind:Fastly
的实例方法 返回: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 所在的地图 钥匙。
Kind:Fastly
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
fastly.readService([serviceId]) ⇒ Promise
通过id获取特定服务。
Kind:Fastly
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
[serviceId] | string | The service id. |
//docs.fastly.com/api/config#service_a884a9abd5af9723f6fcbb1ed13ae4cc
fastly.readVersions() ⇒ Promise
列出特定服务的版本。
Kind:Fastly
的实例方法 返回: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
获取服务的版本足迹。
Kind:Fastly
的实例方法 返回:Versions
- 服务的最新、当前和活动版本。
fastly.cloneVersion(version) ⇒ Promise
将当前配置克隆到新版本中。
Kind:Fastly
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The 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
激活当前版本.
Kind:Fastly
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The 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
列出所有字典项对于特定的服务和版本。
Kind:Fastly
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The version of the dictionary. |
name | string | The 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
获取单个字典项的详细信息。
Kind:Fastly
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | Name of the dictionary. |
key | string | The 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
为特定服务和版本创建一个新的字典项。
Kind:Fastly
的实例方法 返回:Promise
- 响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | number | The version number (current if omitted). |
name | object | The dictionary definition. |
key | string | The key. |
value | string | The value to write. |
//docs.fastly.com/api/config#dictionaryitem 6ec455c0ba1b21671789e1362bc7fe55
fastly.bulkUpdateDictItems(version, name, …items) ⇒ Promise
更新多个字典散装物品。
Kind:Fastly
的实例方法 返回:Promise
- 响应对象。
Param | Type | Description |
---|---|---|
version | number | The version numer (current if ommitted). |
name | string | Name of the dictionary. |
…items | DictUpdate | The 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
更新特定服务和版本的字典项值。
Kind:Fastly
的实例方法 返回:Promise
- 表示完成或失败的响应对象。
参见:https:
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the dictionary. |
key | string | The key to update data under. |
value | string | The 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
删除特定服务和版本的字典项。
Kind:Fastly
的实例方法 Returns: Promise
- The response object representing the completion or failure.
See: https://docs.fastly.com/api/config#dictionaryitem664347e743b8eafc9a93c729d9da0427
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the dictionary. |
key | string | The 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.
Param | Type | Description |
---|---|---|
version | number | Service version to use for dictionary lookup. |
name | string | Name of the dictionary (not ID). |
key | string | Key to create, update or delete. |
value | string | Value 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
Param | Type | Description |
---|---|---|
version | string | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | Name 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
Param | Type | Description |
---|---|---|
version | number | The version number (current if omitted). |
data | object | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a s |
fastly-native-promises
Native Promise based Fastly API client for Node.js
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:
- Get all the versions.
- Filter out the active version.
- Get all the domains for the active version.
- Purge all the domains.
- 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:
- Get all the services associated with the Fastly API token.
- Filter out the service IDs.
- Iterate over all services synchronously.
- Get all the versions.
- Filter out the active version.
- Get all the backends for the active version.
- Filter out the affected backends.
- Continue with the next service if there are no affected backends.
- Clone the active version.
- Update all the affected backends parallelly.
- 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 orundefined
(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
- CreateFunction ⇒
Promise
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.
- UpdateFunction ⇒
Promise
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.
- ReadFunction ⇒
Promise
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.
- ListFunction ⇒
Promise
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 :
AccountAPI
- .readCurrentUser() ⇒
Promise
- .readUsers() ⇒
Promise
- .readUser(id) ⇒
Promise
- .createUser(name, login) ⇒
Promise
- .readInvitations() ⇒
Promise
- .createInvitation(email, role) ⇒
Promise
- .acceptInvitation(acceptCode, name, password) ⇒
Promise
- .deleteInvitation(id) ⇒
Promise
- .readCurrentUser() ⇒
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
Param | Type | Description |
---|---|---|
id | string | The 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
Param | Type | Description |
---|---|---|
name | string | The user name. |
login | string | The 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
Param | Type | Default | Description |
---|---|---|---|
string | The email address for the invitation. | ||
role | string | "engineer" | 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.
Param | Type | Description |
---|---|---|
acceptCode | string | The accept code retrieved in the email. |
name | string | Name for the new user. |
password | string | Password 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
Param | Type | Description |
---|---|---|
id | string | The invitation id. |
AuthAPI : AuthAPI
The Fastly Auth API.
Kind: global class
See: https://docs.fastly.com/api/auth#top
- AuthAPI :
AuthAPI
- .readTokens([customerId]) ⇒
Promise
- .readToken([id]) ⇒
Promise
- .deleteToken([id]) ⇒
Promise
- .createToken(options) ⇒
Promise
- .readTokens([customerId]) ⇒
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
Param | Type | Description |
---|---|---|
[customerId] | string | The 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
Param | Type | Description |
---|---|---|
[id] | string | The 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
Param | Type | Description |
---|---|---|
[id] | string | The 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
Param | Type | Description |
---|---|---|
options | object | The token options. |
DomainAPI : DomainAPI
The Fastly Domain API.
Kind: global class
See: https://docs.fastly.com/api/config#domain
- DomainAPI :
DomainAPI
- .domainCheck(version, name) ⇒
Promise
- .domainCheckAll(version) ⇒
Promise
- .readDomains(version) ⇒
Promise
- .readDomain(version, name) ⇒
Promise
- .readServiceDomains([serviceId]) ⇒
Promise
- .createDomain(version, name, comment) ⇒
Promise
- .updateDomain(version, oldName, name, comment) ⇒
Promise
- .deleteDomain(version, name) ⇒
Promise
- .domainCheck(version, name) ⇒
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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The 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
Param | Type | Description |
---|---|---|
version | string | The 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
Param | Type | Description |
---|---|---|
version | string | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The 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
Param | Type | Description |
---|---|---|
[serviceId] | string | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The domain name. |
comment | string | Optional 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
oldName | string | The old name of the domain. |
name | string | The domain name. |
comment | string | Optional 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The domain name. |
HealthcheckAPI : HealthcheckAPI
The Fastly Healthcheck API.
Kind: global class
See: https://docs.fastly.com/api/config#healthcheck
- HealthcheckAPI :
HealthcheckAPI
- .readHealthchecks(version) ⇒
Promise
- .readHealthcheck(version, name) ⇒
Promise
- .createHealthcheck(version, data) ⇒
Promise
- .updateHealthcheck(version, name, data) ⇒
Promise
- .deleteHealthcheck(version, name) ⇒
Promise
- .readHealthchecks(version) ⇒
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
Param | Type | Description |
---|---|---|
version | string | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
data | object | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the healthcheck to update. |
data | object | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the healthcheck to delete. |
PurgeAPI : PurgeAPI
The Fastly Purge API.
Kind: global class
See: https://docs.fastly.com/api/purge#purge
- PurgeAPI :
PurgeAPI
- .purgeIndividual(url) ⇒
Promise
- .purgeAll() ⇒
Promise
- .purgeKey(key) ⇒
Promise
- .purgeKeys(keys) ⇒
Promise
- .softPurgeIndividual(url) ⇒
Promise
- .softPurgeKey(key) ⇒
Promise
- .softPurgeKeys(keys) ⇒
Promise
- .purgeIndividual(url) ⇒
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
Param | Type | Description |
---|---|---|
url | string | The 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
Param | Type | Description |
---|---|---|
key | string | The 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
Param | Type | Description |
---|---|---|
keys | Array | The 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
Param | Type | Description |
---|---|---|
url | string | The 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
Param | Type | Description |
---|---|---|
key | string | The 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
Param | Type | Description |
---|---|---|
keys | Array | The 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.
conditions.multistepupdate(version, type, commentprefix, nameprefix) ⇒ Array.<function()>
Creates functions for multi-step creation of missing and deletion of superflous conditions.
Kind: instance method of Conditions
Returns: Array.<function()>
- A pair of a create and cleanup function.
Param | Type | Description |
---|---|---|
version | number | Service config version. |
type | string | Condition type, can be REQUEST , RESPONSE , or CACHE . |
commentprefix | string | The prefix to be used for comments. |
nameprefix | string | - The prefix to be used for names. |
Headers
Helper class with high-level operations for condition-management.
headers.update(version, type, commentprefix, nameprefix, action, header, sub) ⇒ Array.<function()>
Creates functions for multi-step creation of missing and deletion of superflous conditional headers.
Kind: instance method of Headers
Returns: Array.<function()>
- A pair of a create and cleanup function.
Param | Type | Description |
---|---|---|
version | number | Service config version. |
type | string | Condition type, can be REQUEST , RESPONSE , or CACHE . |
commentprefix | string | The prefix to be used for comments. |
nameprefix | string | - The prefix to be used for names. |
action | string | What do do with the header, can be set , append , delete . |
header | string | The name of the header to set. |
sub | string | Name of the subroutine where the header should be applied, can be request , fetch , cache , or response . |
Fastly
Kind: global class
- Fastly
- new Fastly(token, service_id, timeout)
- .readLogsFn(service) ⇒
ListFunction
- .readLogFn(service) ⇒
ReadFunction
- .createLogFn(service) ⇒
CreateFunction
- .updateLogFn(service) ⇒
UpdateFunction
- .upsertFn(createFn, updateFn, readFn) ⇒
UpdateFunction
- .discard()
- .dataCenters() ⇒
Promise
- .publicIpList() ⇒
Promise
- .edgeCheck(url) ⇒
Promise
- .readServices() ⇒
Promise
- .readServicesById() ⇒
Promise
- .readService([serviceId]) ⇒
Promise
- .readVersions() ⇒
Promise
- .getVersions() ⇒
Versions
- .cloneVersion(version) ⇒
Promise
- .activateVersion(version) ⇒
Promise
- .readDictItems(version, name) ⇒
Promise
- .readDictItem(version, name, key) ⇒
Promise
- .createDictItem(version, name, key, value) ⇒
Promise
- .bulkUpdateDictItems(version, name, …items) ⇒
Promise
- .updateDictItem(version, name, key, value) ⇒
Promise
- .deleteDictItem(version, name, key) ⇒
Promise
- .writeDictItem(version, name, key, value) ⇒
Promise
- .readDictionaries(version) ⇒
Promise
- .readDictionary(version, name) ⇒
Promise
- .createDictionary(version, data) ⇒
Promise
- .updateDictionary(version, name, data) ⇒
Promise
- .deleteDictionary(version, name) ⇒
Promise
- .readConditions(version) ⇒
Promise
- .readCondition(version, name) ⇒
Promise
- .readSnippet(version, name) ⇒
Promise
- .createCondition(version, data) ⇒
Promise
- .updateCondition(version, name, data) ⇒
Promise
- .deleteCondition(version, name) ⇒
Promise
- .readHeaders(version) ⇒
Promise
- .readHeader(version, name) ⇒
Promise
- .createHeader(version, data) ⇒
Promise
- .updateHeader(version, name, data) ⇒
Promise
- .deleteHeader(version, name) ⇒
Promise
- .readBackends(version) ⇒
Promise
- .updateBackend(version, name, data) ⇒
Promise
- .createBackend(version, data) ⇒
Promise
- .readSnippets(version) ⇒
Promise
- .createSnippet(version, data) ⇒
Promise
- .updateSnippet(version, name, data) ⇒
Promise
- .createVCL(version, data) ⇒
Promise
- .updateVCL(version, name, data) ⇒
Promise
- .setMainVCL(version, name) ⇒
Promise
- .transact(operations, activate, limit) ⇒
object
- .dryrun(operations) ⇒
object
new Fastly(token, service_id, timeout)
The constructor method for creating a fastly-promises instance.
Param | Type | Default | Description |
---|---|---|---|
token | string | The Fastly API token. | |
service_id | string | The Fastly service ID. | |
timeout | number | 15000 | HTTP 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.
Param | Type | Description |
---|---|---|
service | string | The 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.
Param | Type | Description |
---|---|---|
service | string | The 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.
Param | Type | Description |
---|---|---|
service | string | The 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.
Param | Type | Description |
---|---|---|
service | string | The 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.
Param | Type | Description |
---|---|---|
createFn | CreateFunction | A function that creates a resource. |
updateFn | UpdateFunction | A function that updates a resource. |
readFn | ReadFunction | An 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
Param | Type | Description |
---|---|---|
url | string | Full 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
Param | Type | Description |
---|---|---|
[serviceId] | string | The 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
Param | Type | Description |
---|---|---|
version | string | The 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
Param | Type | Description |
---|---|---|
version | string | The 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
Param | Type | Description |
---|---|---|
version | string | The version of the dictionary. |
name | string | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | Name of the dictionary. |
key | string | The 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
Param | Type | Description |
---|---|---|
version | number | The version number (current if omitted). |
name | object | The dictionary definition. |
key | string | The key. |
value | string | The 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.
Param | Type | Description |
---|---|---|
version | number | The version numer (current if ommitted). |
name | string | Name of the dictionary. |
…items | DictUpdate | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the dictionary. |
key | string | The key to update data under. |
value | string | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | The name of the dictionary. |
key | string | The 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.
Param | Type | Description |
---|---|---|
version | number | Service version to use for dictionary lookup. |
name | string | Name of the dictionary (not ID). |
key | string | Key to create, update or delete. |
value | string | Value 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
Param | Type | Description |
---|---|---|
version | string | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a service. |
name | string | Name 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
Param | Type | Description |
---|---|---|
version | number | The version number (current if omitted). |
data | object | The 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
Param | Type | Description |
---|---|---|
version | string | The current version of a s |