Skip to content

Commit

Permalink
Merge pull request #2680 from honojs/docs/jsdoc-middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored May 24, 2024
2 parents 032c1b8 + 776b5e9 commit 3fb4aef
Show file tree
Hide file tree
Showing 32 changed files with 984 additions and 52 deletions.
31 changes: 31 additions & 0 deletions deno_dist/middleware/basic-auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,37 @@ type BasicAuthOptions =
hashFunction?: Function
}

/**
* Basic authentication middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/basic-auth}
*
* @param {BasicAuthOptions} options - The options for the basic authentication middleware.
* @param {string} options.username - The username for authentication.
* @param {string} options.password - The password for authentication.
* @param {string} [options.realm="Secure Area"] - The realm attribute for the WWW-Authenticate header.
* @param {Function} [options.hashFunction] - The hash function used for secure comparison.
* @param {Function} [options.verifyUser] - The function to verify user credentials.
* @returns {MiddlewareHandler} The middleware handler function.
* @throws {HTTPException} If neither "username and password" nor "verifyUser" options are provided.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(
* '/auth/*',
* basicAuth({
* username: 'hono',
* password: 'acoolproject',
* })
* )
*
* app.get('/auth/page', (c) => {
* return c.text('You are authorized')
* })
* ```
*/
export const basicAuth = (
options: BasicAuthOptions,
...users: { username: string; password: string }[]
Expand Down
29 changes: 29 additions & 0 deletions deno_dist/middleware/bearer-auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,35 @@ type BearerAuthOptions =
hashFunction?: Function
}

/**
* Bearer authentication middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/bearer-auth}
*
* @param {BearerAuthOptions} options - The options for the bearer authentication middleware.
* @param {string | string[]} [options.token] - The string or array of strings to validate the incoming bearer token against.
* @param {Function} [options.verifyToken] - The function to verify the token.
* @param {string} [options.realm=""] - The domain name of the realm, as part of the returned WWW-Authenticate challenge header.
* @param {string} [options.prefix="Bearer"] - The prefix (or known as `schema`) for the Authorization header value.
* @param {string} [options.headerName=Authorization] - The header name.
* @param {Function} [options.hashFunction] - A function to handle hashing for safe comparison of authentication tokens.
* @returns {MiddlewareHandler} The middleware handler function.
* @throws {Error} If neither "token" nor "verifyToken" options are provided.
* @throws {HTTPException} If authentication fails, with 401 status code for missing or invalid token, or 400 status code for invalid request.
*
* @example
* ```ts
* const app = new Hono()
*
* const token = 'honoiscool'
*
* app.use('/api/*', bearerAuth({ token }))
*
* app.get('/api/page', (c) => {
* return c.json({ message: 'You are authorized' })
* })
* ```
*/
export const bearerAuth = (options: BearerAuthOptions): MiddlewareHandler => {
if (!('token' in options || 'verifyToken' in options)) {
throw new Error('bearer auth middleware requires options for "token"')
Expand Down
35 changes: 24 additions & 11 deletions deno_dist/middleware/body-limit/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,34 @@ class BodyLimitError extends Error {
}

/**
* Body Limit Middleware
* Body limit middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/body-limit}
*
* @param {BodyLimitOptions} options - The options for the body limit middleware.
* @param {number} options.maxSize - The maximum body size allowed.
* @param {OnError} [options.onError] - The error handler to be invoked if the specified body size is exceeded.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.post(
* '/hello',
* bodyLimit({
* maxSize: 100 * 1024, // 100kb
* onError: (c) => {
* return c.text('overflow :(', 413)
* }
* }),
* (c) => {
* return c.text('pass :)')
* }
* '/upload',
* bodyLimit({
* maxSize: 50 * 1024, // 50kb
* onError: (c) => {
* return c.text('overflow :(', 413)
* },
* }),
* async (c) => {
* const body = await c.req.parseBody()
* if (body['file'] instanceof File) {
* console.log(`Got file sized: ${body['file'].size}`)
* }
* return c.text('pass :)')
* }
* )
* ```
*/
Expand Down
25 changes: 25 additions & 0 deletions deno_dist/middleware/cache/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,31 @@
import type { Context } from '../../context.ts'
import type { MiddlewareHandler } from '../../types.ts'

/**
* cache middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/cache}
*
* @param {Object} options - The options for the cache middleware.
* @param {string | Function} options.cacheName - The name of the cache. Can be used to store multiple caches with different identifiers.
* @param {boolean} [options.wait=false] - A boolean indicating if Hono should wait for the Promise of the `cache.put` function to resolve before continuing with the request. Required to be true for the Deno environment.
* @param {string} [options.cacheControl] - A string of directives for the `Cache-Control` header.
* @param {string | string[]} [options.vary] - Sets the `Vary` header in the response. If the original response header already contains a `Vary` header, the values are merged, removing any duplicates.
* @param {Function} [options.keyGenerator] - Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters.
* @returns {MiddlewareHandler} The middleware handler function.
* @throws {Error} If the `vary` option includes "*".
*
* @example
* ```ts
* app.get(
* '*',
* cache({
* cacheName: 'my-app',
* cacheControl: 'max-age=3600',
* })
* )
* ```
*/
export const cache = (options: {
cacheName: string | ((c: Context) => Promise<string> | string)
wait?: boolean
Expand Down
16 changes: 16 additions & 0 deletions deno_dist/middleware/compress/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,22 @@ interface CompressionOptions {
encoding?: (typeof ENCODING_TYPES)[number]
}

/**
* Compress middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/compress}
*
* @param {CompressionOptions} [options] - The options for the compress middleware.
* @param {'gzip' | 'deflate'} [options.encoding] - The compression scheme to allow for response compression. Either 'gzip' or 'deflate'. If not defined, both are allowed and will be used based on the Accept-Encoding header. 'gzip' is prioritized if this option is not provided and the client provides both in the Accept-Encoding header.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(compress())
* ```
*/
export const compress = (options?: CompressionOptions): MiddlewareHandler => {
return async function compress(ctx, next) {
await next()
Expand Down
39 changes: 39 additions & 0 deletions deno_dist/middleware/cors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,45 @@ type CORSOptions = {
exposeHeaders?: string[]
}

/**
* CORS middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/cors}
*
* @param {CORSOptions} [options] - The options for the CORS middleware.
* @param {string | string[] | ((origin: string, c: Context) => string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header.
* @param {string[]} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header.
* @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header.
* @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header.
* @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header.
* @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use('/api/*', cors())
* app.use(
* '/api2/*',
* cors({
* origin: 'http://example.com',
* allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
* allowMethods: ['POST', 'GET', 'OPTIONS'],
* exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
* maxAge: 600,
* credentials: true,
* })
* )
*
* app.all('/api/abc', (c) => {
* return c.json({ success: true })
* })
* app.all('/api2/abc', (c) => {
* return c.json({ success: true })
* })
* ```
*/
export const cors = (options?: CORSOptions): MiddlewareHandler => {
const defaults: CORSOptions = {
origin: '*',
Expand Down
37 changes: 37 additions & 0 deletions deno_dist/middleware/csrf/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,43 @@ const isSafeMethodRe = /^(GET|HEAD)$/
const isRequestedByFormElementRe =
/^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/

/**
* CSRF protection middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/csrf}
*
* @param {CSRFOptions} [options] - The options for the CSRF protection middleware.
* @param {string|string[]|(origin: string, context: Context) => boolean} [options.origin] - Specify origins.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(csrf())
*
* // Specifying origins with using `origin` option
* // string
* app.use(csrf({ origin: 'myapp.example.com' }))
*
* // string[]
* app.use(
* csrf({
* origin: ['myapp.example.com', 'development.myapp.example.com'],
* })
* )
*
* // Function
* // It is strongly recommended that the protocol be verified to ensure a match to `$`.
* // You should *never* do a forward match.
* app.use(
* '*',
* csrf({
* origin: (origin) => /https:\/\/(\w+\.)?myapp\.example\.com$/.test(origin),
* })
* )
* ```
*/
export const csrf = (options?: CSRFOptions): MiddlewareHandler => {
const handler: IsAllowedOriginHandler = ((optsOrigin) => {
if (!optsOrigin) {
Expand Down
20 changes: 20 additions & 0 deletions deno_dist/middleware/etag/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,26 @@ function etagMatches(etag: string, ifNoneMatch: string | null) {
return ifNoneMatch != null && ifNoneMatch.split(/,\s*/).indexOf(etag) > -1
}

/**
* ETag middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/etag}
*
* @param {ETagOptions} [options] - The options for the ETag middleware.
* @param {boolean} [options.weak=false] - Define using or not using a weak validation. If true is set, then `W/` is added to the prefix of the value.
* @param {string[]} [options.retainedHeaders=RETAINED_304_HEADERS] - The headers that you want to retain in the 304 Response.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use('/etag/*', etag())
* app.get('/etag/abc', (c) => {
* return c.text('Hono is cool')
* })
* ```
*/
export const etag = (options?: ETagOptions): MiddlewareHandler => {
const retainedHeaders = options?.retainedHeaders ?? RETAINED_304_HEADERS
const weak = options?.weak ?? false
Expand Down
58 changes: 58 additions & 0 deletions deno_dist/middleware/jsx-renderer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,40 @@ const createRenderer =
}
}

/**
* JSX renderer middleware for hono.
*
* @see {@link{https://hono.dev/middleware/builtin/jsx-renderer}}
*
* @param {ComponentWithChildren} [component] - The component to render, which can accept children and props.
* @param {RendererOptions} [options] - The options for the JSX renderer middleware.
* @param {boolean | string} [options.docType=true] - The DOCTYPE to be added at the beginning of the HTML. If set to false, no DOCTYPE will be added.
* @param {boolean | Record<string, string>} [options.stream=false] - If set to true, enables streaming response with default headers. If a record is provided, custom headers will be used.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.get(
* '/page/*',
* jsxRenderer(({ children }) => {
* return (
* <html>
* <body>
* <header>Menu</header>
* <div>{children}</div>
* </body>
* </html>
* )
* })
* )
*
* app.get('/page/about', (c) => {
* return c.render(<h1>About me!</h1>)
* })
* ```
*/
export const jsxRenderer = (
component?: ComponentWithChildren,
options?: RendererOptions
Expand All @@ -82,6 +116,30 @@ export const jsxRenderer = (
return next()
}

/**
* useRequestContext for Hono.
*
* @template E - The environment type.
* @template P - The parameter type.
* @template I - The input type.
* @returns {Context<E, P, I>} An instance of Context.
*
* @example
* ```ts
* const RequestUrlBadge: FC = () => {
* const c = useRequestContext()
* return <b>{c.req.url}</b>
* }
*
* app.get('/page/info', (c) => {
* return c.render(
* <div>
* You are accessing: <RequestUrlBadge />
* </div>
* )
* })
* ```
*/
export const useRequestContext = <
E extends Env = any,
P extends string = any,
Expand Down
27 changes: 27 additions & 0 deletions deno_dist/middleware/jwt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,33 @@ declare module '../../context.ts' {
}
}

/**
* JWT Auth middleware for Hono.
*
* @see {@link https://hono.dev/middleware/builtin/jwt}
*
* @param {object} options - The options for the JWT middleware.
* @param {string} [options.secret] - A value of your secret key.
* @param {string} [options.cookie] - If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.
* @param {SignatureAlgorithm} [options.alg=HS256] - An algorithm type that is used for verifying. Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(
* '/auth/*',
* jwt({
* secret: 'it-is-very-secret',
* })
* )
*
* app.get('/auth/page', (c) => {
* return c.text('You are authorized')
* })
* ```
*/
export const jwt = (options: {
secret: string
cookie?: string
Expand Down
Loading

0 comments on commit 3fb4aef

Please sign in to comment.