diesel-core 1.6.7 → 1.6.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adaptor/node/main.d.ts +2 -1
- package/dist/adaptor/node/main.js +3 -1
- package/dist/constant.js +11 -0
- package/dist/ctx.js +507 -52
- package/dist/handleRequest.js +82 -52
- package/dist/http-exception.js +20 -1
- package/dist/http-exception.test.js +50 -0
- package/dist/main.js +670 -258
- package/dist/middlewares/cors/index.test.js +94 -0
- package/dist/middlewares/file-route/index.js +69 -0
- package/dist/middlewares/filesave/index.test.js +73 -0
- package/dist/middlewares/jwt/index.test.js +74 -0
- package/dist/middlewares/powered-by/index.test.js +46 -0
- package/dist/middlewares/ratelimit/index.test.js +104 -0
- package/dist/middlewares/request-id/index.js +50 -0
- package/dist/middlewares/request-id/index.test.js +1 -0
- package/dist/middlewares/security/index.test.js +50 -0
- package/dist/request_pipeline.js +285 -95
- package/dist/router/find-my-way.js +18 -102
- package/dist/router/interface.js +22 -102
- package/dist/router/regex.js +3 -0
- package/dist/router/trie.js +148 -1
- package/dist/router/trie2.js +151 -0
- package/dist/router/trie2.test.js +162 -0
- package/dist/types.js +1 -0
- package/package.json +1 -1
package/dist/handleRequest.js
CHANGED
|
@@ -1,54 +1,84 @@
|
|
|
1
|
-
var
|
|
2
|
-
|
|
3
|
-
,
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
function encode_char(c) {
|
|
10
|
-
return _ENCODE_HTML_RULES[c] || c;
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
11
9
|
};
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
10
|
+
import { Context } from "./ctx";
|
|
11
|
+
import { tryDecodeURI } from "./utils/urls";
|
|
12
|
+
import { generateErrorResponse, handleRouteNotFound, runFilter, runHooks, runMiddlewares } from "./utils/request.util";
|
|
13
|
+
import { isPromise } from "./utils/promise";
|
|
14
|
+
export default function handleRequest(req, server, diesel, env, executionContext) {
|
|
15
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
16
|
+
let pathname;
|
|
17
|
+
const start = req.url.indexOf('/', req.url.indexOf(':') + 4);
|
|
18
|
+
let i = start;
|
|
19
|
+
for (; i < req.url.length; i++) {
|
|
20
|
+
const charCode = req.url.charCodeAt(i);
|
|
21
|
+
if (charCode === 37) { // percent-encoded
|
|
22
|
+
const queryIndex = req.url.indexOf('?', i);
|
|
23
|
+
const path = req.url.slice(start, queryIndex === -1 ? undefined : queryIndex);
|
|
24
|
+
pathname = tryDecodeURI(path.includes('%25') ? path.replace(/%25/g, '%2525') : path);
|
|
25
|
+
break;
|
|
26
|
+
}
|
|
27
|
+
else if (charCode === 63) {
|
|
28
|
+
break;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (!pathname) {
|
|
32
|
+
pathname = req.url.slice(start, i);
|
|
33
|
+
}
|
|
34
|
+
const matchedRouteHandler = diesel.router.find(req.method, pathname);
|
|
35
|
+
const ctx = new Context(req, server, pathname, matchedRouteHandler === null || matchedRouteHandler === void 0 ? void 0 : matchedRouteHandler.path, env, executionContext);
|
|
36
|
+
// const ctx = createCtx(req,server,pathname,routeHandler?.path)
|
|
37
|
+
// PipeLines such as filters , middlewares, hooks
|
|
38
|
+
// if (diesel.hasOnReqHook)
|
|
39
|
+
// await runHooks('onRequest', diesel.hooks.onRequest, [req, pathname, server])
|
|
40
|
+
// middleware execution
|
|
41
|
+
if (diesel.hasMiddleware) {
|
|
42
|
+
const mwResult = yield runMiddlewares(diesel, pathname, ctx);
|
|
43
|
+
if (mwResult)
|
|
44
|
+
return mwResult;
|
|
45
|
+
}
|
|
46
|
+
// filter execution
|
|
47
|
+
if (diesel.hasFilterEnabled) {
|
|
48
|
+
const filterResponse = yield runFilter(diesel, pathname, ctx);
|
|
49
|
+
if (filterResponse)
|
|
50
|
+
return filterResponse;
|
|
51
|
+
}
|
|
52
|
+
// if route not found
|
|
53
|
+
// if (!routeHandler) return await handleRouteNotFound(diesel, ctx, pathname)
|
|
54
|
+
// pre-handler
|
|
55
|
+
if (diesel.hasPreHandlerHook) {
|
|
56
|
+
const result = yield runHooks('preHandler', diesel.hooks.preHandler, [ctx]);
|
|
57
|
+
if (result)
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
let finalResult;
|
|
61
|
+
const handlers = matchedRouteHandler === null || matchedRouteHandler === void 0 ? void 0 : matchedRouteHandler.handler;
|
|
62
|
+
if (handlers.length === 1) {
|
|
63
|
+
const result = handlers[0](ctx);
|
|
64
|
+
finalResult = isPromise(result) ? yield result : result;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
for (let i = 0; i < handlers.length; i++) {
|
|
68
|
+
const result = handlers[i](ctx);
|
|
69
|
+
finalResult = isPromise(result) ? yield result : result;
|
|
70
|
+
if (finalResult)
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// onSend
|
|
75
|
+
if (diesel.hasOnSendHook) {
|
|
76
|
+
const response = yield runHooks('onSend', diesel.hooks.onSend, [ctx, finalResult]);
|
|
77
|
+
if (response)
|
|
78
|
+
return response;
|
|
79
|
+
}
|
|
80
|
+
return finalResult !== null && finalResult !== void 0 ? finalResult : yield handleRouteNotFound(diesel, ctx, pathname);
|
|
81
|
+
// if we dont return a response then by default Bun shows a err
|
|
82
|
+
return generateErrorResponse(500, "No response returned from handler.");
|
|
83
|
+
});
|
|
33
84
|
}
|
|
34
|
-
`;else f=this.source;if(g.client){if(f="escapeFn = escapeFn || "+j.toString()+`;
|
|
35
|
-
`+f,g.compileDebug)f="rethrow = rethrow || "+Qf.toString()+`;
|
|
36
|
-
`+f}if(g.strict)f=`"use strict";
|
|
37
|
-
`+f;if(g.debug)console.log(f);if(g.compileDebug&&g.filename)f=f+`
|
|
38
|
-
//# sourceURL=`+J+`
|
|
39
|
-
`;try{if(g.async)try{z=new Function("return (async function(){}).constructor;")()}catch(X){if(X instanceof SyntaxError)throw new Error("This environment does not support async/await");else throw X}else z=Function;w=new z(g.localsName+", escapeFn, include, rethrow",f)}catch(X){if(X instanceof SyntaxError){if(g.filename)X.message+=" in "+g.filename;if(X.message+=` while compiling ejs
|
|
40
|
-
|
|
41
|
-
`,X.message+=`If the above error is not helpful, you may want to try EJS-Lint:
|
|
42
|
-
`,X.message+="https://github.com/RyanZim/EJS-Lint",!g.async)X.message+=`
|
|
43
|
-
`,X.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw X}var G=g.client?w:function X(x){var Of=function(Lf,r){var O=F.shallowCopy(F.createNullProtoObjWherePossible(),x);if(r)O=F.shallowCopy(O,r);return Y1(Lf,g)(O)};return w.apply(g.context,[x||F.createNullProtoObjWherePossible(),j,Of,Qf])};if(g.filename&&typeof Object.defineProperty==="function"){var V=g.filename,C=R.basename(V,R.extname(V));try{Object.defineProperty(G,"name",{value:C,writable:!1,enumerable:!1,configurable:!0})}catch(X){}}return G},generateSource:function(){var f=this.opts;if(f.rmWhitespace)this.templateText=this.templateText.replace(/[\r\n]+/g,`
|
|
44
|
-
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var w=this,g=this.parseTemplateText(),A=this.opts.delimiter,$=this.opts.openDelimiter,j=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(z,J){var Z;if(z.indexOf($+A)===0&&z.indexOf($+A+A)!==0){if(Z=g[J+2],!(Z==A+j||Z=="-"+A+j||Z=="_"+A+j))throw new Error('Could not find matching close tag for "'+z+'".')}w.scanLine(z)})},parseTemplateText:function(){var f=this.templateText,w=this.regex,g=w.exec(f),A=[],$;while(g){if($=g.index,$!==0)A.push(f.substring(0,$)),f=f.slice($);A.push(g[0]),f=f.slice(g[0].length),g=w.exec(f)}if(f)A.push(f);return A},_addOutput:function(f){if(this.truncate)f=f.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1;if(!f)return f;f=f.replace(/\\/g,"\\\\"),f=f.replace(/\n/g,"\\n"),f=f.replace(/\r/g,"\\r"),f=f.replace(/"/g,"\\\""),this.source+=' ; __append("'+f+`")
|
|
45
|
-
`},scanLine:function(f){var w=this,g=this.opts.delimiter,A=this.opts.openDelimiter,$=this.opts.closeDelimiter,j=0;switch(j=f.split(`
|
|
46
|
-
`).length-1,f){case A+g:case A+g+"_":this.mode=Q.modes.EVAL;break;case A+g+"=":this.mode=Q.modes.ESCAPED;break;case A+g+"-":this.mode=Q.modes.RAW;break;case A+g+"#":this.mode=Q.modes.COMMENT;break;case A+g+g:this.mode=Q.modes.LITERAL,this.source+=' ; __append("'+f.replace(A+g+g,A+g)+`")
|
|
47
|
-
`;break;case g+g+$:this.mode=Q.modes.LITERAL,this.source+=' ; __append("'+f.replace(g+g+$,g+$)+`")
|
|
48
|
-
`;break;case g+$:case"-"+g+$:case"_"+g+$:if(this.mode==Q.modes.LITERAL)this._addOutput(f);this.mode=null,this.truncate=f.indexOf("-")===0||f.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case Q.modes.EVAL:case Q.modes.ESCAPED:case Q.modes.RAW:if(f.lastIndexOf("//")>f.lastIndexOf(`
|
|
49
|
-
`))f+=`
|
|
50
|
-
`}switch(this.mode){case Q.modes.EVAL:this.source+=" ; "+f+`
|
|
51
|
-
`;break;case Q.modes.ESCAPED:this.source+=" ; __append(escapeFn("+Xf(f)+`))
|
|
52
|
-
`;break;case Q.modes.RAW:this.source+=" ; __append("+Xf(f)+`)
|
|
53
|
-
`;break;case Q.modes.COMMENT:break;case Q.modes.LITERAL:this._addOutput(f);break}}else this._addOutput(f)}if(w.opts.compileDebug&&j)this.currentLine+=j,this.source+=" ; __line = "+this.currentLine+`
|
|
54
|
-
`}};Wf.escapeXML=F.escapeXML;Wf.__express=Wf.renderFile;Wf.VERSION=ef;Wf.name=A1;if(typeof window!="undefined")window.ejs=Wf});function D(f){switch(f.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var y=null;async function W1(){if(!y){let f=await Promise.resolve().then(() => Ef(Hf(),1));y=f.default||f}return y}var M1={string:"text/plain; charset=utf-8",object:"application/json; charset=utf-8",Uint8Array:"application/octet-stream",ArrayBuffer:"application/octet-stream"};class P{req;server;path;routePattern;paramNames;env;executionContext;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor(f,w,g,A,$,j,z){this.req=f,this.server=w,this.path=g,this.routePattern=A,this.executionContext=z,this.env=j,this.paramNames=$}setHeader(f,w){return this.headers.set(f,w),this}removeHeader(f){return this.headers.delete(f),this}set(f,w){return this.contextData[f]=w,this}get(f){return this.contextData[f]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):{};return this.parsedQuery}get params(){if(!Array.isArray(this.paramNames))return this.paramNames;if(!this.parsedParams)try{this.parsedParams=U1(this.paramNames,this.path)}catch(f){let w=f instanceof Error?f.message:String(f);throw new Error(`Failed to extract route parameters: ${w}`)}return this.parsedParams??{}}get body(){if(this.req.method==="GET")return Promise.resolve({});if(!this.parsedBody)this.parsedBody=(async()=>{try{let f=await H1(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f}catch(f){throw new Error("Invalid request body format")}})();return this.parsedBody}text(f,w=200){return new Response(f,{status:w,headers:this.headers})}send(f,w=200){let g;if(f instanceof Uint8Array)g="Uint8Array";else if(f instanceof ArrayBuffer)g="ArrayBuffer";else g=typeof f;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",M1[g]??"text/plain; charset=utf-8");let A=g==="object"&&f!==null?JSON.stringify(f):f;return new Response(A,{status:w,headers:this.headers})}json(f,w=200){return Response.json(f,{status:w,headers:this.headers})}file(f,w,g=200){let A=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",w??D(f));return new Response(A,{status:g,headers:this.headers})}async ejs(f,w={},g=200){let A=await W1();try{let $=await Bun.file(f).text(),j=A.render($,w),z=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(j,{status:g,headers:z})}catch($){return console.error("EJS Rendering Error:",$),new Response("Error rendering template",{status:500})}}redirect(f,w=302){return this.headers.set("Location",f),new Response(null,{status:w,headers:this.headers})}setCookie(f,w,g={}){let A=`${encodeURIComponent(f)}=${encodeURIComponent(w)}`;if(g.maxAge)A+=`; Max-Age=${g.maxAge}`;if(g.expires)A+=`; Expires=${g.expires.toUTCString()}`;if(g.path)A+=`; Path=${g.path}`;if(g.domain)A+=`; Domain=${g.domain}`;if(g.secure)A+="; Secure";if(g.httpOnly)A+="; HttpOnly";if(g.sameSite)A+=`; SameSite=${g.sameSite}`;return this.headers.append("Set-Cookie",A),this}get cookies(){if(!this.parsedCookies){let f=this.req.headers.get("cookie");this.parsedCookies=f?R1(f):{}}return this.parsedCookies}stream(f){let w=new Headers(this.headers),g=new ReadableStream({async start(A){await f(A),A.close()}});return new Response(g,{headers:w})}yieldStream(f){return new Response}}function R1(f){return Object.fromEntries(f.split(";").map((w)=>{let[g,...A]=w.trim().split("=");return[g,decodeURIComponent(A.join("="))]}))}function U1(f,w){let g={},[A]=w.split("?"),$=A.split("/").filter((z)=>z!==""),j=$.length-f.length;for(let z=0;z<f.length;z++)g[f[z]]=$[j+z];return g}function P1(f,w){let g={},A=f.split("/"),[$]=w.split("?"),j=$.split("/");if(A.length!==j.length)return null;for(let z=0;z<A.length;z++){let J=A[z];if(J.charCodeAt(0)===58)g[J.slice(1)]=j[z]}return g}async function H1(f){let w=f.headers.get("Content-Type")||"";if(!w)return{};if(f.headers.get("Content-Length")==="0"||!f.body)return{};if(w.startsWith("application/json"))return await f.json();if(w.startsWith("application/x-www-form-urlencoded")){let A=await f.text();return Object.fromEntries(new URLSearchParams(A))}if(w.startsWith("multipart/form-data")){let A=await f.formData(),$={};for(let[j,z]of A.entries())$[j]=z;return $}return{error:"Unknown request body type"}}var D1=(f,w)=>{try{return w(f)}catch{return f.replace(/(?:%[0-9A-Fa-f]{2})+/g,(g)=>{try{return w(g)}catch{return g}})}},_=(f)=>D1(f,decodeURI),k1=(f)=>{let w=f.indexOf("/",f.indexOf(":")+4),g=w;for(;g<f.length;g++){let A=f.charCodeAt(g);if(A===37){let $=f.indexOf("?",g),j=f.slice(w,$===-1?void 0:$);return _(j.includes("%25")?j.replace(/%25/g,"%2525"):j)}else if(A===63)break}return f.slice(w,g)};var H=(f)=>f!==null&&typeof f==="object"&&typeof f.then==="function",Df=(f)=>f!==null&&typeof f==="object"&&typeof f.status==="number"&&typeof f.headers==="object";async function k(f,w,g){if(!w?.length)return;for(let A=0;A<w.length;A++){let $=w[A](...g),j=$ instanceof Promise?await $:$;if(j&&f!=="onRequest")return j}}async function Kf(f,w,g){let A=f.globalMiddlewares;if(A.length)for(let j of A){let z=await j(g);if(z)return z}let $=f.middlewares.get(w);if($&&$.length)for(let j of $){let z=await j(g);if(z)return z}return null}async function i1(f,w,g){for(let A of f){let $=await A(w,g);if($)return $}}async function vf(f,w,g){let A=await K1(f,w,g),$=H(A)?await A:A;if($)return $}async function K1(f,w,g){if(w.endsWith("/"))w=w.slice(0,-1);if(!f.filters.has(w))if(f.filterFunction.length)for(let A of f.filterFunction){let $=await A(g);if($)return $}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function Nf(f,w,g){if(f.staticPath){let J=!0;if(f.staticRequestPath)J=g.startsWith(f.staticRequestPath);if(J){let Z=await v1(f,g,w);if(Z)return Z}}let j=(f.router.find(w.req.method,"*")?.handler).slice(-1);if(j.length>0){let J=await j[0](w);if(Df(J))return J}let z=f.routeNotFoundFunc(w);return z instanceof Promise?await z:z||I(404,`404 Route not found for ${g}`)}function I(f,w){return new Response(JSON.stringify({error:w}),{status:f,headers:{"Content-Type":"application/json"}})}async function v1(f,w,g){if(!f.staticPath)return null;let A=`${f.staticPath}${w}`;if(await Bun.file(A).exists()){let j=D(A);return g.file(A,j,200)}return null}async function N1(f,w,g,A,$){let j,z=f.url.indexOf("/",f.url.indexOf(":")+4),J=z;for(;J<f.url.length;J++){let V=f.url.charCodeAt(J);if(V===37){let C=f.url.indexOf("?",J),X=f.url.slice(z,C===-1?void 0:C);j=_(X.includes("%25")?X.replace(/%25/g,"%2525"):X);break}else if(V===63)break}if(!j)j=f.url.slice(z,J);let Z=g.router.find(f.method,j),B=new P(f,w,j,Z?.path,A,$);if(g.hasMiddleware){let V=await Kf(g,j,B);if(V)return V}if(g.hasFilterEnabled){let V=await vf(g,j,B);if(V)return V}if(g.hasPreHandlerHook){let V=await k("preHandler",g.hooks.preHandler,[B]);if(V)return V}let Y,G=Z?.handler;if(G.length===1){let V=G[0](B);Y=H(V)?await V:V}else for(let V=0;V<G.length;V++){let C=G[V](B);if(Y=H(C)?await C:C,Y)break}if(g.hasOnSendHook){let V=await k("onSend",g.hooks.onSend,[B,Y]);if(V)return V}return Y??await Nf(g,B,j)}export{N1 as default};
|
package/dist/http-exception.js
CHANGED
|
@@ -1 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
export class HTTPException extends Error {
|
|
2
|
+
constructor(status = 500, options) {
|
|
3
|
+
super(options === null || options === void 0 ? void 0 : options.message, { cause: options === null || options === void 0 ? void 0 : options.cause });
|
|
4
|
+
this.name = 'HTTPException';
|
|
5
|
+
this.res = options === null || options === void 0 ? void 0 : options.res;
|
|
6
|
+
this.status = status;
|
|
7
|
+
}
|
|
8
|
+
getResponse() {
|
|
9
|
+
if (this.res) {
|
|
10
|
+
const newResponse = new Response(this.res.body, {
|
|
11
|
+
status: this.status,
|
|
12
|
+
headers: this.res.headers,
|
|
13
|
+
});
|
|
14
|
+
return newResponse;
|
|
15
|
+
}
|
|
16
|
+
return new Response(this.message, {
|
|
17
|
+
status: this.status,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { describe, expect, it } from 'bun:test';
|
|
11
|
+
import { HTTPException } from './http-exception';
|
|
12
|
+
describe('HTTPException', () => {
|
|
13
|
+
it('Should be 401 HTTP exception object', () => __awaiter(void 0, void 0, void 0, function* () {
|
|
14
|
+
// We should throw an exception if is not authorized
|
|
15
|
+
// because next handlers should not be fired.
|
|
16
|
+
const exception = new HTTPException(401, {
|
|
17
|
+
message: 'Unauthorized',
|
|
18
|
+
});
|
|
19
|
+
const res = exception.getResponse();
|
|
20
|
+
expect(res.status).toBe(401);
|
|
21
|
+
expect(yield res.text()).toBe('Unauthorized');
|
|
22
|
+
expect(exception.status).toBe(401);
|
|
23
|
+
expect(exception.message).toBe('Unauthorized');
|
|
24
|
+
}));
|
|
25
|
+
it('Should be accessible to the object causing the exception', () => __awaiter(void 0, void 0, void 0, function* () {
|
|
26
|
+
// We should pass the cause of the error to the cause option
|
|
27
|
+
// because it makes debugging easier.
|
|
28
|
+
const error = new Error('Server Error');
|
|
29
|
+
const exception = new HTTPException(500, {
|
|
30
|
+
message: 'Internal Server Error',
|
|
31
|
+
cause: error,
|
|
32
|
+
});
|
|
33
|
+
const res = exception.getResponse();
|
|
34
|
+
expect(res.status).toBe(500);
|
|
35
|
+
expect(yield res.text()).toBe('Internal Server Error');
|
|
36
|
+
expect(exception.status).toBe(500);
|
|
37
|
+
expect(exception.message).toBe('Internal Server Error');
|
|
38
|
+
expect(exception.cause).toBe(error);
|
|
39
|
+
}));
|
|
40
|
+
it('Should prioritize the status code over the code in the response', () => __awaiter(void 0, void 0, void 0, function* () {
|
|
41
|
+
const exception = new HTTPException(400, {
|
|
42
|
+
res: new Response('An exception', {
|
|
43
|
+
status: 200,
|
|
44
|
+
}),
|
|
45
|
+
});
|
|
46
|
+
const res = exception.getResponse();
|
|
47
|
+
expect(res.status).toBe(400);
|
|
48
|
+
expect(yield res.text()).toBe('An exception');
|
|
49
|
+
}));
|
|
50
|
+
});
|