Skip to content

Commit

Permalink
chore(context): improve AsyncProxy with better names and more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondfeng committed May 3, 2019
1 parent da83214 commit 81469e7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
Expand Up @@ -60,6 +60,35 @@ describe('Interception proxy', () => {
'log: after-greet',
'convertName: after-greet',
]);

// Make sure `greet` always return Promise now
expect(proxy.greet('Jane')).to.be.instanceOf(Promise);
});

it('creates async methods for the proxy', () => {
class MyController {
name: string;

greet(name: string): string {
return `Hello, ${name}`;
}

async hello(name: string) {
return `Hello, ${name}`;
}
}

interface ExpectedAsyncProxyForMyController {
name: string;
greet(name: string): Promise<string>; // the return type becomes `Promise<string>`
hello(name: string): Promise<string>; // the same as MyController
}

const proxy = createProxyWithInterceptors(new MyController(), ctx);

// Enforce compile time check to ensure the AsyncProxy typing works for TS
// tslint:disable-next-line:no-unused
const check: ExpectedAsyncProxyForMyController = proxy;
});

it('invokes interceptors on a static method', async () => {
Expand Down
10 changes: 5 additions & 5 deletions packages/context/src/interception-proxy.ts
Expand Up @@ -7,18 +7,18 @@ import {Context} from './context';
import {InvocationArgs, invokeMethodWithInterceptors} from './interceptor';

/**
* The Promise type for `T`. If `T` extends `Promise`, the type is `T`,
* Create the Promise type for `T`. If `T` extends `Promise`, the type is `T`,
* otherwise the type is `Promise<T>`.
*/
export type PromiseType<T> = T extends Promise<unknown> ? T : Promise<T>;
export type AsPromise<T> = T extends Promise<unknown> ? T : Promise<T>;

/**
* The async variant of a function to always return Promise<R>. If T is not a
* function, the type is `T`.
*/
// tslint:disable-next-line:no-unused (possible tslint bug to treat `R` as unused)
export type AsyncType<T> = T extends (...args: InvocationArgs) => infer R
? (...args: InvocationArgs) => PromiseType<R>
export type AsAsyncFunction<T> = T extends (...args: InvocationArgs) => infer R
? (...args: InvocationArgs) => AsPromise<R>
: T;

/**
Expand Down Expand Up @@ -49,7 +49,7 @@ export type AsyncType<T> = T extends (...args: InvocationArgs) => infer R
* }
* ```
*/
export type AsyncProxy<T> = {[P in keyof T]: AsyncType<T[P]>};
export type AsyncProxy<T> = {[P in keyof T]: AsAsyncFunction<T[P]>};

/**
* A proxy handler that applies interceptors
Expand Down

0 comments on commit 81469e7

Please sign in to comment.