@milkio/stargate 1.0.0-alpha.3 → 1.0.0-alpha.34

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.
Files changed (2) hide show
  1. package/index.ts +86 -16
  2. package/package.json +1 -1
package/index.ts CHANGED
@@ -40,6 +40,64 @@ export async function createStargate<Generated extends { routeSchema: any; rejec
40
40
  const $fetch = stargateOptions.fetch ?? fetch;
41
41
  const $abort = stargateOptions.abort ?? AbortController;
42
42
 
43
+ type StargateEvents = {
44
+ "milkio:executeBefore": { path: string; options: Mixin<ExecuteOptions, { headers: Record<string, string>; baseUrl: string }> };
45
+ "milkio:fetchBefore": { path: string; options: Mixin<ExecuteOptions, { headers: Record<string, string>; baseUrl: string }>; body: string };
46
+ "milkio:executeError": {
47
+ path: string;
48
+ options: Mixin<ExecuteOptions, { headers: Record<string, string>; baseUrl: string }>;
49
+ error: Partial<Generated["rejectCode"]>;
50
+ handleError: <K extends keyof Partial<Generated["rejectCode"]>>(error: any, key: K, handler: (error: Partial<Generated["rejectCode"][K]>) => boolean | Promise<boolean>) => Promise<void>;
51
+ };
52
+ };
53
+
54
+ const handleError: any = async (error: any, key: string, handler: (error: any) => boolean | Promise<boolean>) => {
55
+ if (key in error) {
56
+ const handled = await handler(error[key]);
57
+ if (handled) delete error[key];
58
+ }
59
+ };
60
+
61
+ const __initEventManager = () => {
62
+ const handlers = new Map<(event: any) => void, string>();
63
+ const indexed = new Map<string, Set<(event: any) => void>>();
64
+
65
+ const eventManager = {
66
+ on: <Key extends keyof StargateEvents, Handler extends (event: StargateEvents[Key]) => void>(key: Key, handler: Handler) => {
67
+ handlers.set(handler, key as string);
68
+ if (indexed.has(key as string) === false) {
69
+ indexed.set(key as string, new Set());
70
+ }
71
+ const set = indexed.get(key as string)!;
72
+ set.add(handler);
73
+ handlers.set(handler, key as string);
74
+
75
+ return () => {
76
+ handlers.delete(handler);
77
+ set.delete(handler);
78
+ };
79
+ },
80
+ off: <Key extends keyof StargateEvents, Handler extends (event: StargateEvents[Key]) => void>(key: Key, handler: Handler) => {
81
+ const set = indexed.get(key as string);
82
+ if (!set) return;
83
+ handlers.delete(handler);
84
+ set.delete(handler);
85
+ },
86
+ emit: async <Key extends keyof StargateEvents, Value extends StargateEvents[Key]>(key: Key, value: Value): Promise<void> => {
87
+ const h = indexed.get(key as string);
88
+ if (h) {
89
+ for (const handler of h) {
90
+ await handler(value);
91
+ }
92
+ }
93
+ },
94
+ };
95
+
96
+ return eventManager;
97
+ };
98
+
99
+ const eventManager = __initEventManager();
100
+
43
101
  const bootstrap = async () => {
44
102
  let baseUrl = stargateOptions.baseUrl;
45
103
  if (typeof baseUrl === "function") baseUrl = await baseUrl();
@@ -51,24 +109,25 @@ export async function createStargate<Generated extends { routeSchema: any; rejec
51
109
  const baseUrl: Promise<string> = bootstrap();
52
110
 
53
111
  const stargate = {
112
+ ...eventManager,
54
113
  $types: {
55
114
  generated: void 0 as unknown as Generated,
56
115
  },
57
116
  options: stargateOptions,
58
- async execute<Path extends keyof Generated["routeSchema"]["$types"]>(
117
+ async execute<Path extends keyof Generated["routeSchema"]>(
59
118
  path: Path,
60
119
  options?: Mixin<
61
120
  ExecuteOptions,
62
121
  {
63
- params?: Generated["routeSchema"]["$types"][Path]["params"];
122
+ params?: Generated["routeSchema"][Path]["types"]["params"];
64
123
  }
65
124
  >,
66
125
  ): Promise<
67
- Generated["routeSchema"]["$types"][Path]["🐣"] extends boolean
126
+ Generated["routeSchema"][Path]["types"]["🐣"] extends boolean
68
127
  ? // action
69
- [Partial<Generated["rejectCode"]>, null, ExecuteResultsOption] | [null, Generated["routeSchema"]["$types"][Path]["result"], ExecuteResultsOption]
128
+ [Partial<Generated["rejectCode"]>, null, ExecuteResultsOption] | [null, Generated["routeSchema"][Path]["types"]["result"], ExecuteResultsOption]
70
129
  : // stream
71
- [Partial<Generated["rejectCode"]>, null, ExecuteResultsOption] | [null, AsyncGenerator<[Partial<Generated["rejectCode"]>, null] | [null, GeneratorGeneric<Generated["routeSchema"]["$types"][Path]["result"]>], ExecuteResultsOption>]
130
+ [Partial<Generated["rejectCode"]>, null, ExecuteResultsOption] | [null, AsyncGenerator<[Partial<Generated["rejectCode"]>, null] | [null, GeneratorGeneric<Generated["routeSchema"][Path]["types"]["result"]>], ExecuteResultsOption>]
72
131
  > {
73
132
  if (!options) options = {};
74
133
  if (options.headers === undefined) options.headers = {};
@@ -85,11 +144,14 @@ export async function createStargate<Generated extends { routeSchema: any; rejec
85
144
  // action
86
145
  if (options.headers["Accept"] === undefined) options.headers["Accept"] = "application/json";
87
146
  if (options.headers["Content-Type"] === undefined) options.headers["Content-Type"] = "application/json";
88
-
89
- const body = TSON.stringify(options.params) ?? "";
90
-
91
147
  let result: { value: Record<any, any> };
148
+
92
149
  try {
150
+ await eventManager.emit("milkio:executeBefore", { path: path as string, options: options as any });
151
+
152
+ const body = TSON.stringify(options.params) ?? "";
153
+ await eventManager.emit("milkio:fetchBefore", { path: path as string, options: options as any, body: body });
154
+
93
155
  const response = await new Promise<string>(async (resolve, reject) => {
94
156
  const timeout = options?.timeout ?? options?.timeout ?? 6000;
95
157
  const timer = setTimeout(() => {
@@ -106,12 +168,18 @@ export async function createStargate<Generated extends { routeSchema: any; rejec
106
168
  });
107
169
  result = { value: TSON.parse(response) };
108
170
  } catch (error: any) {
109
- if (error?.[0]?.REQUEST_TIMEOUT) return error;
110
- return [{ REQUEST_FAIL: error }, null, { executeId: "unknown" }];
171
+ if (error?.[0]?.REQUEST_TIMEOUT) {
172
+ await eventManager.emit("milkio:executeError", { handleError, path: path as string, options: options as any, error: error });
173
+ return error;
174
+ }
175
+ let errorPined = { REQUEST_FAIL: error };
176
+ await eventManager.emit("milkio:executeError", { handleError, path: path as string, options: options as any, error: errorPined });
177
+ return [errorPined, null, { executeId: "unknown" }];
111
178
  }
112
179
  if (result.value.success !== true) {
113
180
  const error: any = {};
114
181
  error[result.value.code] = result.value.reject ?? null;
182
+ await eventManager.emit("milkio:executeError", { handleError, path: path as string, options: options as any, error: error });
115
183
  return [error, null, { executeId: "unknown" }];
116
184
  }
117
185
 
@@ -121,7 +189,6 @@ export async function createStargate<Generated extends { routeSchema: any; rejec
121
189
  if (options.headers["Accept"] === undefined) options.headers["Accept"] = "text/event-stream";
122
190
  if (options.headers["Content-Type"] === undefined) options.headers["Content-Type"] = "application/json";
123
191
 
124
- const body = TSON.stringify(options.params) ?? "";
125
192
  const stacks: Map<
126
193
  number,
127
194
  {
@@ -174,6 +241,11 @@ export async function createStargate<Generated extends { routeSchema: any; rejec
174
241
  iterator.return();
175
242
  });
176
243
  try {
244
+ await eventManager.emit("milkio:executeBefore", { path: path as string, options: options as any });
245
+
246
+ const body = TSON.stringify(options!.params) ?? "";
247
+ await eventManager.emit("milkio:fetchBefore", { path: path as string, options: options as any, body: body });
248
+
177
249
  const response = await $fetch(url, {
178
250
  method: "POST",
179
251
  headers: options!.headers,
@@ -188,15 +260,13 @@ export async function createStargate<Generated extends { routeSchema: any; rejec
188
260
 
189
261
  await getBytes(response.body!, getLines(getMessages(onmessage)));
190
262
 
191
- // for (const m of _afterExecuteMiddlewares) {
192
- // await m.middleware({ path: path as string, storage: options.storage as ClientStorage, result: { value: undefined } });
193
- // }
194
-
195
263
  await iterator.return();
196
264
  } catch (err) {
197
265
  if (!curRequestController.signal.aborted) curRequestController.abort();
266
+ const error = { REQUEST_FAIL: err };
267
+ await eventManager.emit("milkio:executeError", { handleError, path: path as string, options: options as any, error: error });
198
268
  await iterator.throw(err);
199
- streamResultFetched.reject([{ REQUEST_FAIL: err }, null, { executeId: "unknown" }]);
269
+ streamResultFetched.reject([error, null, { executeId: "unknown" }]);
200
270
  }
201
271
  }
202
272
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@milkio/stargate",
3
3
  "module": "index.ts",
4
- "version": "1.0.0-alpha.3",
4
+ "version": "1.0.0-alpha.34",
5
5
  "type": "module",
6
6
  "dependencies": {
7
7
  "@southern-aurora/tson": "^2.0.2"