-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathRelayNetworkLayer.js
More file actions
106 lines (94 loc) · 2.78 KB
/
Copy pathRelayNetworkLayer.js
File metadata and controls
106 lines (94 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* @flow */
import { Network } from 'relay-runtime';
import RelayRequest from './RelayRequest';
import fetchWithMiddleware from './fetchWithMiddleware';
import type {
Middleware,
MiddlewareSync,
MiddlewareRaw,
FetchFunction,
FetchHookFunction,
SubscribeFunction,
RNLExecuteFunction,
} from './definition';
export type RelayNetworkLayerOpts = {|
subscribeFn?: SubscribeFunction,
beforeFetch?: FetchHookFunction,
noThrow?: boolean,
|};
export default class RelayNetworkLayer {
_middlewares: Middleware[];
_rawMiddlewares: MiddlewareRaw[];
_middlewaresSync: RNLExecuteFunction[];
execute: RNLExecuteFunction;
executeWithEvents: any;
+fetchFn: FetchFunction;
+subscribeFn: ?SubscribeFunction;
+noThrow: boolean;
constructor(
middlewares: Array<?Middleware | MiddlewareSync | MiddlewareRaw>,
opts?: RelayNetworkLayerOpts
) {
this._middlewares = [];
this._rawMiddlewares = [];
this._middlewaresSync = [];
this.noThrow = false;
const mws = Array.isArray(middlewares) ? (middlewares: any) : [middlewares];
mws.forEach((mw) => {
if (mw) {
if (mw.execute) {
this._middlewaresSync.push(mw.execute);
} else if (mw.isRawMiddleware) {
this._rawMiddlewares.push(mw);
} else {
this._middlewares.push(mw);
}
}
});
if (opts) {
this.subscribeFn = opts.subscribeFn;
this.noThrow = opts.noThrow === true;
// TODO deprecate
if (opts.beforeFetch) {
this._middlewaresSync.push((opts.beforeFetch: any));
}
}
this.fetchFn = (operation, variables, cacheConfig, uploadables) => {
for (let i = 0; i < this._middlewaresSync.length; i++) {
const res = this._middlewaresSync[i](operation, variables, cacheConfig, uploadables);
if (res) return res;
}
return {
subscribe: (sink) => {
const req = new RelayRequest(operation, variables, cacheConfig, uploadables);
const res = fetchWithMiddleware(
req,
this._middlewares,
this._rawMiddlewares,
this.noThrow
);
res
.then(
(value) => {
sink.next(value);
sink.complete();
},
(error) => {
if (error && error.name && error.name === 'AbortError') {
sink.complete();
} else sink.error(error);
}
)
// avoid unhandled promise rejection error
.catch(() => {});
return () => {
req.cancel();
};
},
};
};
const network = Network.create(this.fetchFn, this.subscribeFn);
this.execute = network.execute;
this.executeWithEvents = network.executeWithEvents;
}
}