Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support raw Set-Cookie headers #310

Merged
merged 2 commits into from
Oct 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
- [HTTP/2 Server Push](#http2-server-push)
- [Force HTTP/1(.1) protocol](#force-http11-protocol)
- [HTTP/1.1 Keep-Alive](#http11-keep-alive)
- [Extract Set-Cookie Header](#extract-set-cookie-header)
- [Self-signed Certificates](#self-signed-certificates)
- [Set cache size limit](#set-cache-size-limit)
- [Disable caching](#disable-caching)
Expand Down Expand Up @@ -455,6 +456,18 @@ const resp = await fetch('https://httpbin.org/status/200');
console.log(`Connection: ${resp.headers.get('connection')}`); // -> keep-alive
```

### Extract Set-Cookie Header

Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.plain()`. This is an `@adobe/fetch` only API.

```javascript
const { fetch } = require('@adobe/fetch');

const resp = await fetch('https://httpbin.org/cookies/set?a=1&b=2');
// returns an array of values, instead of a string of comma-separated values
console.log(resp.headers.plain()['set-cookie']);
```

### Self-signed Certificates

```javascript
Expand Down
34 changes: 30 additions & 4 deletions src/fetch/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,25 @@ class Headers {
});
} else if (Array.isArray(init)) {
init.forEach(([name, value]) => {
this.append(name, value);
if (Array.isArray(value)) {
// special case for Set-Cookie header which can have an array of values
value.forEach((val) => {
this.append(name, val);
});
} else {
this.append(name, value);
}
});
} else /* istanbul ignore else */ if (isPlainObject(init)) {
for (const [name, value] of Object.entries(init)) {
this.append(name, value);
if (Array.isArray(value)) {
// special case for Set-Cookie header which can have an array of values
value.forEach((val) => {
this.append(name, val);
});
} else {
this.set(name, value);
}
}
}
}
Expand All @@ -98,14 +112,26 @@ class Headers {

get(name) {
const val = this[INTERNALS].map.get(normalizeName(name));
return val === undefined ? null : val;
if (val === undefined) {
return null;
} else if (Array.isArray(val)) {
return val.join(', ');
} else {
return val;
}
}

append(name, value) {
const nm = normalizeName(name);
const val = normalizeValue(value, name);
const oldVal = this[INTERNALS].map.get(nm);
this[INTERNALS].map.set(nm, oldVal ? `${oldVal}, ${val}` : val);
if (Array.isArray(oldVal)) {
oldVal.push(val);
} else if (oldVal === undefined) {
this[INTERNALS].map.set(nm, val);
} else {
this[INTERNALS].map.set(nm, [oldVal, val]);
}
}

delete(name) {
Expand Down
15 changes: 13 additions & 2 deletions test/fetch/headers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ describe('Headers Tests', () => {
['c', '4'],
['b', '3'],
['a', '1'],
['d', ['5', '6']],
]);
expect(headers).to.have.property('forEach');

Expand All @@ -73,6 +74,7 @@ describe('Headers Tests', () => {
['a', '1'],
['b', '2, 3'],
['c', '4'],
['d', '5, 6'],
]);
});

Expand Down Expand Up @@ -154,8 +156,9 @@ describe('Headers Tests', () => {
});

it('constructor should support plain object', () => {
const headers = new Headers({ foo: 'bar' });
const headers = new Headers({ foo: 'bar', 'x-cookies': ['a=1', 'b=2'] });
expect(headers.get('foo')).to.be.equal('bar');
expect(headers.get('x-cookies')).to.be.equal('a=1, b=2');
});

it('get should return null if not found', () => {
Expand All @@ -181,8 +184,16 @@ describe('Headers Tests', () => {
});

it('plain() should return plain object representation', () => {
const hdrObj = { foo: 'bar' };
const hdrObj = { foo: 'bar', 'x-cookies': ['a=1', 'b=2'] };
const headers = new Headers(hdrObj);
expect(headers.plain()).to.be.deep.equal(hdrObj);
});

it('should support multi-valued headers (e.g. Set-Cookie)', () => {
const headers = new Headers();
headers.set('set-cookie', 'a=1; Path=/');
headers.append('set-cookie', 'b=2; Path=/');
expect(headers.get('set-cookie')).to.be.equal('a=1; Path=/, b=2; Path=/');
expect(headers.plain()['set-cookie']).to.be.deep.equal(['a=1; Path=/', 'b=2; Path=/']);
});
});
11 changes: 11 additions & 0 deletions test/fetch/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,17 @@ testParams.forEach((params) => {
assert.deepStrictEqual(reqForm, searchParams);
});

it('returns Set-Cookie headers', async () => {
const resp = await fetch(`${baseUrl}/cookies/set?a=1&b=2`, { redirect: 'manual' });
// Response headers:
// set-cookie: a=1; [Secure; ]Path=/
// set-cookie: b=2; [Secure; ]Path=/
assert.strictEqual(resp.status, 302);
assert(/a=1; (Secure; )?Path=\/, b=2; (Secure; )?Path=\//.test(resp.headers.get('set-cookie')));
assert(/a=1; (Secure; )?Path=\//.test(resp.headers.plain()['set-cookie'][0]));
assert(/b=2; (Secure; )?Path=\//.test(resp.headers.plain()['set-cookie'][1]));
});

if (protocol === 'https') {
it('supports self signed certificate', async () => {
const server = new Server(httpVersion === '2.0' ? 2 : 1, true, HELLO_WORLD);
Expand Down