Skip to content

Commit

Permalink
feat: add abitlity to pass the user-agent in config object
Browse files Browse the repository at this point in the history
  • Loading branch information
bukowskiadam committed Jan 12, 2024
1 parent ce77d63 commit adcf0b9
Show file tree
Hide file tree
Showing 3 changed files with 109 additions and 133 deletions.
8 changes: 5 additions & 3 deletions lib/data-provider.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
'use strict';

const url = require('url');
const defaultHeaders = {
Accept: 'text/html, application/xhtml+xml, application/xml',
};

module.exports = function DataProvider(config) {
const pendingReqests = new Map();
Expand All @@ -12,6 +9,11 @@ module.exports = function DataProvider(config) {

const baseUrl = config.baseUrl || '';
const httpClient = config.httpClient || globalThis.fetch;
const userAgent = config.userAgent || 'node-esi';
const defaultHeaders = {
Accept: 'text/html, application/xhtml+xml, application/xml',
'user-agent': userAgent,
};

function extendRequestOptions(src, baseOptions) {
return [
Expand Down
40 changes: 37 additions & 3 deletions test/data-provider-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,39 @@ describe('Data Provider', () => {
.catch(done);
});

it('allows to configure custom user agent', (done) => {
// given
let calledUserAgent;
const userAgent = 'my-custom-agent';
const server = http.createServer((req, res) => {
calledUserAgent = req.headers['user-agent'];
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('stuff');
});
server.listen();

const port = server.address().port;
const dataProvider = new DataProvider({
baseUrl: `http://localhost:${port}`,
userAgent,
});

// when
dataProvider
.get('/')

// then
.then((result) => {
assert.equal(result, 'stuff');
assert.equal(calledUserAgent, userAgent);
done();
})
.catch(done);
});

it('should work with a custom http client that is fetch api compatible', (done) => {
// given
const baseUrl = 'http://example.com';
const userAgent = 'my-custom-agent';
let calledUrl;
let calledOptions;

Expand All @@ -113,7 +142,10 @@ describe('Data Provider', () => {

// when
dataProvider
.get('/path', { headers: { 'user-agent': userAgent } })
.get('/path', {
headers: { custom: 'custom-header-value' },
optionX: 'optionX',
})

// then
.then((result) => {
Expand All @@ -122,8 +154,10 @@ describe('Data Provider', () => {
assert.deepEqual(calledOptions, {
headers: {
Accept: 'text/html, application/xhtml+xml, application/xml',
'user-agent': userAgent,
'user-agent': 'node-esi',
custom: 'custom-header-value',
},
optionX: 'optionX',
});
done();
})
Expand Down
Loading

0 comments on commit adcf0b9

Please sign in to comment.