-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathserver-fns-runtime.ts
More file actions
29 lines (28 loc) · 980 Bytes
/
server-fns-runtime.ts
File metadata and controls
29 lines (28 loc) · 980 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
28
29
import { getRequestEvent } from "solid-js/web";
import { provideRequestEvent } from "solid-js/web/storage";
export function createServerReference(fn: Function, id: string) {
if (typeof fn !== "function")
throw new Error("Export from a 'use server' module must be a function");
const baseURL = import.meta.env.SERVER_BASE_URL ?? "";
return new Proxy(fn, {
get(target, prop, receiver) {
if (prop === "url") {
return `${baseURL}/_server?id=${encodeURIComponent(id)}`;
}
if (prop === "GET") return receiver;
return (target as any)[prop];
},
apply(target, thisArg, args) {
const ogEvt = getRequestEvent();
if (!ogEvt) throw new Error("Cannot call server function outside of a request");
const evt = { ...ogEvt };
evt.locals.serverFunctionMeta = {
id
};
evt.serverOnly = true;
return provideRequestEvent(evt, () => {
return fn.apply(thisArg, args);
});
}
});
}