@adobe/fastly-native-promises
Promise based Fastly API client for Node.js
Last updated a month ago by adobe-admin .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install @adobe/fastly-native-promises 
SYNC missed versions from official npm registry.

fastly-native-promises

Native Promise based Fastly API client for Node.js

NPM Version Known Vulnerabilities codecov CircleCI GitHub license GitHub 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: '',
  });
});

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

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
email 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.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.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.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.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#soft_purge_0c4f56f3d68e9bed44fb8b638b78ea36

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#soft_purge_2e4d29085640127739f8467f27a5b549

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.

Kind: global class

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.

Kind: global class

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

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.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#public_ip_list_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#dictionary_item_a48de28cd7e76c1ea58523f39bb7204b

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#dictionary_item_08f090cd03ed4602ae63f131087e2f29

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#dictionary_item_6ec455c0ba1b21671789e1362bc7fe55

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#dictionary_item_34c884a7cdce84dfcfd38dac7a0b5bb0

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#dictionary_item_664347e743b8eafc9a93c729d9da0427

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 service.
name string The name of the dictionary.
data object The data to be sent as the request body.

Example

instance.updateDictionary('34', 'old-name', { name: 'new-name' })
   .then(res => {
     console.log(res.data);
   })
   .catch(err => {
     console.log(err.message

Current Tags

  • 1.16.0                                ...           latest (a month ago)

29 Versions

  • 1.16.0                                ...           a month ago
  • 1.15.1                                ...           2 months ago
  • 1.15.0                                ...           6 months ago
  • 1.14.2                                ...           7 months ago
  • 1.14.1                                ...           7 months ago
  • 1.14.0                                ...           8 months ago
  • 1.13.0                                ...           9 months ago
  • 1.12.0                                ...           10 months ago
  • 1.11.0                                ...           10 months ago
  • 1.10.0                                ...           a year ago
  • 1.9.1                                ...           a year ago
  • 1.9.0                                ...           a year ago
  • 1.8.1                                ...           a year ago
  • 1.8.0                                ...           a year ago
  • 1.7.0                                ...           a year ago
  • 1.6.1                                ...           a year ago
  • 1.6.0                                ...           a year ago
  • 1.5.0                                ...           a year ago
  • 1.4.0                                ...           a year ago
  • 1.3.2                                ...           a year ago
  • 1.3.1                                ...           a year ago
  • 1.3.0                                ...           a year ago
  • 1.2.0                                ...           a year ago
  • 1.1.2                                ...           a year ago
  • 1.1.1                                ...           a year ago
  • 1.1.0                                ...           a year ago
  • 1.0.3                                ...           a year ago
  • 1.0.2                                ...           a year ago
  • 1.0.1                                ...           a year ago

Copyright 2014 - 2016 © taobao.org |