1
0

switch to return syntax

This commit is contained in:
2022-11-24 22:55:26 +01:00
parent c6dfaa3158
commit 61ad67766f

View File

@@ -13,19 +13,17 @@ export interface Route<TEnv> {
} }
/** /**
* Router Context * Router Context
* *
* @typedef RouterContext * @typedef RouterContext
* @property {RouterEnv} env Environment * @property {RouterEnv} env Environment
* @property {RouterRequest} req Request Object * @property {RouterRequest} req Request Object
* @property {RouterResponse} res Response Object * @property {ExecutionContext} ctx Context Object
* @property {RouterNext} next Next Handler */
*/ export interface RouterContext<TEnv = any> {
export interface RouterContext<TEnv> { env: TEnv
env: TEnv req: RouterRequest
req: RouterRequest ctx: ExecutionContext
res: RouterResponse
next: RouterNext
} }
/** /**
@@ -70,41 +68,14 @@ export interface RouterRequestQuery {
} }
/** /**
* Response Object * Handler Function
* *
* @typedef RouterResponse * @callback RouterHandler
* @property {Headers} headers Response headers object * @param {RouterContext} ctx
* @property {number} [status=204] Return status code (default: `204`) * @returns {Promise<Response | void> Response | void}
* @property {string | any} [body] Either an `object` (will be converted to JSON) or a string */
* @property {Response} [raw] A response object that is to be returned, this will void all other res properties and return this as is.
*/
export interface RouterResponse {
headers: Headers
status?: number
body?: string | any
raw?: Response,
webSocket?: WebSocket
}
/**
* Next Function
*
* @callback RouterNext
* @returns {Promise<void>}
*/
export interface RouterNext {
(): Promise<void>
}
/**
* Handler Function
*
* @callback RouterHandler
* @param {RouterContext} ctx
* @returns {Promise<void> | void}
*/
export interface RouterHandler<TEnv = any> { export interface RouterHandler<TEnv = any> {
(ctx: RouterContext<TEnv>): Promise<void> | void (ctx: RouterContext<TEnv>): Promise<Response | void> | Response | void
} }
/** /**
@@ -325,21 +296,33 @@ export class Router<TEnv = any> {
return this return this
} }
/** private setCorsHeaders(headers: Headers = new Headers()): Headers {
* Register route if (this.corsConfig.allowOrigin && !headers.has('Access-Control-Allow-Origin'))
* headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
* @private if (this.corsConfig.allowMethods && !headers.has('Access-Control-Allow-Methods'))
* @param {string} method HTTP request method headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
* @param {string} url URL String if (this.corsConfig.allowHeaders && !headers.has('Access-Control-Allow-Headers'))
* @param {RouterHandler[]} handlers Arrar of handler functions headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
* @returns {Router} if (this.corsConfig.maxAge && !headers.has('Access-Control-Max-Age'))
*/ headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
private register(method: string, url: string, handlers: RouterHandler<TEnv>[]): Router<TEnv> { return headers
this.routes.push({ }
method,
url, /**
handlers * Register route
}) *
* @private
* @param {string} method HTTP request method
* @param {string} url URL String
* @param {RouterHandler[]} handlers Arrar of handler functions
* @returns {Router}
*/
private register(method: string, url: string, handlers: RouterHandler<TEnv>[]): Router<TEnv> {
this.routes.push({
method,
url,
handlers
})
return this return this
} }
@@ -385,98 +368,57 @@ export class Router<TEnv = any> {
}) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method)) }) || this.routes.find(r => r.url === '*' && [request.method, '*'].includes(r.method))
} }
/** /**
* Handle requests * Handle requests
* *
* @param {TEnv} env * @param {TEnv} env
* @param {Request} request * @param {Request} request
* @param {any} [extend] * @param {any} [extend]
* @returns {Promise<Response>} * @returns {Promise<Response>}
*/ */
public async handle(env: TEnv, request: Request, extend: any = {}): Promise<Response> { public async handle(request: Request, env: TEnv, ctx: ExecutionContext, extend: any = {}): Promise<Response> {
try { const req: RouterRequest = {
const req: RouterRequest = { ...extend,
...extend, method: request.method,
method: request.method, headers: request.headers,
headers: request.headers, url: request.url,
url: request.url, cf: request.cf,
cf: request.cf, params: {},
params: {}, query: {},
query: {}, body: ''
body: '' }
}
const headers = new Headers() const route = this.getRoute(req)
const route = this.getRoute(req)
if (this.corsEnabled) { if (!route)
if (this.corsConfig.allowOrigin) return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
if (this.corsConfig.allowMethods)
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
if (this.corsConfig.allowHeaders)
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
if (this.corsConfig.maxAge)
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
if (!route && req.method === 'OPTIONS') { if (this.corsEnabled && req.method === 'OPTIONS') {
return new Response(null, { return new Response(null, {
headers, headers: this.setCorsHeaders(),
status: this.corsConfig.optionsSuccessStatus status: this.corsConfig.optionsSuccessStatus
}) })
} }
}
if (!route) const handlers = [...this.globalHandlers, ...route.handlers]
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
if (['POST', 'PUT', 'PATCH'].includes(req.method)) { let response: Response | undefined
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
try {
req.body = await request.json()
} catch {
req.body = {}
}
} else {
try {
req.body = await request.text()
} catch {
req.body = ''
}
}
}
const res: RouterResponse = { headers } for (const handler of handlers) {
const handlers = [...this.globalHandlers, ...route.handlers] const res = await handler({ env, req, ctx })
let prevIndex = -1
const runner = async (index: number) => { if (res) {
if (index === prevIndex) response = res
throw new Error('next() called multiple times') break
}
}
prevIndex = index if (!response)
return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
if (typeof handlers[index] === 'function') if (this.corsEnabled)
await handlers[index]({ env, req, res, next: async () => await runner(index + 1) }) this.setCorsHeaders(response.headers)
}
await runner(0) return response
}
if (typeof res.body === 'object') {
if (!res.headers.has('Content-Type'))
res.headers.set('Content-Type', 'application/json')
res.body = JSON.stringify(res.body)
}
if (res.raw)
return res.raw
return new Response([101, 204, 205, 304].includes(res.status || (res.body ? 200 : 204)) ? null : res.body, { status: res.status, headers: res.headers, webSocket: res.webSocket || null })
} catch(err) {
console.error(err)
return new Response(this.debugMode && err instanceof Error ? err.stack : '', { status: 500 })
}
}
>>>>>>> ad4557e (add editorconfig)
} }