-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.ts
More file actions
27 lines (23 loc) · 778 Bytes
/
Copy pathcontext.ts
File metadata and controls
27 lines (23 loc) · 778 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { AsyncLocalStorage } from "async_hooks";
import { type ZodSchema } from "zod";
const asyncLocalStorage = new AsyncLocalStorage();
export function getContext() {
const context = asyncLocalStorage.getStore();
if (context instanceof Object) {
return context;
}
return {};
}
export function getZodContext<T extends object>(schema: ZodSchema<T>) {
const context = asyncLocalStorage.getStore();
const res = schema.safeParse(context);
if (res.success) {
return res.data;
}
throw new Error(`Context does not match schema: ${res.error.message}`, {
cause: res.error,
});
}
export function runWithContext<T>(context: object, fn: () => T) {
return asyncLocalStorage.run({ ...getContext(), ...context }, fn);
}