milkio 0.0.10 → 0.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.co.toml +0 -0
- package/api-test/index.ts +64 -0
- package/c.ts +39 -57
- package/defines/define-api-test.ts +3 -3
- package/defines/define-api.ts +3 -3
- package/defines/define-http-handler.ts +60 -69
- package/defines/define-middleware.ts +2 -2
- package/defines/define-use.ts +6 -6
- package/index.ts +23 -22
- package/kernel/context.ts +1 -2
- package/kernel/fail.ts +6 -6
- package/kernel/logger.ts +38 -38
- package/kernel/meta.ts +5 -5
- package/kernel/middleware.ts +16 -16
- package/kernel/milkio.ts +70 -95
- package/kernel/runtime.ts +2 -7
- package/kernel/validate.ts +5 -5
- package/package.json +4 -1
- package/scripts/gen-insignificant.ts +261 -0
- package/scripts/gen-significant.ts +176 -0
- package/{scripts → scripts-del}/build-cookbook.ts +119 -119
- package/scripts-del/build-dto.ts +65 -0
- package/{scripts → scripts-del}/generate/generate-app-partial.ts +31 -31
- package/{scripts → scripts-del}/generate/generate-app.ts +41 -41
- package/scripts-del/generate/generate-database.ts +22 -0
- package/scripts-del/generate-partial.ts +15 -0
- package/scripts-del/generate.ts +23 -0
- package/templates/api.ts +4 -4
- package/types.ts +29 -19
- package/utils/create-template.ts +5 -5
- package/utils/create-ulid.ts +3 -3
- package/utils/env-to-boolean.ts +5 -5
- package/utils/env-to-number.ts +2 -2
- package/utils/env-to-string.ts +2 -2
- package/utils/exec.ts +12 -12
- package/utils/handle-catch-error.ts +10 -10
- package/utils/remove-dir.ts +11 -11
- package/utils/tson.ts +2 -2
- package/defines/define-api-test-handler.ts +0 -71
- package/kernel/config.ts +0 -14
- package/scripts/build-dto.ts +0 -65
- package/scripts/generate/generate-database.ts +0 -22
- package/scripts/generate-database.ts +0 -23
- package/scripts/generate-partial.ts +0 -15
- package/scripts/generate.ts +0 -23
package/.co.toml
CHANGED
|
File without changes
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/* eslint-disable no-constant-condition, @typescript-eslint/no-unsafe-argument, no-console, @typescript-eslint/no-explicit-any */
|
|
2
|
+
|
|
3
|
+
import schema from "../../../generated/api-schema"
|
|
4
|
+
import { type MilkioApp } from ".."
|
|
5
|
+
|
|
6
|
+
export const executeApiTests = async <Path extends Array<keyof (typeof schema)["apiTestsSchema"]>>(app: MilkioApp, path: Path | string | true | 1 | undefined) => {
|
|
7
|
+
console.log(`🥛 Milkio Api Testing..\n`)
|
|
8
|
+
|
|
9
|
+
let pathArr = [] as Array<string>
|
|
10
|
+
if (!path || path === "1" || path === 1 || path === true) {
|
|
11
|
+
pathArr = Object.keys(schema.apiTestsSchema) as unknown as Path
|
|
12
|
+
} else if (typeof path === "string") {
|
|
13
|
+
pathArr = [path] as Path
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const tests = []
|
|
17
|
+
const startedAt = new Date().getTime()
|
|
18
|
+
|
|
19
|
+
for (let path of pathArr) {
|
|
20
|
+
if (path.startsWith("/")) path = path.slice(1) as Path[number]
|
|
21
|
+
|
|
22
|
+
tests.push(
|
|
23
|
+
// @ts-ignore
|
|
24
|
+
(async () => {
|
|
25
|
+
// @ts-ignore
|
|
26
|
+
const module = await schema.apiTestsSchema[path]().module
|
|
27
|
+
const cases = module.test.getCases()
|
|
28
|
+
let i = 0
|
|
29
|
+
for (const cs of cases) {
|
|
30
|
+
++i
|
|
31
|
+
const csStartedAt = new Date().getTime()
|
|
32
|
+
const clear = setTimeout(() => {
|
|
33
|
+
console.error(`------`)
|
|
34
|
+
console.error(`❌ TIMEOUT -- More than ${cs.timeout ?? 8192}ms`)
|
|
35
|
+
console.error(` ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i}`)
|
|
36
|
+
console.error(`------`)
|
|
37
|
+
throw new Error("")
|
|
38
|
+
}, cs.timeout ?? 8192)
|
|
39
|
+
await cs.handler({
|
|
40
|
+
// @ts-ignore
|
|
41
|
+
execute: async (params: any, headers?: any, options?: any) => app.execute(path, params, headers ?? {}, options),
|
|
42
|
+
executeOther: async (path: any, params: any, headers?: any, options?: any) => app.execute(path, params, headers ?? {}, options),
|
|
43
|
+
reject: (message?: string) => {
|
|
44
|
+
console.error(`------`)
|
|
45
|
+
console.error(`❌ REJECT -- ${message ?? "Test not satisfied"}`)
|
|
46
|
+
console.error(` ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i} | Time: ${new Date().getTime() - csStartedAt}ms`)
|
|
47
|
+
console.error(`------`)
|
|
48
|
+
throw new Error("")
|
|
49
|
+
}
|
|
50
|
+
} as any)
|
|
51
|
+
clearTimeout(clear)
|
|
52
|
+
console.log(`✅ DIRECT -- ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i} | Time: ${new Date().getTime() - csStartedAt}ms`)
|
|
53
|
+
}
|
|
54
|
+
})()
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
await Promise.all(tests)
|
|
59
|
+
|
|
60
|
+
const endedAt = new Date().getTime()
|
|
61
|
+
|
|
62
|
+
console.log(`\n✅ All tests passed.`)
|
|
63
|
+
console.log(`🥛 Milkio Api Testing took ${((endedAt - startedAt) / 1000).toFixed(2)}s\n`)
|
|
64
|
+
}
|
package/c.ts
CHANGED
|
@@ -1,73 +1,55 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
|
|
3
|
-
/* eslint-disable @typescript-eslint/no-misused-promises, no-console, @typescript-eslint/no-explicit-any */
|
|
3
|
+
/* eslint-disable no-constant-condition, @typescript-eslint/no-misused-promises, no-console, @typescript-eslint/no-explicit-any */
|
|
4
4
|
|
|
5
|
-
import { argv,
|
|
6
|
-
import
|
|
7
|
-
import {
|
|
8
|
-
import { $ } from "bun";
|
|
9
|
-
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { argv, exit } from "node:process"
|
|
6
|
+
import process from "process"
|
|
7
|
+
import { $ } from "bun"
|
|
10
8
|
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
const params = argv.slice(3) as Parameters<(typeof commands)[keyof typeof commands]>;
|
|
9
|
+
const method = argv[2] as keyof typeof commands
|
|
10
|
+
const params = argv.slice(3) as Parameters<(typeof commands)[keyof typeof commands]>
|
|
14
11
|
|
|
15
12
|
const commands = {
|
|
16
13
|
async gen() {
|
|
17
|
-
|
|
14
|
+
console.log("🥛 Milkio Generating..\n")
|
|
15
|
+
await (await import('./scripts/gen-significant')).default()
|
|
16
|
+
await (await import('./scripts/gen-insignificant')).default()
|
|
17
|
+
console.log("\n✅ Milkio Generated!")
|
|
18
18
|
},
|
|
19
|
-
async "gen:
|
|
20
|
-
|
|
19
|
+
async "gen:significant"() {
|
|
20
|
+
console.log("🥛 Milkio Significant Generating..\n")
|
|
21
|
+
await (await import('./scripts/gen-significant')).default()
|
|
22
|
+
console.log("\n✅ Milkio Significant Generated!")
|
|
21
23
|
},
|
|
22
|
-
async "
|
|
23
|
-
|
|
24
|
+
async "gen:insignificant"() {
|
|
25
|
+
console.log("🥛 Milkio Insignificant Generating..\n")
|
|
26
|
+
await (await import('./scripts/gen-insignificant')).default()
|
|
27
|
+
console.log("\n✅ Milkio Insignificant Generated!")
|
|
24
28
|
},
|
|
25
|
-
async "build:
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
// async "build:cookbook"() {
|
|
30
|
+
// await exec(rootPath, ["bun", "./node_modules/milkio/scripts/build-cookbook.ts"])
|
|
31
|
+
// },
|
|
32
|
+
// async "build:dto"() {
|
|
33
|
+
// await exec(join(rootPath, "packages", "dto"), ["bun", "i"])
|
|
34
|
+
// await exec(rootPath, ["bun", "./node_modules/milkio/scripts/generate.ts"])
|
|
35
|
+
// await exec(rootPath, ["bun", "./node_modules/milkio/scripts/build-dto.ts"])
|
|
36
|
+
// },
|
|
37
|
+
async EAR(commandBase64ed: string) {
|
|
38
|
+
try { await $`clear` } catch (e) {}
|
|
39
|
+
const command = Buffer.from(commandBase64ed, 'base64').toString('utf-8')
|
|
40
|
+
await $`${{ raw: command }}`
|
|
41
|
+
process.on('SIGINT', () => {}) // prevent users from exiting by pressing ctrl + c
|
|
42
|
+
while (true) await new Promise((resolve) => process.stdin.on('keypress', resolve))
|
|
29
43
|
},
|
|
30
|
-
|
|
31
|
-
const run = async () => {
|
|
32
|
-
const packageJson = await JSON.parse((await readFile(join(rootPath, "package.json"))).toString());
|
|
33
|
-
await $`${{ raw: packageJson.scripts.start }}`.env({
|
|
34
|
-
...env,
|
|
35
|
-
MILKIO_RUN_MODE: "API_TEST",
|
|
36
|
-
MILKIO_TEST: files ?? "1"
|
|
37
|
-
});
|
|
38
|
-
};
|
|
39
|
-
if (!env.MILKIO_TEST_RESERVED && reserved !== "1") {
|
|
40
|
-
// Normal test
|
|
41
|
-
await run();
|
|
42
|
-
} else {
|
|
43
|
-
// Keep after testing, the terminal never exits and is usually used for various IDE extensions.
|
|
44
|
-
try {
|
|
45
|
-
await run();
|
|
46
|
-
} catch (error) {}
|
|
47
|
-
while (true) {
|
|
48
|
-
const result = await new Promise((resolve) => {
|
|
49
|
-
const wasRaw = process.stdin.isRaw;
|
|
50
|
-
process.stdin.setRawMode(true);
|
|
51
|
-
process.stdin.resume();
|
|
52
|
-
process.stdin.once("data", (data) => {
|
|
53
|
-
process.stdin.pause();
|
|
54
|
-
process.stdin.setRawMode(wasRaw);
|
|
55
|
-
resolve(data.toString());
|
|
56
|
-
});
|
|
57
|
-
});
|
|
58
|
-
// No exit function is set
|
|
59
|
-
// if (result === "q") exit(0);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
};
|
|
44
|
+
}
|
|
64
45
|
|
|
65
46
|
if (method === undefined || !(method in commands)) {
|
|
66
|
-
console.log("Command does not exist, Supported commands are:")
|
|
67
|
-
console.log(" " + Object.keys(commands).join(", "))
|
|
68
|
-
exit(1)
|
|
47
|
+
console.log("Command does not exist, Supported commands are:")
|
|
48
|
+
console.log(" " + Object.keys(commands).join(", "))
|
|
49
|
+
exit(1)
|
|
69
50
|
}
|
|
70
51
|
|
|
71
|
-
|
|
52
|
+
// @ts-ignore
|
|
53
|
+
await commands[method](...params)
|
|
72
54
|
|
|
73
|
-
exit(0)
|
|
55
|
+
exit(0)
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { type Api, type ExecuteResult, type ExecuteOptions } from ".."
|
|
2
|
-
import type schema from "../../../
|
|
1
|
+
import { type Api, type ExecuteResult, type ExecuteOptions } from ".."
|
|
2
|
+
import type schema from "../../../generated/api-schema"
|
|
3
3
|
|
|
4
4
|
export function defineApiTest<ApiT extends Api>(_api: ApiT, cases: Array<ApiTestCases<ApiT>>) {
|
|
5
5
|
return {
|
|
6
6
|
getCases: () => cases,
|
|
7
7
|
isApiTest: true
|
|
8
|
-
}
|
|
8
|
+
}
|
|
9
9
|
}
|
|
10
10
|
|
|
11
11
|
export type ApiTestCases<ApiT extends Api> = {
|
package/defines/define-api.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type { Meta } from "../../../src/meta"
|
|
2
|
-
import type { Context } from "../../../src/context"
|
|
1
|
+
import type { Meta } from "../../../src/meta"
|
|
2
|
+
import type { Context } from "../../../src/context"
|
|
3
3
|
|
|
4
4
|
export function defineApi<ApiT extends Api>(api: ApiT): ApiT & { isApi: true } {
|
|
5
5
|
return {
|
|
6
6
|
...api,
|
|
7
7
|
isApi: true
|
|
8
|
-
}
|
|
8
|
+
}
|
|
9
9
|
}
|
|
10
10
|
|
|
11
11
|
export type Api = {
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/* eslint-disable no-console */
|
|
2
|
-
import {
|
|
3
|
-
import type { ExecuteId, MilkioApp, Mixin } from ".."
|
|
4
|
-
import { hanldeCatchError } from "../utils/handle-catch-error"
|
|
5
|
-
import { routerHandler } from "../../../src/router"
|
|
6
|
-
import schema from "../../../
|
|
7
|
-
import { failCode } from "../../../src/fail-code"
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
2
|
+
import { loggerPushTags, loggerSubmit, useLogger, runtime, MiddlewareEvent } from ".."
|
|
3
|
+
import type { ExecuteId, MilkioApp, Mixin } from ".."
|
|
4
|
+
import { hanldeCatchError } from "../utils/handle-catch-error"
|
|
5
|
+
import { routerHandler } from "../../../src/router"
|
|
6
|
+
import schema from "../../../generated/api-schema"
|
|
7
|
+
import { failCode } from "../../../src/fail-code"
|
|
8
|
+
import { TSON } from "@southern-aurora/tson"
|
|
9
|
+
import { createUlid } from "../utils/create-ulid"
|
|
10
|
+
import { configMilkio } from "../../../src/apps/config/milkio"
|
|
11
11
|
|
|
12
12
|
export type ExecuteHttpServerOptions = {
|
|
13
13
|
/**
|
|
@@ -21,34 +21,23 @@ export type ExecuteHttpServerOptions = {
|
|
|
21
21
|
};
|
|
22
22
|
|
|
23
23
|
export function defineHttpHandler(app: MilkioApp, options: ExecuteHttpServerOptions = {}) {
|
|
24
|
-
// If an unexpected error occurs, exit the process.
|
|
25
|
-
// For modern production environments such as Serverless, Kubernetes, or Docker Compose:
|
|
26
|
-
// The process will automatically restart after exiting.
|
|
27
|
-
// This helps prevent unexpected errors from contaminating the entire application and causing subsequent requests to fail intermittently.
|
|
28
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
29
|
-
process.on("uncaughtException", async (error) => {
|
|
30
|
-
const logger = useLogger("global");
|
|
31
|
-
logger.error("ErrorCaughtInUncaughtExceptionEvent:", error);
|
|
32
|
-
await loggerSubmitAll();
|
|
33
|
-
exit(1);
|
|
34
|
-
});
|
|
35
|
-
|
|
36
24
|
const fetch = async (request: MilkioHTTPRequest) => {
|
|
37
|
-
const fullurl = new URL(request.request.url, `http://${request.request.headers.get("host") ?? "localhost"}`)
|
|
38
|
-
const executeId = (options?.executeIdGenerator ? await options.executeIdGenerator(request.request) : createUlid()) as ExecuteId
|
|
39
|
-
runtime.execute.executeIds.add(executeId)
|
|
40
|
-
const logger = useLogger(executeId)
|
|
41
|
-
const ip = (request.request.headers.get("x-forwarded-for") as string | undefined)?.split(",")[0] ?? "0.0.0.0"
|
|
42
|
-
const headers = request.request.headers
|
|
25
|
+
const fullurl = new URL(request.request.url, `http://${request.request.headers.get("host") ?? "localhost"}`)
|
|
26
|
+
const executeId = (options?.executeIdGenerator ? await options.executeIdGenerator(request.request) : createUlid()) as ExecuteId
|
|
27
|
+
runtime.execute.executeIds.add(executeId)
|
|
28
|
+
const logger = useLogger(executeId)
|
|
29
|
+
const ip = (request.request.headers.get("x-forwarded-for") as string | undefined)?.split(",")[0] ?? "0.0.0.0"
|
|
30
|
+
const headers = request.request.headers
|
|
43
31
|
|
|
44
32
|
loggerPushTags(executeId, {
|
|
45
33
|
from: "http-server",
|
|
46
34
|
fullUrl: fullurl.pathname,
|
|
47
35
|
ip,
|
|
48
36
|
method: request.request.method,
|
|
37
|
+
// @ts-ignore
|
|
49
38
|
requestHeaders: request.request.headers.toJSON(),
|
|
50
39
|
timein: new Date().getTime()
|
|
51
|
-
})
|
|
40
|
+
})
|
|
52
41
|
|
|
53
42
|
const response: MilkioHTTPResponse = {
|
|
54
43
|
body: "",
|
|
@@ -59,13 +48,13 @@ export function defineHttpHandler(app: MilkioApp, options: ExecuteHttpServerOpti
|
|
|
59
48
|
"Access-Control-Allow-Headers": configMilkio.corsAllowHeaders ?? "*",
|
|
60
49
|
"Access-Control-Allow-Origin": configMilkio.corsAllowOrigin ?? "*"
|
|
61
50
|
}
|
|
62
|
-
}
|
|
51
|
+
}
|
|
63
52
|
|
|
64
53
|
try {
|
|
65
54
|
// Process OPTIONS pre inspection requests
|
|
66
55
|
if (request.request.method === "OPTIONS") {
|
|
67
|
-
await loggerSubmit(executeId)
|
|
68
|
-
runtime.execute.executeIds.delete(executeId)
|
|
56
|
+
await loggerSubmit(executeId)
|
|
57
|
+
runtime.execute.executeIds.delete(executeId)
|
|
69
58
|
|
|
70
59
|
return new Response("", {
|
|
71
60
|
headers: {
|
|
@@ -73,44 +62,45 @@ export function defineHttpHandler(app: MilkioApp, options: ExecuteHttpServerOpti
|
|
|
73
62
|
"Access-Control-Allow-Headers": configMilkio.corsAllowHeaders ?? "*",
|
|
74
63
|
"Access-Control-Allow-Origin": configMilkio.corsAllowOrigin ?? "*"
|
|
75
64
|
}
|
|
76
|
-
})
|
|
65
|
+
})
|
|
77
66
|
}
|
|
78
67
|
|
|
79
|
-
let path = fullurl.pathname.substring(1).split("/")
|
|
68
|
+
let path = fullurl.pathname.substring(1).split("/")
|
|
80
69
|
|
|
81
70
|
// Compatible with API gateway's ability to differentiate versions by path
|
|
82
71
|
// see: /src/config/ConfigProgram.ts in "ignorePathLevel"
|
|
83
|
-
if (configMilkio.ignorePathLevel !== 0) path = path.slice(configMilkio.ignorePathLevel)
|
|
72
|
+
if (configMilkio.ignorePathLevel !== 0) path = path.slice(configMilkio.ignorePathLevel)
|
|
84
73
|
|
|
85
|
-
let pathstr = path.join("/") as keyof (typeof schema)["apiMethodsSchema"]
|
|
74
|
+
let pathstr = path.join("/") as keyof (typeof schema)["apiMethodsSchema"]
|
|
86
75
|
|
|
87
76
|
// Special processing: do not run middleware when encountering 404 and return quickly
|
|
88
77
|
if (!(pathstr in schema.apiMethodsSchema)) {
|
|
89
|
-
|
|
78
|
+
// @ts-ignore
|
|
79
|
+
const redirectPath = await routerHandler(pathstr, fullurl)
|
|
90
80
|
if (!redirectPath) {
|
|
91
|
-
const rawbody = await request.request.text()
|
|
81
|
+
const rawbody = await request.request.text()
|
|
92
82
|
loggerPushTags(executeId, {
|
|
93
83
|
body: rawbody || "no body"
|
|
94
|
-
})
|
|
95
|
-
response.body = `{"executeId":"${executeId}","success":false,"fail":{"code":"NOT_FOUND","message":${JSON.stringify(failCode.NOT_FOUND())}}}
|
|
84
|
+
})
|
|
85
|
+
response.body = `{"executeId":"${executeId}","success":false,"fail":{"code":"NOT_FOUND","message":${JSON.stringify(failCode.NOT_FOUND())}}}`
|
|
96
86
|
|
|
97
87
|
loggerPushTags(executeId, {
|
|
98
88
|
status: response.status,
|
|
99
89
|
responseHeaders: response.headers,
|
|
100
90
|
timeout: new Date().getTime()
|
|
101
|
-
})
|
|
91
|
+
})
|
|
102
92
|
|
|
103
|
-
await loggerSubmit(executeId)
|
|
104
|
-
runtime.execute.executeIds.delete(executeId)
|
|
93
|
+
await loggerSubmit(executeId)
|
|
94
|
+
runtime.execute.executeIds.delete(executeId)
|
|
105
95
|
|
|
106
|
-
return new Response(response.body, response)
|
|
96
|
+
return new Response(response.body, response)
|
|
107
97
|
}
|
|
108
|
-
pathstr = redirectPath as typeof pathstr
|
|
98
|
+
pathstr = redirectPath as typeof pathstr
|
|
109
99
|
}
|
|
110
100
|
|
|
111
101
|
loggerPushTags(executeId, {
|
|
112
102
|
path: pathstr
|
|
113
|
-
})
|
|
103
|
+
})
|
|
114
104
|
|
|
115
105
|
const detail = {
|
|
116
106
|
path: pathstr,
|
|
@@ -119,56 +109,57 @@ export function defineHttpHandler(app: MilkioApp, options: ExecuteHttpServerOpti
|
|
|
119
109
|
fullurl,
|
|
120
110
|
request: request.request,
|
|
121
111
|
response
|
|
122
|
-
}
|
|
112
|
+
}
|
|
123
113
|
|
|
124
114
|
// execute api
|
|
125
115
|
// after request middleware
|
|
126
|
-
await MiddlewareEvent.handle("afterHTTPRequest", [headers, detail])
|
|
116
|
+
await MiddlewareEvent.handle("afterHTTPRequest", [headers, detail])
|
|
127
117
|
|
|
128
|
-
const rawbody = await request.request.text()
|
|
118
|
+
const rawbody = await request.request.text()
|
|
129
119
|
loggerPushTags(executeId, {
|
|
130
120
|
body: rawbody || "no body"
|
|
131
|
-
})
|
|
121
|
+
})
|
|
132
122
|
|
|
133
123
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
134
|
-
let params: any
|
|
124
|
+
let params: any
|
|
135
125
|
if (rawbody === "") {
|
|
136
|
-
params = undefined
|
|
126
|
+
params = undefined
|
|
137
127
|
} else {
|
|
138
128
|
try {
|
|
139
|
-
params = JSON.parse(rawbody)
|
|
129
|
+
params = JSON.parse(rawbody)
|
|
140
130
|
} catch (error) {
|
|
141
|
-
const logger = useLogger(executeId)
|
|
142
|
-
logger.log("TIP: body is not json, the content is not empty, but the content is not in a valid JSON format. The original content value can be retrieved via request.request.text()")
|
|
143
|
-
params = undefined
|
|
131
|
+
const logger = useLogger(executeId)
|
|
132
|
+
logger.log("TIP: body is not json, the content is not empty, but the content is not in a valid JSON format. The original content value can be retrieved via request.request.text()")
|
|
133
|
+
params = undefined
|
|
144
134
|
}
|
|
145
135
|
}
|
|
146
136
|
|
|
147
137
|
loggerPushTags(executeId, {
|
|
148
138
|
params
|
|
149
|
-
})
|
|
139
|
+
})
|
|
150
140
|
|
|
151
141
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
142
|
+
// @ts-ignore
|
|
152
143
|
const result = await app._executeCoreToJson(pathstr, params, headers, {
|
|
153
144
|
executeId,
|
|
154
145
|
logger,
|
|
155
146
|
detail
|
|
156
|
-
})
|
|
147
|
+
})
|
|
157
148
|
|
|
158
149
|
// @ts-ignore
|
|
159
150
|
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression, @typescript-eslint/no-explicit-any
|
|
160
|
-
response.body = `${response.body ?? ""}${result}
|
|
151
|
+
response.body = `${response.body ?? ""}${result}`
|
|
161
152
|
|
|
162
153
|
// before response middleware
|
|
163
154
|
const middlewareResponse = {
|
|
164
155
|
value: response.body
|
|
165
|
-
}
|
|
166
|
-
await MiddlewareEvent.handle("beforeHTTPResponse", [middlewareResponse, detail])
|
|
156
|
+
}
|
|
157
|
+
await MiddlewareEvent.handle("beforeHTTPResponse", [middlewareResponse, detail])
|
|
167
158
|
|
|
168
|
-
response.body = middlewareResponse.value
|
|
159
|
+
response.body = middlewareResponse.value
|
|
169
160
|
} catch (error) {
|
|
170
|
-
const result = hanldeCatchError(error, executeId)
|
|
171
|
-
response.body = TSON.stringify(result)
|
|
161
|
+
const result = hanldeCatchError(error, executeId)
|
|
162
|
+
response.body = TSON.stringify(result)
|
|
172
163
|
}
|
|
173
164
|
|
|
174
165
|
loggerPushTags(executeId, {
|
|
@@ -177,15 +168,15 @@ export function defineHttpHandler(app: MilkioApp, options: ExecuteHttpServerOpti
|
|
|
177
168
|
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
178
169
|
body: response.body || "",
|
|
179
170
|
timeout: new Date().getTime()
|
|
180
|
-
})
|
|
171
|
+
})
|
|
181
172
|
|
|
182
|
-
await loggerSubmit(executeId)
|
|
183
|
-
runtime.execute.executeIds.delete(executeId)
|
|
173
|
+
await loggerSubmit(executeId)
|
|
174
|
+
runtime.execute.executeIds.delete(executeId)
|
|
184
175
|
|
|
185
|
-
return new Response(response.body, response)
|
|
186
|
-
}
|
|
176
|
+
return new Response(response.body, response)
|
|
177
|
+
}
|
|
187
178
|
|
|
188
|
-
return fetch
|
|
179
|
+
return fetch
|
|
189
180
|
}
|
|
190
181
|
|
|
191
182
|
export type MilkioHTTPRequest = {
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { type MiddlewareOptions } from ".."
|
|
1
|
+
import { type MiddlewareOptions } from ".."
|
|
2
2
|
|
|
3
3
|
export function defineMiddleware(options: MiddlewareOptions): () => MiddlewareOptions {
|
|
4
4
|
return () => ({
|
|
5
5
|
...options,
|
|
6
6
|
// @ts-ignore
|
|
7
7
|
isMiddleware: true
|
|
8
|
-
})
|
|
8
|
+
})
|
|
9
9
|
}
|
package/defines/define-use.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
export const defineUse = <CreatorFn extends () => Promise<unknown> | unknown>(creatorFn: CreatorFn): (() => Promise<Awaited<ReturnType<CreatorFn>>>) => {
|
|
2
2
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3
|
-
let use: any | undefined
|
|
3
|
+
let use: any | undefined
|
|
4
4
|
|
|
5
5
|
const getUse = async () => {
|
|
6
6
|
if (use === undefined) {
|
|
7
|
-
use = await creatorFn()
|
|
7
|
+
use = await creatorFn()
|
|
8
8
|
}
|
|
9
|
-
return use
|
|
10
|
-
}
|
|
9
|
+
return use
|
|
10
|
+
}
|
|
11
11
|
|
|
12
|
-
return getUse
|
|
13
|
-
}
|
|
12
|
+
return getUse
|
|
13
|
+
}
|
package/index.ts
CHANGED
|
@@ -1,33 +1,34 @@
|
|
|
1
1
|
// types
|
|
2
|
-
export * from "./types"
|
|
2
|
+
export * from "./types"
|
|
3
3
|
|
|
4
4
|
// utils
|
|
5
|
-
export * from "./utils/tson"
|
|
6
|
-
export * from "./utils/create-ulid"
|
|
7
|
-
export * from "./utils/env-to-string"
|
|
8
|
-
export * from "./utils/env-to-number"
|
|
9
|
-
export * from "./utils/env-to-boolean"
|
|
10
|
-
export * from "./utils/create-template"
|
|
5
|
+
export * from "./utils/tson"
|
|
6
|
+
export * from "./utils/create-ulid"
|
|
7
|
+
export * from "./utils/env-to-string"
|
|
8
|
+
export * from "./utils/env-to-number"
|
|
9
|
+
export * from "./utils/env-to-boolean"
|
|
10
|
+
export * from "./utils/create-template"
|
|
11
11
|
|
|
12
12
|
// defines
|
|
13
|
-
export * from "./defines/define-use"
|
|
14
|
-
export * from "./defines/define-api"
|
|
15
|
-
export * from "./defines/define-api-test"
|
|
16
|
-
export * from "./defines/define-middleware"
|
|
13
|
+
export * from "./defines/define-use"
|
|
14
|
+
export * from "./defines/define-api"
|
|
15
|
+
export * from "./defines/define-api-test"
|
|
16
|
+
export * from "./defines/define-middleware"
|
|
17
17
|
|
|
18
18
|
// kernel
|
|
19
|
-
export * from "./kernel/runtime"
|
|
20
|
-
export * from "./kernel/logger"
|
|
21
|
-
export * from "./kernel/fail"
|
|
22
|
-
export * from "./kernel/meta"
|
|
23
|
-
export * from "./kernel/
|
|
24
|
-
export * from "./kernel/
|
|
25
|
-
export * from "./kernel/
|
|
26
|
-
export * from "./kernel/middleware";
|
|
19
|
+
export * from "./kernel/runtime"
|
|
20
|
+
export * from "./kernel/logger"
|
|
21
|
+
export * from "./kernel/fail"
|
|
22
|
+
export * from "./kernel/meta"
|
|
23
|
+
export * from "./kernel/context"
|
|
24
|
+
export * from "./kernel/validate"
|
|
25
|
+
export * from "./kernel/middleware"
|
|
27
26
|
|
|
28
27
|
// handler
|
|
29
|
-
export * from "./defines/define-http-handler"
|
|
30
|
-
|
|
28
|
+
export * from "./defines/define-http-handler"
|
|
29
|
+
|
|
30
|
+
// api test
|
|
31
|
+
export * from "./api-test/index"
|
|
31
32
|
|
|
32
33
|
// milkio
|
|
33
|
-
export * from "./kernel/milkio"
|
|
34
|
+
export * from "./kernel/milkio"
|
package/kernel/context.ts
CHANGED
package/kernel/fail.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import { failCode } from "../../../src/fail-code"
|
|
1
|
+
import { failCode } from "../../../src/fail-code"
|
|
2
2
|
|
|
3
3
|
export function reject<Code extends keyof typeof failCode, FailData extends (typeof failCode)[Code]>(code: Code, data: Parameters<FailData>[0]) {
|
|
4
4
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
|
|
5
|
-
const message = failCode[code]?.(data as any) ?? ""
|
|
5
|
+
const message = failCode[code]?.(data as any) ?? ""
|
|
6
6
|
const error = {
|
|
7
7
|
name: "MilkioReject",
|
|
8
8
|
code,
|
|
9
9
|
message,
|
|
10
10
|
data,
|
|
11
11
|
stack: ""
|
|
12
|
-
}
|
|
13
|
-
Error.captureStackTrace(error)
|
|
14
|
-
error.stack = error.stack.replace(/\n.*\n/, "\n")
|
|
12
|
+
}
|
|
13
|
+
Error.captureStackTrace(error)
|
|
14
|
+
error.stack = error.stack.replace(/\n.*\n/, "\n")
|
|
15
15
|
|
|
16
|
-
return error
|
|
16
|
+
return error
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
export type MilkioReject = ReturnType<typeof reject>;
|