1
0

add editorconfig

This commit is contained in:
2022-11-25 00:58:21 +01:00
parent 2529e5ce24
commit ad4557ecb3
2 changed files with 406 additions and 397 deletions

9
.editorconfig Normal file
View File

@@ -0,0 +1,9 @@
root = true
[*]
end_of_line = lf
insert_final_newline = false
[src/**.ts]
charset = utf-8
indent_style = tab

View File

@@ -1,481 +1,481 @@
/** /**
* Route Object * Route Object
* *
* @typedef Route * @typedef Route
* @property {string} method HTTP request method * @property {string} method HTTP request method
* @property {string} url URL String * @property {string} url URL String
* @property {RouterHandler[]} handlers Array of handler functions * @property {RouterHandler[]} handlers Array of handler functions
*/ */
export interface Route<TEnv> { export interface Route<TEnv> {
method: string method: string
url: string url: string
handlers: RouterHandler<TEnv>[] handlers: RouterHandler<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 {RouterResponse} res Response Object
* @property {RouterNext} next Next Handler * @property {RouterNext} next Next Handler
*/ */
export interface RouterContext<TEnv> { export interface RouterContext<TEnv> {
env: TEnv env: TEnv
req: RouterRequest req: RouterRequest
res: RouterResponse res: RouterResponse
next: RouterNext next: RouterNext
} }
/** /**
* Request Object * Request Object
* *
* @typedef RouterRequest * @typedef RouterRequest
* @property {string} url URL * @property {string} url URL
* @property {string} method HTTP request method * @property {string} method HTTP request method
* @property {RouterRequestParams} params Object containing all parameters defined in the url string * @property {RouterRequestParams} params Object containing all parameters defined in the url string
* @property {RouterRequestQuery} query Object containing all query parameters * @property {RouterRequestQuery} query Object containing all query parameters
* @property {Headers} headers Request headers object * @property {Headers} headers Request headers object
* @property {string | any} body Only available if method is `POST`, `PUT`, `PATCH` or `DELETE`. Contains either the received body string or a parsed object if valid JSON was sent. * @property {string | any} body Only available if method is `POST`, `PUT`, `PATCH` or `DELETE`. Contains either the received body string or a parsed object if valid JSON was sent.
* @property {IncomingRequestCfProperties} [cf] object containing custom Cloudflare properties. (https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object) * @property {IncomingRequestCfProperties} [cf] object containing custom Cloudflare properties. (https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object)
*/ */
export interface RouterRequest { export interface RouterRequest {
url: string url: string
method: string method: string
params: RouterRequestParams params: RouterRequestParams
query: RouterRequestQuery query: RouterRequestQuery
headers: Headers headers: Headers
body: string | any body: string | any
cf?: IncomingRequestCfProperties cf?: IncomingRequestCfProperties
[key: string]: any [key: string]: any
} }
/** /**
* Request Parameters * Request Parameters
* *
* @typedef RouterRequestParams * @typedef RouterRequestParams
*/ */
export interface RouterRequestParams { export interface RouterRequestParams {
[key: string]: string [key: string]: string
} }
/** /**
* Request Query * Request Query
* *
* @typedef RouterRequestQuery * @typedef RouterRequestQuery
*/ */
export interface RouterRequestQuery { export interface RouterRequestQuery {
[key: string]: string [key: string]: string
} }
/** /**
* Response Object * Response Object
* *
* @typedef RouterResponse * @typedef RouterResponse
* @property {Headers} headers Response headers object * @property {Headers} headers Response headers object
* @property {number} [status=204] Return status code (default: `204`) * @property {number} [status=204] Return status code (default: `204`)
* @property {string | any} [body] Either an `object` (will be converted to JSON) or a string * @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. * @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 { export interface RouterResponse {
headers: Headers headers: Headers
status?: number status?: number
body?: string | any body?: string | any
raw?: Response, raw?: Response,
webSocket?: WebSocket webSocket?: WebSocket
} }
/** /**
* Next Function * Next Function
* *
* @callback RouterNext * @callback RouterNext
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export interface RouterNext { export interface RouterNext {
(): Promise<void> (): Promise<void>
} }
/** /**
* Handler Function * Handler Function
* *
* @callback RouterHandler * @callback RouterHandler
* @param {RouterContext} ctx * @param {RouterContext} ctx
* @returns {Promise<void> | void} * @returns {Promise<void> | void}
*/ */
export interface RouterHandler<TEnv = any> { export interface RouterHandler<TEnv = any> {
(ctx: RouterContext<TEnv>): Promise<void> | void (ctx: RouterContext<TEnv>): Promise<void> | void
} }
/** /**
* CORS Config * CORS Config
* *
* @typedef RouterCorsConfig * @typedef RouterCorsConfig
* @property {string} [allowOrigin="*"] Access-Control-Allow-Origin (default: `*`) * @property {string} [allowOrigin="*"] Access-Control-Allow-Origin (default: `*`)
* @property {string} [allowMethods="*"] Access-Control-Allow-Methods (default: `*`) * @property {string} [allowMethods="*"] Access-Control-Allow-Methods (default: `*`)
* @property {string} [allowHeaders="*"] Access-Control-Allow-Headers (default: `*`) * @property {string} [allowHeaders="*"] Access-Control-Allow-Headers (default: `*`)
* @property {number} [maxAge=86400] Access-Control-Max-Age (default: `86400`) * @property {number} [maxAge=86400] Access-Control-Max-Age (default: `86400`)
* @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`) * @property {number} [optionsSuccessStatus=204] Return status code for OPTIONS request (default: `204`)
*/ */
export interface RouterCorsConfig { export interface RouterCorsConfig {
allowOrigin?: string allowOrigin?: string
allowMethods?: string allowMethods?: string
allowHeaders?: string allowHeaders?: string
maxAge?: number maxAge?: number
optionsSuccessStatus?: number optionsSuccessStatus?: number
} }
/** /**
* Router * Router
* *
* @public * @public
* @class * @class
*/ */
export class Router<TEnv = any> { export class Router<TEnv = any> {
/** /**
* Router Array * Router Array
* *
* @protected * @protected
* @type {Route[]} * @type {Route[]}
*/ */
protected routes: Route<TEnv>[] = [] protected routes: Route<TEnv>[] = []
/** /**
* Global Handlers * Global Handlers
* *
* @protected * @protected
* @type {RouterHandler[]} * @type {RouterHandler[]}
*/ */
protected globalHandlers: RouterHandler<TEnv>[] = [] protected globalHandlers: RouterHandler<TEnv>[] = []
/** /**
* Debug Mode * Debug Mode
* *
* @protected * @protected
* @type {boolean} * @type {boolean}
*/ */
protected debugMode: boolean = false protected debugMode: boolean = false
/** /**
* CORS Config * CORS Config
* *
* @protected * @protected
* @type {RouterCorsConfig} * @type {RouterCorsConfig}
*/ */
protected corsConfig: RouterCorsConfig = {} protected corsConfig: RouterCorsConfig = {}
/** /**
* CORS enabled * CORS enabled
*- *
* @protected * @protected
* @type {boolean} * @type {boolean}
*/ */
protected corsEnabled: boolean = false protected corsEnabled: boolean = false
/** /**
* Register global handlers * Register global handlers
* *
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public use(...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public use(...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
for (let handler of handlers) { for (let handler of handlers) {
this.globalHandlers.push(handler) this.globalHandlers.push(handler)
} }
return this return this
} }
/** /**
* Register CONNECT route * Register CONNECT route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public connect(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public connect(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('CONNECT', url, handlers) return this.register('CONNECT', url, handlers)
} }
/** /**
* Register DELETE route * Register DELETE route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public delete(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public delete(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('DELETE', url, handlers) return this.register('DELETE', url, handlers)
} }
/** /**
* Register GET route * Register GET route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public get(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public get(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('GET', url, handlers) return this.register('GET', url, handlers)
} }
/** /**
* Register HEAD route * Register HEAD route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public head(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public head(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('HEAD', url, handlers) return this.register('HEAD', url, handlers)
} }
/** /**
* Register OPTIONS route * Register OPTIONS route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public options(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public options(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('OPTIONS', url, handlers) return this.register('OPTIONS', url, handlers)
} }
/** /**
* Register PATCH route * Register PATCH route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public patch(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public patch(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('PATCH', url, handlers) return this.register('PATCH', url, handlers)
} }
/** /**
* Register POST route * Register POST route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public post(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public post(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('POST', url, handlers) return this.register('POST', url, handlers)
} }
/** /**
* Register PUT route * Register PUT route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public put(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public put(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('PUT', url, handlers) return this.register('PUT', url, handlers)
} }
/** /**
* Register TRACE route * Register TRACE route
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public trace(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public trace(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('TRACE', url, handlers) return this.register('TRACE', url, handlers)
} }
/** /**
* Register route, ignoring method * Register route, ignoring method
* *
* @param {string} url * @param {string} url
* @param {RouterHandler[]} handlers * @param {RouterHandler[]} handlers
* @returns {Router} * @returns {Router}
*/ */
public any(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> { public any(url: string, ...handlers: RouterHandler<TEnv>[]): Router<TEnv> {
return this.register('*', url, handlers) return this.register('*', url, handlers)
} }
/** /**
* Debug Mode * Debug Mode
* *
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true) * @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
* @returns {Router} * @returns {Router}
*/ */
public debug(state: boolean = true): Router<TEnv> { public debug(state: boolean = true): Router<TEnv> {
this.debugMode = state this.debugMode = state
return this return this
} }
/** /**
* Enable CORS support * Enable CORS support
* *
* @param {RouterCorsConfig} [config] * @param {RouterCorsConfig} [config]
* @returns {Router} * @returns {Router}
*/ */
public cors(config?: RouterCorsConfig): Router<TEnv> { public cors(config?: RouterCorsConfig): Router<TEnv> {
this.corsEnabled = true this.corsEnabled = true
this.corsConfig = { this.corsConfig = {
allowOrigin: config?.allowOrigin || '*', allowOrigin: config?.allowOrigin || '*',
allowMethods: config?.allowMethods || '*', allowMethods: config?.allowMethods || '*',
allowHeaders: config?.allowHeaders || '*', allowHeaders: config?.allowHeaders || '*',
maxAge: config?.maxAge || 86400, maxAge: config?.maxAge || 86400,
optionsSuccessStatus: config?.optionsSuccessStatus || 204 optionsSuccessStatus: config?.optionsSuccessStatus || 204
} }
return this return this
} }
/** /**
* Register route * Register route
* *
* @private * @private
* @param {string} method HTTP request method * @param {string} method HTTP request method
* @param {string} url URL String * @param {string} url URL String
* @param {RouterHandler[]} handlers Arrar of handler functions * @param {RouterHandler[]} handlers Arrar of handler functions
* @returns {Router} * @returns {Router}
*/ */
private register(method: string, url: string, handlers: RouterHandler<TEnv>[]): Router<TEnv> { private register(method: string, url: string, handlers: RouterHandler<TEnv>[]): Router<TEnv> {
this.routes.push({ this.routes.push({
method, method,
url, url,
handlers handlers
}) })
return this return this
} }
/** /**
* Get Route by request * Get Route by request
* *
* @private * @private
* @param {RouterRequest} request * @param {RouterRequest} request
* @returns {Route | undefined} * @returns {Route | undefined}
*/ */
private getRoute(request: RouterRequest): Route<TEnv> | undefined { private getRoute(request: RouterRequest): Route<TEnv> | undefined {
const url = new URL(request.url) const url = new URL(request.url)
const pathArr = url.pathname.split('/').filter(i => i) const pathArr = url.pathname.split('/').filter(i => i)
return this.routes.find(r => { return this.routes.find(r => {
const routeArr = r.url.split('/').filter(i => i) const routeArr = r.url.split('/').filter(i => i)
if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length) if (![request.method, '*'].includes(r.method) || routeArr.length !== pathArr.length)
return false return false
const params: RouterRequestParams = {} const params: RouterRequestParams = {}
for (let i = 0; i < routeArr.length; i++) { for (let i = 0; i < routeArr.length; i++) {
if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':') if (routeArr[i] !== pathArr[i] && routeArr[i][0] !== ':')
return false return false
if (routeArr[i][0] === ':') if (routeArr[i][0] === ':')
params[routeArr[i].substring(1)] = pathArr[i] params[routeArr[i].substring(1)] = pathArr[i]
} }
request.params = params request.params = params
const query: any = {} const query: any = {}
for (const [k, v] of url.searchParams.entries()) { for (const [k, v] of url.searchParams.entries()) {
query[k] = v query[k] = v
} }
request.query = query request.query = query
return true return true
}) || 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(env: TEnv, request: Request, extend: any = {}): Promise<Response> {
try { 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 headers = new Headers()
const route = this.getRoute(req) const route = this.getRoute(req)
if (this.corsEnabled) { if (this.corsEnabled) {
if (this.corsConfig.allowOrigin) if (this.corsConfig.allowOrigin)
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin) headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
if (this.corsConfig.allowMethods) if (this.corsConfig.allowMethods)
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods) headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
if (this.corsConfig.allowHeaders) if (this.corsConfig.allowHeaders)
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders) headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
if (this.corsConfig.maxAge) if (this.corsConfig.maxAge)
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString()) headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
if (!route && req.method === 'OPTIONS') { if (!route && req.method === 'OPTIONS') {
return new Response(null, { return new Response(null, {
headers, headers,
status: this.corsConfig.optionsSuccessStatus status: this.corsConfig.optionsSuccessStatus
}) })
} }
} }
if (!route) if (!route)
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 }) return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
if (['POST', 'PUT', 'PATCH'].includes(req.method)) { if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) { if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
try { try {
req.body = await request.json() req.body = await request.json()
} catch { } catch {
req.body = {} req.body = {}
} }
} else { } else {
try { try {
req.body = await request.text() req.body = await request.text()
} catch { } catch {
req.body = '' req.body = ''
} }
} }
} }
const res: RouterResponse = { headers } const res: RouterResponse = { headers }
const handlers = [...this.globalHandlers, ...route.handlers] const handlers = [...this.globalHandlers, ...route.handlers]
let prevIndex = -1 let prevIndex = -1
const runner = async (index: number) => { const runner = async (index: number) => {
if (index === prevIndex) if (index === prevIndex)
throw new Error('next() called multiple times') throw new Error('next() called multiple times')
prevIndex = index prevIndex = index
if (typeof handlers[index] === 'function') if (typeof handlers[index] === 'function')
await handlers[index]({ env, req, res, next: async () => await runner(index + 1) }) await handlers[index]({ env, req, res, next: async () => await runner(index + 1) })
} }
await runner(0) await runner(0)
if (typeof res.body === 'object') { if (typeof res.body === 'object') {
if (!res.headers.has('Content-Type')) if (!res.headers.has('Content-Type'))
res.headers.set('Content-Type', 'application/json') res.headers.set('Content-Type', 'application/json')
res.body = JSON.stringify(res.body) res.body = JSON.stringify(res.body)
} }
if (res.raw) if (res.raw)
return 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 }) 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) { } catch(err) {
console.error(err) console.error(err)
return new Response(this.debugMode && err instanceof Error ? err.stack : '', { status: 500 }) return new Response(this.debugMode && err instanceof Error ? err.stack : '', { status: 500 })
} }
} }
} }