-
Notifications
You must be signed in to change notification settings - Fork 418
Expand file tree
/
Copy pathserver.ts
More file actions
46 lines (42 loc) · 1.4 KB
/
server.ts
File metadata and controls
46 lines (42 loc) · 1.4 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { getRequestEvent } from "solid-js/web";
import { provideRequestEvent } from "solid-js/web/storage";
import { registerServerFunction } from "./registration.ts";
interface Registration<T extends any[], R> {
id: string;
fn: (...args: T) => Promise<R>;
}
export function createServerReference<T extends any[], R>(
id: string,
fn: (...args: T) => Promise<R>,
) {
const registration: Registration<T, R> = { id, fn };
registerServerFunction(id, fn);
return registration;
}
export function cloneServerReference<T extends any[], R>({ id, fn }: Registration<T, R>) {
if (typeof fn !== "function")
throw new Error("Export from a 'use server' module must be a function");
let baseURL = import.meta.env.BASE_URL ?? "/";
if (!baseURL.endsWith("/")) baseURL += "/";
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 as T);
});
},
});
}