From b815bab09ca9044fc1e9f894abedbb7bb4910f96 Mon Sep 17 00:00:00 2001 From: Brandon Liu Date: Thu, 28 Sep 2023 15:07:25 +0800 Subject: [PATCH] js: FetchSource takes optional custom headers (#112) * js: FetchSource takes optional custom headers --- js/examples/maplibre.html | 2 +- js/index.ts | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/js/examples/maplibre.html b/js/examples/maplibre.html index 80e89df..1ada9e9 100644 --- a/js/examples/maplibre.html +++ b/js/examples/maplibre.html @@ -23,7 +23,7 @@ let PMTILES_URL = "https://protomaps.github.io/PMTiles/protomaps(vector)ODbL_firenze.pmtiles"; - const p = new pmtiles.PMTiles(PMTILES_URL) + const p = new pmtiles.PMTiles(PMTILES_URL); // this is so we share one instance across the JS code and the map renderer protocol.add(p); diff --git a/js/index.ts b/js/index.ts index f97a0c4..d781e40 100644 --- a/js/index.ts +++ b/js/index.ts @@ -282,15 +282,21 @@ export class FileAPISource implements Source { export class FetchSource implements Source { url: string; + customHeaders: Headers; - constructor(url: string) { + constructor(url: string, customHeaders: Headers = new Headers()) { this.url = url; + this.customHeaders = customHeaders; } getKey() { return this.url; } + setHeaders(customHeaders: Headers) { + this.customHeaders = customHeaders; + } + async getBytes( offset: number, length: number, @@ -303,9 +309,15 @@ export class FetchSource implements Source { signal = controller.signal; } + const requestHeaders = new Headers(this.customHeaders); + requestHeaders.set( + "Range", + "bytes=" + offset + "-" + (offset + length - 1) + ); + let resp = await fetch(this.url, { signal: signal, - headers: { Range: "bytes=" + offset + "-" + (offset + length - 1) }, + headers: requestHeaders, }); // TODO: can return 416 with offset > 0 if content changed, which will have a blank etag.