Skip to content

Instantly share code, notes, and snippets.

@Grubba27
Created January 3, 2024 20:16
Show Gist options
  • Save Grubba27/0d3d4423586bcfad985c0666d6ccf436 to your computer and use it in GitHub Desktop.
Save Grubba27/0d3d4423586bcfad985c0666d6ccf436 to your computer and use it in GitHub Desktop.
dead simple trpc like api for meteor
import { Meteor } from "meteor/meteor";
const setProxySettings = (
{
call,
filter,
}: {
call: ({ path, args }: { path: unknown; args: unknown[] }) => any;
filter: (path: string[]) => unknown;
} = {
call: ({ path, args }) => {
return {
path,
args,
};
},
filter: (path: string[]) => path,
}
) => {
const createProxyClient = <T>(path: string[] = []) => {
const proxy = new Proxy(() => {}, {
get(_, key: string) {
if (typeof key !== "string" || key === "then" || key === "toJSON") {
// special case for if the proxy is accidentally treated
// like a PromiseLike (like in `Promise.resolve(proxy)`)
return undefined;
}
return createProxyClient([...path, key]);
},
apply(_1, _2, args) {
const filteredPath = filter(path);
return call({
path: filteredPath,
args,
});
},
}) as unknown as T;
return proxy;
};
return createProxyClient;
};
const createProxyClient = setProxySettings({
call: ({ path, args }) => {
return Meteor.callAsync(path as string, ...args);
},
filter: (path) => path.join("."),
});
// @ts-ignore
export const createClient = <T>() => createProxyClient<T>() as T;
// server.js
const addMethods = <
T extends Record<string, (this: Meteor.MethodThisType, ...args: any[]) => any>
>(
obj: T
) => {
Meteor.methods(obj);
return obj;
};
const obj = addMethods({
foo: async function (this: Meteor.MethodThisType, a: string) {
console.log("call", this, a);
return a;
},
bar: async () => {
console.log("call", "bar");
return "bar";
},
});
export type TestServer = typeof obj;
// client.js
const p = createClient<TestServer>();
p.bar()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment