Skip to content

Commit

Permalink
feat: implement response.has (#1397)
Browse files Browse the repository at this point in the history
  • Loading branch information
tinovyatkin authored and dead-horse committed Oct 14, 2019
1 parent 8be5626 commit d48d88e
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
9 changes: 9 additions & 0 deletions docs/api/response.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,15 @@ app.use(async ctx => {
const etag = ctx.response.get('ETag');
```

### response.has(field)

Returns `true` if the header identified by name is currently set in the outgoing headers.
The header name matching is case-insensitive.

```js
const rateLimited = ctx.response.has('X-RateLimit-Limit');
```

### response.set(field, value)

Set response header `field` to `value`:
Expand Down
1 change: 1 addition & 0 deletions lib/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ delegate(proto, 'response')
.method('redirect')
.method('remove')
.method('vary')
.method('has')
.method('set')
.method('append')
.method('flushHeaders')
Expand Down
25 changes: 24 additions & 1 deletion lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ module.exports = {
if (!this._explicitStatus) this.status = 200;

// set the content-type only if not yet set
const setType = !this.header['content-type'];
const setType = !this.has('Content-Type');

// string
if ('string' == typeof val) {
Expand Down Expand Up @@ -419,6 +419,29 @@ module.exports = {
return this.header[field.toLowerCase()] || '';
},

/**
* Returns true if the header identified by name is currently set in the outgoing headers.
* The header name matching is case-insensitive.
*
* Examples:
*
* this.has('Content-Type');
* // => true
*
* this.get('content-type');
* // => true
*
* @param {String} field
* @return {boolean}
* @api public
*/
has(field) {
return typeof this.res.hasHeader === 'function'
? this.res.hasHeader(field)
// Node < 7.7
: field.toLowerCase() in this.headers;
},

/**
* Set header `field` to `val`, or pass
* an object of header fields.
Expand Down
21 changes: 21 additions & 0 deletions test/response/has.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

'use strict';

const assert = require('assert');
const context = require('../helpers/context');

describe('ctx.response.has(name)', () => {
it('should check a field value, case insensitive way', () => {
const ctx = context();
ctx.set('X-Foo', '');
assert.ok(ctx.response.has('x-Foo'));
assert.ok(ctx.has('x-foo'));
});

it('should return false for non-existent header', () => {
const ctx = context();
assert.strictEqual(ctx.response.has('boo'), false);
ctx.set('x-foo', 5);
assert.strictEqual(ctx.has('x-boo'), false);
});
});

0 comments on commit d48d88e

Please sign in to comment.