@@ -2,32 +2,48 @@ import callWithHooks from './callWithHooks';
22import { LoadableMixinInstance } from './LoadableMixin' ;
33
44/**
5- * Decorate a function to causes loading states changes during its execution. It
6- * set state as loading when function is init and unset on throws an error or
5+ * An union of any function and functions that have access to `this`
6+ * (Vue instance).
7+ */
8+ export type Method =
9+ | ( ( ...args : any [ ] ) => any )
10+ | ( ( this : LoadableMixinInstance , ...args : any [ ] ) => any ) ;
11+
12+ /**
13+ * A Higher-order type to trasnform a method into loadable method that have
14+ * access to `this` (Vue instance) and returns a Promise.
15+ */
16+ export type LoadableMethod < T extends Method > = (
17+ this : LoadableMixinInstance ,
18+ ...args : Parameters < T >
19+ ) =>
20+ ReturnType < T > extends Promise < any >
21+ ? ReturnType < T >
22+ : Promise < ReturnType < T > > ;
23+
24+ /**
25+ * Decorate a method to causes loading states changes during its execution. It
26+ * sets state as loading when function is init and unsets on throws an error or
727 * resolve/return.
8- * @example ```js
28+ * @example
929 * Vue.component('SignInForm', {
1030 * methods: {
1131 * signIn: loadable(async function ({ email, password }) {
1232 * // ...
1333 * }, 'signIn')
1434 * }
15- * })```
16- * @param λ - A function , commonly async, which causes loading state changes.
17- * @param [state] - Loading state name.
35+ * });
36+ * @param method - A method , commonly async, which causes loading state changes.
37+ * @param [state] - Loading state name. It's "unknown" if not defined.
1838 */
19- export default function loadable < Return , Params extends any [ ] > (
20- λ : ( this : LoadableMixinInstance , ...params : Params ) => Return | Promise < Return > ,
21- state : string = 'unknown' ,
22- ) : ( this : LoadableMixinInstance , ...params : Params ) => Promise < Return > {
23- return function ( ) {
24- const params = arguments as unknown as Params ;
25-
39+ const loadable = < T extends Method > ( method : T , state : string = 'unknown' ) =>
40+ function ( ) {
2641 this . $setLoading ( state ) ;
2742
2843 return callWithHooks (
29- ( ) => λ . apply ( this , params ) ,
44+ ( ) => method . apply ( this , arguments as any ) ,
3045 ( ) => this . $unsetLoading ( state )
3146 ) ;
32- } ;
33- }
47+ } as LoadableMethod < T > ;
48+
49+ export default loadable ;
0 commit comments