Skip to content

Commit

Permalink
Add default common headers
Browse files Browse the repository at this point in the history
  • Loading branch information
SDBowen authored and gandlafbtc committed Sep 10, 2023
1 parent d0aeec0 commit 3b44223
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { checkResponse } from './utils';
type RequestArgs = {
endpoint: string;
requestBody?: Record<string, unknown>;
headers?: Record<string, string>;
};

type RequestOptions = RequestArgs & Omit<RequestInit, 'body'>;
type RequestOptions = RequestArgs & Omit<RequestInit, 'body' | 'headers'>;

let globalRequestOptions: Partial<RequestOptions> = {};

Expand All @@ -17,9 +18,20 @@ export function setGlobalRequestOptions(options: Partial<RequestOptions>): void
globalRequestOptions = options;
}

async function _request({ endpoint, requestBody, ...options }: RequestOptions): Promise<Response> {
async function _request({
endpoint,
requestBody,
headers: requestHeaders,
...options
}: RequestOptions): Promise<Response> {
const body = requestBody ? JSON.stringify(requestBody) : undefined;
const response = await fetch(endpoint, { body, ...options });
const headers = {
...{ Accept: 'application/json, text/plain, */*' },
...(body ? { 'Content-Type': 'application/json' } : undefined),
...requestHeaders
};

const response = await fetch(endpoint, { body, headers, ...options });

if (!response.ok) {
const { error, detail } = await response.json();
Expand All @@ -31,8 +43,6 @@ async function _request({ endpoint, requestBody, ...options }: RequestOptions):
}

export default async function request<T>(options: RequestOptions): Promise<T> {
options.headers = { 'Content-Type': 'application/json', ...options.headers };
options.headers = { 'Accept': 'application/json', ...options.headers };
const response = await _request({ ...options, ...globalRequestOptions });
const data = await response.json().catch(() => ({ error: 'bad response' }));
checkResponse(data);
Expand Down
53 changes: 53 additions & 0 deletions test/request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import nock from 'nock';
import { CashuMint } from '../src/CashuMint.js';
import { CashuWallet } from '../src/CashuWallet.js';
import { setGlobalRequestOptions } from '../src/request.js';

let request: Record<string, string> | undefined;
const mintUrl = 'https://legend.lnbits.com/cashu/api/v1/4gr9Xcmz3XEkUNwiBiQGoC';
const invoice =
'lnbc20u1p3u27nppp5pm074ffk6m42lvae8c6847z7xuvhyknwgkk7pzdce47grf2ksqwsdpv2phhwetjv4jzqcneypqyc6t8dp6xu6twva2xjuzzda6qcqzpgxqyz5vqsp5sw6n7cztudpl5m5jv3z6dtqpt2zhd3q6dwgftey9qxv09w82rgjq9qyyssqhtfl8wv7scwp5flqvmgjjh20nf6utvv5daw5h43h69yqfwjch7wnra3cn94qkscgewa33wvfh7guz76rzsfg9pwlk8mqd27wavf2udsq3yeuju';

beforeAll(() => {
nock.disableNetConnect();
});

beforeEach(() => {
nock.cleanAll();
request = undefined;
});

describe('requests', () => {
test('request with body contains the correct headers', async () => {
const mint = new CashuMint(mintUrl);
nock(mintUrl)
.post('/checkfees')
.reply(200, function () {
request = this.req.headers;
return { fee: 20 };
});

const wallet = new CashuWallet(mint);
await wallet.getFee(invoice);

expect(request).toBeDefined();
expect(request!['content-type']).toContain('application/json');
expect(request!['accept']).toContain('application/json, text/plain, */*');
});
test('global custom headers can be set', async () => {
const mint = new CashuMint(mintUrl);
nock(mintUrl)
.post('/checkfees')
.reply(200, function () {
request = this.req.headers;
return { fee: 20 };
});

const wallet = new CashuWallet(mint);
setGlobalRequestOptions({ headers: { 'x-cashu': 'xyz-123-abc' } });
await wallet.getFee(invoice);

expect(request).toBeDefined();
expect(request!['x-cashu']).toContain('xyz-123-abc');
});
});

0 comments on commit 3b44223

Please sign in to comment.