1 | import Resource from './resource';
|
2 |
|
3 | type Executor =
|
4 | (
|
5 | res: ((value: FollowablePromise) => void),
|
6 | rej: ((reason: any) => any)
|
7 | )
|
8 | => void;
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | export default class FollowablePromise {
|
19 |
|
20 | realPromise: Promise<Resource>;
|
21 |
|
22 | constructor(executor: Executor ) {
|
23 | this.realPromise = new Promise(executor);
|
24 | }
|
25 |
|
26 | |
27 |
|
28 |
|
29 |
|
30 | then(onResolve: (result: any) => Resource | Promise<Resource>, onReject?: (reason: any) => never): Promise<Resource> {
|
31 | return this.realPromise.then(onResolve, onReject);
|
32 | }
|
33 |
|
34 | |
35 |
|
36 |
|
37 |
|
38 | catch<T>(onReject: (reason: any) => Promise<T> | T): Promise<Resource | T> {
|
39 | return this.realPromise.catch(onReject);
|
40 | }
|
41 |
|
42 | /**
|
43 | * The follow function will wait for this promise to resolve, assume the
|
44 | * resolved value is a Ketting resource and then call 'follow' on it.
|
45 | *
|
46 | * The function returns a Promise that will resolve into the result of that
|
47 | * 'follow' function.
|
48 | *
|
49 | * In practice this means you can chain multiple 'follow' calls.
|
50 | */
|
51 | follow(rel: string, variables?: object): FollowablePromise {
|
52 |
|
53 | return new FollowablePromise((resolve: (value: FollowablePromise) => void, reject: (reason: any) => void) => {
|
54 |
|
55 | this.realPromise.then((resource: Resource) => {
|
56 | resolve(resource.follow(rel, variables));
|
57 |
|
58 | }).catch(err => {
|
59 | reject(err);
|
60 | });
|
61 |
|
62 | });
|
63 |
|
64 | }
|
65 |
|
66 | /**
|
67 | * The followAll function will wait for this promise to resolve, assume the
|
68 | * resolved value is a Ketting resource and then call 'followAll' on it.
|
69 | *
|
70 | * The function returns a Promise that will resolve into the result of that
|
71 | * 'followAll' function.
|
72 | *
|
73 | * In practice this means you can end a chain of 'follow' calls in the
|
74 | * 'followAll' call.
|
75 | *
|
76 | * It's really the same idea as the follow function, except that you can't
|
77 | * keep on chaining after the followAll, because it resolves in an array of
|
78 | * resources.
|
79 | */
|
80 | followAll(rel: string): Promise<Resource[]> {
|
81 | return this.realPromise.then((resource: Resource) => {
|
82 | return resource.followAll(rel);
|
83 | });
|
84 | }
|
85 |
|
86 | }
|
87 |
|
\ | No newline at end of file |