Skip to content

Commit

Permalink
fix:route's base bugs.
Browse files Browse the repository at this point in the history
  • Loading branch information
chizuki committed Oct 7, 2022
1 parent 2bca586 commit 8afa2d7
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
13 changes: 9 additions & 4 deletions packages/core/src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { MaybePromise } from "maybe-types"
import { parseFormdata } from "./utils/parse"

import { version } from "../package.json"
import { slash } from "./utils/common"

export const FOURZE_VERSION = version

Expand Down Expand Up @@ -58,6 +59,7 @@ export interface FourzeRoute extends FourzeBaseRoute {
readonly [FOURZE_ROUTE_SYMBOL]: true
readonly pathRegex: RegExp
readonly pathParams: RegExpMatchArray
readonly finalPath: string
meta: Record<string, any>
match: (url: string, method?: string) => boolean
}
Expand All @@ -76,6 +78,8 @@ export function isRoute(route: any): route is FourzeRoute {

const REQUEST_PATH_REGEX = new RegExp(`^(${FOURZE_METHODS.join("|")}):.*`, "i")

const NOT_NEED_BASE = /^((https?|file):)?\/\//gi

const PARAM_KEY_REGEX = /(\:[\w_-]+)|(\{[\w_-]+\})/g

export function defineRoute(route: FourzeBaseRoute): FourzeRoute {
Expand All @@ -100,13 +104,14 @@ export function defineRoute(route: FourzeBaseRoute): FourzeRoute {
handle,
match,
meta,
get finalPath() {
return base && !NOT_NEED_BASE.test(path) ? slash(`${base}${path}`) : path
},
get pathParams() {
const p = base ? `${base}${path}` : path
return p.match(PARAM_KEY_REGEX) ?? []
return this.finalPath.match(PARAM_KEY_REGEX) ?? []
},
get pathRegex() {
const p = base ? `${base}${path}` : path
return new RegExp(`^${p.replace(PARAM_KEY_REGEX, "([a-zA-Z0-9_-\\s]+)?")}`.concat("(.*)([?&#].*)?$"), "i")
return new RegExp(`^${this.finalPath.replace(PARAM_KEY_REGEX, "([a-zA-Z0-9_-\\s]+)?")}`.concat("(.*)([?&#].*)?$"), "i")
},
get [FOURZE_ROUTE_SYMBOL](): true {
return true
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/utils/common.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
export const isNode = () => typeof window === "undefined"

export const isBrowser = () => !isNode()

export function slash(p: string): string {
return p.replace(/\\/g, "/")
}

export function joinPath(...paths: string[]) {
return slash(paths.join("/"))
}
5 changes: 1 addition & 4 deletions packages/server/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { slash } from "@fourze/core"
import os from "os"
import path from "path"

Expand All @@ -10,7 +11,3 @@ export const isWindows = os.platform() === "win32"
export function normalizePath(id: string) {
return path.posix.normalize(isWindows ? slash(id) : id)
}

export function slash(p: string): string {
return p.replace(/\\/g, "/")
}

0 comments on commit 8afa2d7

Please sign in to comment.