Created
January 3, 2024 20:16
-
-
Save Grubba27/0d3d4423586bcfad985c0666d6ccf436 to your computer and use it in GitHub Desktop.
dead simple trpc like api for meteor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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