File tree 1 file changed +31
-4
lines changed
1 file changed +31
-4
lines changed Original file line number Diff line number Diff line change 1
1
import contentTypeUtil from "content-type" ;
2
2
import { isHttpError } from "http-errors" ;
3
3
import type { Middleware , ParameterizedContext } from "koa" ;
4
- import { type JsonApiMediaType , getAcceptableMediaTypes } from "./accept.js" ;
4
+ import { type JsonApiMediaType , ParserError , getAcceptableMediaTypes } from "./accept.js" ;
5
5
import { JsonApiBody , JsonApiErrorBody } from "./body.js" ;
6
6
import { InputValidationError } from "./request.js" ;
7
7
@@ -13,9 +13,36 @@ type JsonApiState = {
13
13
14
14
export const jsonApiRequestMiddleware = ( ) : Middleware < JsonApiState > => {
15
15
return async ( context , next ) => {
16
- context . state . jsonApi = {
17
- acceptableTypes : getAcceptableMediaTypes ( context . get ( "Accept" ) ) ,
18
- } ;
16
+ try {
17
+ context . state . jsonApi = {
18
+ acceptableTypes : getAcceptableMediaTypes ( context . get ( "Accept" ) ) ,
19
+ } ;
20
+ } catch ( error ) {
21
+ if ( ! ( error instanceof ParserError ) ) {
22
+ throw error ;
23
+ }
24
+
25
+ context . status = 400 ;
26
+ context . set (
27
+ "Content-Type" ,
28
+ contentTypeUtil . format ( { type : "application/vnd.api+json" } ) ,
29
+ ) ;
30
+ context . body = {
31
+ jsonapi : { version : "1.1" } ,
32
+ errors : [
33
+ {
34
+ status : "400" ,
35
+ code : "bad_request" ,
36
+ title : "Bad Request" ,
37
+ detail : error . message ,
38
+ source : {
39
+ header : "accept" ,
40
+ } ,
41
+ } ,
42
+ ] ,
43
+ } ;
44
+ return ;
45
+ }
19
46
20
47
await next ( ) ;
21
48
handleResponse ( context ) ;
You can’t perform that action at this time.
0 commit comments