fix: add hiro product header to default network fetch function

This commit is contained in:
janniks
2023-09-18 13:55:32 +02:00
committed by janniks
parent debeb0051b
commit 58eb3af347
3 changed files with 16 additions and 5 deletions

View File

@@ -4,8 +4,11 @@ import 'cross-fetch/polyfill';
// Reference: https://developer.mozilla.org/en-US/docs/Web/API/Request/Request
const defaultFetchOpts: RequestInit = {
// By default referrer value will be client:origin: above reference link
referrerPolicy: 'origin', // Use origin value for referrer policy
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
referrerPolicy: 'origin', // Use origin value for referrer policy
headers: {
'x-hiro-product': 'stacksjs',
},
};
/**
@@ -39,7 +42,7 @@ export const setFetchOptions = (ops: RequestInit): RequestInit => {
export async function fetchWrapper(input: RequestInfo, init?: RequestInit): Promise<Response> {
const fetchOpts = {};
// Use the provided options in request options along with default or user provided values
Object.assign(fetchOpts, init, defaultFetchOpts);
Object.assign(fetchOpts, defaultFetchOpts, init);
const fetchResult = await fetch(input, fetchOpts);
return fetchResult;
@@ -81,7 +84,7 @@ export interface ApiKeyMiddlewareOpts {
/** @internal */
export function hostMatches(host: string, pattern: string | RegExp) {
if (typeof pattern === 'string') return pattern === host;
return (pattern as RegExp).exec(host);
return pattern.exec(host);
}
/**

View File

@@ -4,13 +4,21 @@ import { fetchWrapper, getFetchOptions, setFetchOptions } from '../src/fetch';
test('Verify fetch private options', async () => {
const defaultOptioins = getFetchOptions();
expect(defaultOptioins).toEqual({ referrerPolicy: 'origin' });
expect(defaultOptioins).toEqual({
referrerPolicy: 'origin',
headers: {
'x-hiro-product': 'stacksjs',
},
});
// Override default options when fetchPrivate is called internally by other stacks.js libraries like transactions or from server side
// This is for developers as they cannot directly pass options directly in fetchPrivate
const modifiedOptions: RequestInit = {
referrer: 'http://test.com',
referrerPolicy: 'same-origin',
headers: {
'x-hiro-product': 'stacksjs',
},
};
// Developers can set fetch options globally one time specifically when fetchPrivate is used internally by stacks.js libraries

View File

@@ -20,7 +20,7 @@ test('createApiKeyMiddleware adds x-api-key header to correct host request', asy
const fetchFn = createFetchFn(middleware);
await fetchFn('https://example.com');
expect(fetchMock.mock.calls[0][1]?.headers).toBe(undefined);
expect(fetchMock.mock.calls[0][1]?.headers).toStrictEqual({ 'x-hiro-product': 'stacksjs' });
await fetchFn('https://api.stacks.co');
expect((fetchMock.mock.calls[1][1]?.headers as Headers)?.get('x-api-key')).toContain(apiKey);