Skip to content

Commit

Permalink
chore:add loadmodule trycacth.
Browse files Browse the repository at this point in the history
  • Loading branch information
chizuki committed Jul 22, 2022
1 parent bccf61a commit 4963e36
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 41 deletions.
39 changes: 26 additions & 13 deletions packages/core/src/mock/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { FourzeRoute } from "../shared"
import type { FourzeResponse, FourzeRoute } from "../shared"
import { createRequest, createResponse } from "../shared"

const originalFetch = globalThis.fetch
Expand All @@ -24,9 +24,18 @@ class ProxyFetchResponse implements Response {

data: any

constructor(url: string, data: any) {
this.url = url
this.data = data
_response: FourzeResponse

constructor(response: FourzeResponse) {
this.url = response.req.url!
this.data = response.result
for (let [key, value] of Object.entries(response.headers)) {
if (Array.isArray(value)) {
value = value.join(",")
}
this.headers.append(key, value ?? "")
}
this._response = response
}

arrayBuffer(): Promise<ArrayBuffer> {
Expand All @@ -46,7 +55,7 @@ class ProxyFetchResponse implements Response {
}

clone(): Response {
return new ProxyFetchResponse(this.url, this.data)
return new ProxyFetchResponse(this._response)
}

text(): Promise<string> {
Expand All @@ -59,12 +68,8 @@ export function createProxyFetch(routes: FourzeRoute[] = []) {
let url: string
let method: string = "GET"
let body: any
if (typeof input === "string") {
url = input
method = init?.method ?? method
body = init?.body ?? {}
} else if (input instanceof URL) {
url = input.href
if (typeof input === "string" || input instanceof URL) {
url = input.toString()
method = init?.method ?? method
body = init?.body ?? {}
} else {
Expand All @@ -75,13 +80,21 @@ export function createProxyFetch(routes: FourzeRoute[] = []) {

const route = routes.find(e => e.match(url, method))
if (route) {
const request = createRequest({ url, method, body })
const headers: Record<string, string[]> = {}
new Headers(init?.headers ?? {}).forEach((value, key) => {
if (headers[key]) {
headers[key].push(value)
} else {
headers[key] = [value]
}
})
const request = createRequest({ url, method, body, headers })

const response = createResponse()

await route.dispatch(request, response)

return Promise.resolve(new ProxyFetchResponse(url, response.result))
return new ProxyFetchResponse(response)
}
return originalFetch(input, init)
}
Expand Down
12 changes: 4 additions & 8 deletions packages/core/src/mock/xhr.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createRequest, createResponse } from "../shared"
import type { FourzeRequest, FourzeRoute } from "../shared"
import { createRequest, createResponse } from "../shared"
import { HTTP_STATUS_CODES } from "./code"

type XHR_RESPONSE_PROPERTY = "readyState" | "responseURL" | "status" | "statusText" | "responseType" | "response" | "responseText" | "responseXML"
Expand Down Expand Up @@ -146,18 +146,14 @@ export function createProxyXHR(routes: FourzeRoute[]) {
return this
}

Object.defineProperty(MockXHR.prototype, "$routes", () => routes)

MockXHR.UNSENT = 0
MockXHR.OPENED = 1
MockXHR.HEADERS_RECEIVED = 2
MockXHR.LOADING = 3
MockXHR.DONE = 4

Object.defineProperty(MockXHR.prototype, "$routes", {
get() {
return routes
}
})

MockXHR.prototype.setRequestHeader = function (this: MockXmlHttpRequest, name: string, value: string) {
if (!!this.$base) {
this.$base.setRequestHeader(name, value)
Expand Down Expand Up @@ -208,7 +204,7 @@ export function createProxyXHR(routes: FourzeRoute[]) {

console.log("mock url ->", url, routes)

this.$route = this.$routes.find(e => e.match(url.toString(), method))
this.$route = routes.find(e => e.match(url.toString(), method))
console.log("find mock route", this.$route)
this.$base = null
this.request = createRequest({
Expand Down
8 changes: 3 additions & 5 deletions packages/server/src/renderer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import path from "path"
import type { FourzeRequest, FourzeResponse } from "@fourze/core"
import { logger } from "@fourze/core"
import fs from "fs"
import mime from "mime"
import { logger } from "@fourze/core"
import type { FourzeRequest, FourzeResponse } from "@fourze/core"
import path from "path"
import type { FourzeMiddleware } from "./app"

export interface FourzeRendererOptions {
Expand Down Expand Up @@ -61,8 +61,6 @@ export function createRenderer(options: FourzeRendererOptions | string = {}): Fo
let p: string = path.join(dir, url)
p = path.normalize(p)

let i = 0

let content: Buffer | undefined
for (let template of templates) {
if ((content = template(p))) {
Expand Down
34 changes: 19 additions & 15 deletions packages/server/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ export function createRouter(params: FourzeRouterOptions | FourzeSetup): FourzeR
}

const loadJsModule = async (mod: string) => {
this.remove(mod)
const module = require(mod)
const route = module?.exports?.default ?? module?.default
if (isFourze(route) || isRoute(route) || (Array.isArray(route) && route.some(isRoute))) {
Expand All @@ -100,21 +99,23 @@ export function createRouter(params: FourzeRouterOptions | FourzeSetup): FourzeR
const loadTsModule = async (mod: string) => {
const modName = mod.replace(".ts", TEMPORARY_FILE_SUFFIX)
const { build } = require("esbuild") as typeof import("esbuild")
try {
await build({
entryPoints: [mod],
external: ["@fourze/core"],
outfile: modName,
write: true,
platform: "node",
bundle: true,
format: "cjs",
metafile: true,
target: "es6"
})

await build({
entryPoints: [mod],
external: ["@fourze/core"],
outfile: modName,
write: true,
platform: "node",
bundle: true,
format: "cjs",
metafile: true,
target: "es6"
})

await loadJsModule(modName)

await loadJsModule(modName)
} catch (err) {
logger.error(`load file ${modName}`, err)
}
try {
await fs.promises.unlink(modName)
} catch (err) {
Expand Down Expand Up @@ -161,7 +162,10 @@ export function createRouter(params: FourzeRouterOptions | FourzeSetup): FourzeR

switch (event) {
case "add":
await this.load(path)
break
case "change":
this.remove(path)
await this.load(path)
break
case "unlink":
Expand Down

0 comments on commit 4963e36

Please sign in to comment.