Skip to content

Commit

Permalink
feat: restrict router accepted generic type
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiaaas committed Feb 7, 2023
1 parent f0c99a8 commit 7c5c6a9
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/router.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Express } from "express"
import type { Express, Router } from "express"
import path from "path"

import type { Options } from "./types"
Expand All @@ -10,6 +10,8 @@ import { getHandlers, getMethodKey } from "./utils"

const REQUIRE_MAIN_FILE = path.dirname(require.main?.filename || process.cwd())

type ExpressLike = Express | Router

/**
* Attach routes to an Express app or router instance
*
Expand All @@ -20,7 +22,10 @@ const REQUIRE_MAIN_FILE = path.dirname(require.main?.filename || process.cwd())
* @param app An express app or router instance
* @param options An options object (optional)
*/
const createRouter = <T = Express>(app: T, options: Options = {}): T => {
const createRouter = <T extends ExpressLike = ExpressLike>(
app: T,
options: Options = {}
): T => {
const files = walkTree(
options.directory || path.join(REQUIRE_MAIN_FILE, "routes")
)
Expand All @@ -45,7 +50,7 @@ const createRouter = <T = Express>(app: T, options: Options = {}): T => {

// wildcard default export route matching
if (typeof exports.default !== "undefined") {
;(app as unknown as any).all(url, ...getHandlers(exports.default))
app.all.apply(null, [url, ...getHandlers(exports.default)])
}
}

Expand Down

0 comments on commit 7c5c6a9

Please sign in to comment.