using protobuf-ts and @grpc-js client with promises #345
josefschabasser
started this conversation in
General
Replies: 3 comments 6 replies
-
This doesn't seem to be an issue with protobuf-ts, so I'm converting this into a discussion. |
Beta Was this translation helpful? Give feedback.
1 reply
-
I'm not new to TypeScript, and wouldn't want to type this. 😅 Did you look at @protobuf-ts/grpc-transport? This gives you a promise-based client. Under the hood, it uses @grpc/grpc-js. |
Beta Was this translation helpful? Give feedback.
1 reply
-
Alright, I got it working: import type { Client, ServiceError, CallOptions, ClientUnaryCall, Metadata } from '@grpc/grpc-js'
type OriginalCall<T, U> = (
request: T,
metadata: Metadata,
options: Partial<CallOptions>,
callback: (err: ServiceError | null, res?: U) => void,
) => ClientUnaryCall
type PromisifiedCall<T, U> = (
request: T,
metadata?: Metadata,
options?: Partial<CallOptions>,
) => Promise<U>
export type PromisifiedClient<C> = { $: C } & {
[prop in Exclude<keyof C, keyof Client>]: C[prop] extends OriginalCall<infer T, infer U>
? PromisifiedCall<T, U>
: never
}
export function promisifyClient<C extends Client>(client: C) {
return new Proxy(client, {
get: (target, descriptor) => {
const key = descriptor as keyof PromisifiedClient<C>
if (key === '$') return target
const func = target[key]
if (typeof func === 'function')
return (...args: unknown[]) =>
new Promise((resolve, reject) =>
func.call(
target,
...[...args, (err: unknown, res: unknown) => (err ? reject(err) : resolve(res))],
),
)
},
}) as unknown as PromisifiedClient<C>
} Usage: import { credentials } from '@grpc/grpc-js'
import { PGetImportantStuffArguments } from './_generated/test'
import { TestClient } from './_generated/test.grpc-client'
import { promisifyClient } from './grpc_promisify'
const client = promisifyClient(new TestClient('localhost:51623', credentials.createInsecure()))
const args = PGetImportantStuffArguments.create({})
client
.getImportantStuff(args)
.then(console.log)
.catch(console.error) |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I tried to promisify @grpc-js clients using this gist: https://gist.github.com/smnbbrv/f147fceb4c29be5ce877b6275018e294 and keep running into the same issue as https://gist.github.com/smnbbrv/f147fceb4c29be5ce877b6275018e294?permalink_comment_id=4178884#gistcomment-4178884.
What can I do about it?
Beta Was this translation helpful? Give feedback.
All reactions