UNPKG

@akamai-consulting/edgegrid-js-fetch

Version:

Signing and fetch library the Akamai OPEN EdgeGrid Authentication scheme in a JS environment that supports the fetch spec

75 lines (74 loc) 2.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const auth_1 = require("./auth"); const helpers_1 = require("./helpers"); const builtinFetch = fetch; /** Class representing an EdgeGrid request signer and fetcher. */ class EdgeGrid { #config; /** * Get the configuration object used for signing requests. * @returns {EdgeGridCredentials} The edgerc configuration object. */ get config() { return this.#config; } /** * Create an EdgeGridCredentials object. * @param {EdgeGridCredentials} credentials - The credentials used for signing requests */ constructor(credentials) { this.#config = credentials; } /** * Builds the request using the properties of the local config Object. * Follows the same signature as the WHATWG fetch spec * * @param {RequestInfo|URL} input - The Request Object or URL. * @param {RequestInit} init - An init object to include options such as heders and body. * * @returns Promise which resolves to a signed Request object */ async signRequest(input, init) { let requestToSign; if (input instanceof Request) { const url = new URL(input.url); //url.host = this.config.host; requestToSign = new Request(url, input); requestToSign = new Request(requestToSign, init); } else { const url = new URL(input, 'https://' + this.config.host); requestToSign = new Request(url, init); } let signedRequest = (0, auth_1.generateAuthedRequest)(requestToSign, this.config.clientToken, this.config.clientSecret, this.config.accessToken); return signedRequest; } /** * Signs and fetches the request using the properties of the local config Object. * Follows the same signature as the WHATWG fetch spec * * @param {RequestInfo|URL} input - The Request Object or URL. * @param {RequestInit} init - An init object to include options such as heders and body. * * @returns Response object fetched from the EdgeGrid API */ async fetch(input, init) { let signedRequest = await this.signRequest(input, init); // clone request in case we need to use it for a redirect let clonedRequest = signedRequest.clone(); let response = await builtinFetch(signedRequest, { redirect: 'manual', // prevent automatic redirect following }); // Check for redirect manually const locationHeader = response.headers.get('location'); if ((0, helpers_1.isRedirect)(response.status) && locationHeader) { const headers = clonedRequest.headers; headers.delete('authorization'); const redirectedRequest = new Request(clonedRequest, { headers }); return this.fetch(locationHeader, redirectedRequest); } return response; } } exports.default = EdgeGrid;