Git Product home page Git Product logo

accepts's People

Contributors

carpasse avatar dougwilson avatar federomero avatar hayeah avatar jonathanong avatar nook-scheel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

accepts's Issues

Change to mime-types causes crash

When a user gives an unknown file extension to types, it crashes with TypeError: Object false has no method 'match' when it didn't use to.

Accept types always validating

I'm trying to use this in Koa.js and the results are indeterministic.

For example

// "normal" browser request (Chrome)
// accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
this.request.accept.types('json');   // -> 'json'
this.request.accept.types('html');   // -> 'html'

// ajax ($.getJSON) request with jQuery (Chrome)
// accept: application/json, text/javascript, */*; q=0.01
this.request.accept.types('json');   // -> 'json'
this.request.accept.types('html');   // -> 'html'

there should be a strict mode, or something. How can the program determine accurately what response type to return?

Something better than req.accepts('json') && !req.accepts('html') ??

Hello again :)

In lots of places in my app I have this line

if (req.accepts('json') && !req.accepts('html')) {
    // process the GET request from superagent (client)
    ...
    res.json(200, data);
} else {
    // middleware further down will load the basic page layout
    next();
}

The reason why I need !req.accepts('html') is because of the single page app structure. In other words, when the URL is called for the first time, the whole page layout has to be loaded first.

And when loaded, then the controller on the client side will fire the GET request (XHR) where a JSON is returned and data is finally presented on the page.

I might be correct there and the above code is fine. But I think there is a bad code smell around req.accepts('json') && !req.accepts('html'). Do you think so?

Ability to add additional types

It would be nice to add types so that the following would work.

// Accepts: application/hal+json
const accept = accepts(req);

switch(accept.type(['json', 'html'])) {
    case 'json':
       // would match both application/json and application/hal+json
    default:
      // 
}

*/* does not match text/*

const accepts = require('accepts')

const accept = accepts({
  headers: {
    'accept': 'text/*',
  },
})

console.log(accept.types([ 'application/json', 'text/html' ])) // > text/html
console.log(accept.types([ 'application/json', '*/*' ])) // > false

change * default

The current default is that:

Treats non-existent headers as *

, which doesn't make sense.

const contentType = accepts(incomingMessage)
  .type([
    'image/webp',
    'image/jpeg',
  ]) || 'image/jpeg';

In this case, I want to default to the safest option, which is the last entry in the array, or image/jpeg if nothing is matched.

When no header is present, however, the first option is picked, which is the least likely to be supported.

Ideally, I should be able to pick the fallback option when either header is not present or header value cannot be matched.

Implementing "406: not acceptable"

Context

In order to write a spec compliant content negotiation on the server, we also need to handle a request with e.g., the extreme accept: */*;q=0, which should return a 406 not acceptable.

Use cases are for example: a client that can only parse 1 serialization to do something like accept: application/json;q=1,*/*;q=0. If the server cannot provide an answer, the client will get the convenient 406.

Problem

In the accepts package, the server asks the client whether it accepts a certain list of values as follows (as copied from the README.md):

  switch (accept.type(['json', 'html'])) {
    case 'json':
      ...
      break
   case default:
      ...
      break
  }

The list ['json','html'] is the server-side list of preferences, yet the client also may have its preferences. It’s not because a client does not have application/json in its client-side list, that it cannot parse JSON. So, if the client is asking only for application/xml, but the server cannot offer that, the functionality should be that application/json is returned, as this is the preference from the server. Right now, the accepts library would return null, and leave the spec compliant implementation up to the user of the package. Yet probably, that user is not going to go through the pain of parsing the accept header all over again.

An extra note: it may be that the client cannot parse json at all, and wants to indicate that it can only parse XML.

Suggested solution

Instead of accept.type(['a','b','c']) is false or the format that is mentioned in the accept header of the request, I would only return false (and thus let the developer know it should return a 406) when the client indicated it does not accept any of the server-side representations. This function must return the first representation that is not not acceptable by the client.

When this is implemented, this would be a breaking change and would require a new major version number of this package.

RFC compliant explanation

https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation

Can we make this library more abstract?

Hi, i want to use this library with not only IncomingMessage instances.

Node.js 16+ has Fetch API now and it has global constructors such as Request, Response, Headers and other.

Also i see that implementation of this library uses only headers field from req parameter.

Idea 1

Maybe we can make this library more abstract, for example we can make next interface changes:

// it is just a variant of interface
declare function accepts(getHeader: (headerName: string) => string | null): Accepts

With this interface we can use this library with instance of any class:

const req1 = new IncomingMessage(/* ... */);
const result1 = accepts(headerName => req1.getHeader(headerName));

const req2 = new Request(/* ... */)
const result2 = accepts(headerName => req2.headers.get(headerName))

Idea 2

Incoming message already has getHeader method, we can make interface like:

declare function accepts(req: Pick<IncomingMessage, 'getHeader'>): Accepts

And then we can use it now too for IncomingMessage:

const req = new IncomingMessage(/* ... */);

// no changes in usage
const accept = accepts(req);

And also we can use it easy with Request instance or any other request value:

const req = new Request(/* ... */);

// easy making wrapper object for use with Request
const accept = accepts({
  getHeader: headerName => req.headers.get(headerName)
});

Idea 3

Maybe we can make just TypeScript types of this library more abstract, for example:

declare function accepts(req: Pick<IncomingMessage, 'headers'>): Accepts

RangeError: Maximum call stack size exceeded

Hi,

I am getting this
RangeError: Maximum call stack size exceeded
when testing with non-existent accept-headers. that is:

  • no accept-header at all
  • or not-so-common accept-headers like 'text/plain'
  • outright nonsensical accept-headers like 'foo/bar' or 'test123'

I tried

try {
  type = accept.types('html', 'json');
} catch(e) {
// RangeError: Maximum call stack size exceeded
}

to get around the problem, but it still crashes the process
I haven't tried to pimp the request.headers yet, I don't know if it can be done but it looks like it shouldn't

k.

Cannot find module negotiator

Hi!

Reporting a bug. When I import express, it imports accepts which imports negotiator. However, it seems that version 1.3.8 of accepts cannot find the negotiator dependency. It has to be explicitly installed in the project. Some more details:
Node version: 20.10.0
Express version: 4.17.0
Reverting to accepts 1.3.7 fixes the issue.

docs

  • accept.types() supports type-is-type types. accept.types('json', 'html', 'text/*', 'image/*', 'video/*')
  • only execute accept[property]() once so content negotiation can do its job. don't do multiple accept[property]()s

possibility to get region from accept language

Hi πŸ‘‹
I'm using express, and i'm trying to figure out how to get the preferred region code (2 letter country code)
do you have any recommendations to deal with this?

almost feel like the negotiator dep should have some kind of feature to retrieve it

Type suffixes

In my application, I am negotiation API version by an Accept header that follows the following structure:

application/vnd.<appName>.<version>+json

Is there a way of handling this with accepts? Should it match "json"?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.