Skip to content
This repository has been archived by the owner on Jun 27, 2024. It is now read-only.

Commit

Permalink
feat(ext): add onPlugIn event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
boywithkeyboard committed Aug 6, 2023
1 parent 0454cfe commit 0d57e03
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 4 deletions.
42 changes: 38 additions & 4 deletions cheetah.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export class cheetah extends base<cheetah>() {
#proxy
#routes: Set<[Uppercase<Method>, string, RegExp, HandlerOrSchema[]]>
#runtime: 'deno' | 'cloudflare'
#onPlugIn

constructor({
base,
Expand Down Expand Up @@ -109,6 +110,7 @@ export class cheetah extends base<cheetah>() {
this.#runtime = typeof globalThis?.Deno?.serve !== 'function'
? 'cloudflare'
: 'deno'
this.#onPlugIn = false
}

/* use ---------------------------------------------------------------------- */
Expand Down Expand Up @@ -242,24 +244,56 @@ export class cheetah extends base<cheetah>() {
let body: Response | void = undefined

for (const e of this.#extensions.values()) {
if (this.#onPlugIn === true && e[1].onPlugIn !== undefined) {
await e[1].onPlugIn({
env: __app.env,
routes: this.#routes,
runtime: this.#runtime,
setRoute: (method, pathname, ...handlers) => {
this.#routes.add([
method.toUpperCase() as Uppercase<Method>,
pathname,
RegExp(
`^${
(pathname
.replace(/\/+(\/|$)/g, '$1'))
.replace(/(\/?\.?):(\w+)\+/g, '($1(?<$2>*))')
.replace(/(\/?\.?):(\w+)/g, '($1(?<$2>[^$1/]+?))')
.replace(/\./g, '\\.')
.replace(/(\/?)\*/g, '($1.*)?')
}/*$`,
),
// @ts-ignore:
handlers,
])
},
})
}

if (
e[0] !== '*' &&
__app.request.pathname.indexOf(e[0]) !== 0
) {
continue
}

const { onRequest } = e[1]

if (onRequest !== undefined) {
const result = await onRequest({ app: __app, req, _: e[1].__config })
if (e[1].onRequest !== undefined) {
const result = await e[1].onRequest({
app: __app,
req,
_: e[1].__config,
})

if (result !== undefined) {
body = result
}
}
}

if (this.#onPlugIn) {
this.#onPlugIn = false
}

if (body !== undefined) {
return body
}
Expand Down
76 changes: 76 additions & 0 deletions extensions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// Copyright 2023 Samuel Kopp. All rights reserved. Apache-2.0 license.
import { ZodString, ZodUnion } from 'https://deno.land/x/zod@v3.21.4/types.ts'
import { Handler, ObjectType } from './handler.ts'
import { AppContext, Context } from './mod.ts'
import { Method } from './base.ts'

type HasRequired<T> = Partial<T> extends T ? false : true

Expand All @@ -10,6 +13,76 @@ export type Extension<
Config extends Record<string, unknown> | unknown = never,
> = {
__config: Config | undefined
onPlugIn: HasRequired<Config> extends true ? ((context: {
env: AppContext['env']
routes: AppContext['routes']
runtime: AppContext['runtime']
setRoute: <
Pathname extends `/${string}`,
// deno-lint-ignore no-explicit-any
ValidatedBody extends ObjectType | ZodString | ZodUnion<any>,
ValidatedCookies extends ObjectType,
ValidatedHeaders extends ObjectType,
ValidatedQuery extends ObjectType,
>(
method: Method,
pathname: Pathname,
...handler: (
| {
body?: ValidatedBody
cookies?: ValidatedCookies
headers?: ValidatedHeaders
query?: ValidatedQuery
/** @deprecated please pass this option to the `c.req.body()` method! */
transform?: boolean // TODO remove at v2.0
cors?: string
}
| Handler<
Pathname,
ValidatedBody,
ValidatedCookies,
ValidatedHeaders,
ValidatedQuery
>
)[]
) => void | Promise<void>
settings: Config
}) => void | Promise<void>)
: ((context: {
env: AppContext['env']
routes: AppContext['routes']
runtime: AppContext['runtime']
setRoute: <
Pathname extends `/${string}`,
// deno-lint-ignore no-explicit-any
ValidatedBody extends ObjectType | ZodString | ZodUnion<any>,
ValidatedCookies extends ObjectType,
ValidatedHeaders extends ObjectType,
ValidatedQuery extends ObjectType,
>(
method: Method,
pathname: Pathname,
...handlers: (
| {
body?: ValidatedBody
cookies?: ValidatedCookies
headers?: ValidatedHeaders
query?: ValidatedQuery
/** @deprecated please pass this option to the `c.req.body()` method! */
transform?: boolean // TODO remove at v2.0
cors?: string
}
| Handler<
Pathname,
ValidatedBody,
ValidatedCookies,
ValidatedHeaders,
ValidatedQuery
>
)[]
) => void
settings?: Config
}) => void | Promise<void>)
onRequest?: HasRequired<Config> extends true ? ((context: {
app: AppContext
req: Request
Expand Down Expand Up @@ -51,15 +124,18 @@ export function validExtension(ext: Record<string, unknown>) {
export function createExtension<
Config extends Record<string, unknown> | unknown = unknown,
>({
onPlugIn,
onRequest,
onResponse,
}: {
onPlugIn?: Extension<Config>['onPlugIn']
onRequest?: Extension<Config>['onRequest']
onResponse?: Extension<Config>['onResponse']
}) {
return ((__config?: Config) => {
return {
__config,
onPlugIn,
onRequest,
onResponse,
[Symbol('cheetah.extension')]: 'v1.0',
Expand Down

0 comments on commit 0d57e03

Please sign in to comment.