Skip to content

Commit 699215f

Browse files
committed
feat: allow resolver to return a promise
1 parent b93c9f5 commit 699215f

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

src/index.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ export type ReturnType<T> = T extends (...args: any) => infer R ? R : never
33
export type PromisifyFn<T> = ReturnType<T> extends Promise<any>
44
? T
55
: (...args: ArgumentsType<T>) => Promise<Awaited<ReturnType<T>>>
6+
export type Thenable<T> = T | PromiseLike<T>
67

7-
export type BirpcResolver = (name: string, resolved: (...args: unknown[]) => unknown) => ((...args: unknown[]) => unknown) | undefined
8+
export type BirpcResolver = (name: string, resolved: (...args: unknown[]) => unknown) => Thenable<((...args: unknown[]) => unknown) | undefined>
89

910
export interface ChannelOptions {
1011
/**
@@ -329,9 +330,9 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
329330
if (msg.t === TYPE_REQUEST) {
330331
const { m: method, a: args } = msg
331332
let result, error: any
332-
const fn = resolver
333+
const fn = await (resolver
333334
? resolver(method, (functions as any)[method])
334-
: (functions as any)[method]
335+
: (functions as any)[method])
335336

336337
if (!fn) {
337338
error = new Error(`[birpc] function "${method}" not found`)

test/resolver.test.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { MessageChannel } from 'node:worker_threads'
22
import { expect, it } from 'vitest'
3+
import type { Thenable } from '../src';
34
import { createBirpc } from '../src'
45
import * as Alice from './alice'
56
import * as Bob from './bob'
@@ -18,7 +19,7 @@ it('resolver', async () => {
1819
},
1920
)
2021

21-
let customResolverFn: ((...args: any[]) => any) | undefined
22+
let customResolverFn: Thenable<((...args: any[]) => any) | undefined> | undefined
2223

2324
const alice = createBirpc<BobFunctions, AliceFunctions>(
2425
{ ...Alice },
@@ -46,7 +47,7 @@ it('resolver', async () => {
4647
.rejects
4748
.toThrow('[birpc] function "foo" not found')
4849

49-
customResolverFn = (a: string) => `Custom resolve function to ${a}`
50+
customResolverFn = Promise.resolve((a: string) => `Custom resolve function to ${a}`)
5051

5152
// @ts-expect-error `foo` is not defined
5253
expect(await bob.foo('Bob'))

0 commit comments

Comments
 (0)