UNPKG

2.52 kBPlain TextView Raw
1import Resource from './resource';
2
3type Executor =
4 (
5 res: ((value: FollowablePromise) => void),
6 rej: ((reason: any) => any)
7 )
8 => void;
9
10/**
11 * The FollowablePromise is a Promise that adds the follow and followAll
12 * functions.
13 *
14 * It's really just a thin wrapper around the promise. Note that we're not
15 * extending the built-in Promise object, but proxy it as browsers don't allow
16 * extending the Promise object.
17 */
18export default class FollowablePromise {
19
20 realPromise: Promise<Resource>;
21
22 constructor(executor: Executor ) {
23 this.realPromise = new Promise(executor);
24 }
25
26 /**
27 * The then function maps to a standard then function, as it appears on the
28 * promise.
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 * The catch function maps to a standard then function, as it appears on the
36 * promise.
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