Middleware which passes a request to different handlers based on the content type. The most basic use case is to allow a single API endpoint to:
- Return HTML in response to a request from a browser.
- Return JSON in response to a request from a script or AJAX request.
To use this grade, you must create the map options.handlers
, which indicates which content types should be handled by
which handler
grades, as in the following example:
handlers: {
json: {
contentType: "application/json",
handlerGrades: ["name.spaced.grade1"]
},
text: {
contentType: ["text/html", "text/plain"]
handlerGrades: ["name.spaced.grade2", "name.spaced.grade1"]
}
}
The Accept
headers supplied by the user will be tested using request.accepts(contentType)
. The first entry whose
contentType
matches what the request accepts will be used. If no Accepts
headers are provided, any contentType
will match, and hence the first handler will be used (see below for details on controlling the ordering).
When the decision has been made and a match has been found, a dynamic component will be constructed using the matching
'handlerGrades'. This component is a fluid.express.handler
, and is expected to perform the required functions (see
[handler.md](the handler docs) for details).
To control the order in which handlers are tested, you should use the namespace
and priority
attributes,
as in the following example:
handlers: {
html: {
priority: "first",
contentType: ["text/html", "text/plain"],
handlerGrades: "my.html.handler.grade"
},
json: {
contentType: "application/json",
priority: "after:html",
handlerGrades: ["my.json.handler.grade"]
},
"default": {
priority: "last",
contentType: "*/*",
handlerGrades: "my.default.handler.grade"
}
}
Note that request.accepts()
will match the first handler if the request has no Accept
header. Thus, in the
above example:
- A request with no
Accept
header will be handled bymy.html.handler.grade
(because it's first in the list by priority). - A request with
Accept: text/html
,Accept: text/plain
, orAccept: text/*
will be handled bymy.html.handler.grade
. - A request with
Accept: application/json
orAccept: application/*
will be handled bymy.json.handler.grade
. - A request with any other
Accept
header will be handled bymy.default.handler.grade
This invoker fulfills the standard contract for a fluid.express.middleware
component. It locates an appropriate handler
if possible, and allows that to handle the original request. If no handler can be found, next(err)
is called and
downstream error handling middleware is expected to handle things from there.