|
| 1 | +import { LogConfig } from '@basemaps/shared'; |
| 2 | +import assert from 'node:assert'; |
| 3 | +import ulid from 'ulid'; |
| 4 | + |
| 5 | +const logger = LogConfig.get(); |
| 6 | +/** Fresh API Key to use */ |
| 7 | +const apiKey = 'c' + ulid.ulid().toLowerCase(); |
| 8 | + |
| 9 | +/** Http headers required to trigger CORS */ |
| 10 | +const Cors = { origin: 'https://example.com' }; |
| 11 | + |
| 12 | +/** Host that is being tested */ |
| 13 | +let host = process.env['BASEMAPS_HOST'] || 'https://dev.basemaps.linz.govt.nz'; |
| 14 | + |
| 15 | +if (!host.startsWith('http')) throw new Error(`Invalid host: ${host}`); |
| 16 | +if (host.endsWith('/')) host = host.slice(0, host.length - 1); |
| 17 | + |
| 18 | +/** Request a url with options |
| 19 | + * |
| 20 | + * @example |
| 21 | + * ```typescript |
| 22 | + * await req('/v1/version') |
| 23 | + * await req('/v1/version', { method: 'OPTIONS' }) |
| 24 | + * ```` |
| 25 | + */ |
| 26 | +async function req(path: string, opts?: RequestInit): Promise<Response> { |
| 27 | + const target = new URL(path, host); |
| 28 | + logger.trace({ path, url: target.href }, 'Fetch'); |
| 29 | + const startTime = performance.now(); |
| 30 | + const res = await fetch(target, opts); |
| 31 | + logger.info( |
| 32 | + { path, url: target.href, status: res.status, ...opts, duration: performance.now() - startTime }, |
| 33 | + 'Fetch:Done', |
| 34 | + ); |
| 35 | + return res; |
| 36 | +} |
| 37 | + |
| 38 | +export const ctx = { logger, host, Cors, apiKey, req }; |
| 39 | + |
| 40 | +/** Validate that the response was not a cached response */ |
| 41 | +export function assertCacheMiss(res: Response): void { |
| 42 | + const cacheHeader = res.headers.get('x-cache'); |
| 43 | + if (cacheHeader == null) return; // No header is a miss |
| 44 | + assert.equal(cacheHeader.startsWith('Miss'), true, `Should be a cache Miss ${res.headers.get('x-cache')}`); |
| 45 | +} |
0 commit comments