Skip to content

Commit

Permalink
add preferred option
Browse files Browse the repository at this point in the history
  • Loading branch information
bjohansebas committed Oct 22, 2024
1 parent e1c347e commit 45cad4b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
11 changes: 8 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,17 +119,22 @@ Accepts.prototype.types = function (types_) {
* ['gzip', 'deflate']
*
* @param {String|Array} encodings...
* @param {Object} options_
* @return {String|Array}
* @public
*/

Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings_) {
Accepts.prototype.encodings = function (encodings_, options_) {
var encodings = encodings_
var preferred = arguments[arguments.length - 1]?.preferred || null

// support flattened arguments
if (encodings && !Array.isArray(encodings)) {
encodings = new Array(arguments.length)
var lenght = preferred ? arguments.length - 1 : arguments.length

encodings = new Array(lenght)

for (var i = 0; i < encodings.length; i++) {
encodings[i] = arguments[i]
}
Expand All @@ -140,7 +145,7 @@ Accepts.prototype.encodings = function (encodings_) {
return this.negotiator.encodings()
}

return this.negotiator.encodings(encodings)[0] || false
return this.negotiator.encodings(encodings, { preferred: preferred })[0] || false
}

/**
Expand Down
15 changes: 15 additions & 0 deletions test/encoding.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ describe('accepts.encodings()', function () {
assert.strictEqual(accept.encodings('compress', 'gzip'), 'gzip')
assert.strictEqual(accept.encodings('gzip', 'compress'), 'gzip')
})

it('should accept a preferred encoding', function () {
var req = createRequest('gzip, br, compress')
var accept = accepts(req)
assert.strictEqual(accept.encodings('gzip', 'br', 'identity', { preferred: ['br'] }), 'br')
assert.strictEqual(accept.encodings('gzip', 'identity', 'br', { preferred: ['br'] }), 'br')
})
})

describe('with an array', function () {
Expand All @@ -65,6 +72,14 @@ describe('accepts.encodings()', function () {
assert.strictEqual(accept.encodings(['compress', 'gzip']), 'gzip')
})
})

describe('with preferred encoding', function () {
it('should return the preferred encoding', function () {
var req = createRequest('gzip, br')
var accept = accepts(req)
assert.strictEqual(accept.encodings(['br', 'gzip', 'identity'], { preferred: ['br'] }), 'br')
})
})
})

function createRequest (encoding) {
Expand Down

0 comments on commit 45cad4b

Please sign in to comment.