forked from futurepress/react-native-static-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
125 lines (104 loc) · 2.55 KB
/
index.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import {
NativeModules,
AppState,
Platform
} from 'react-native';
const { FPStaticServer } = NativeModules;
const PORT = '';
const ROOT = null;
const LOCALHOST = 'http://127.0.0.1:';
class StaticServer {
constructor(port, root, opts) {
switch (arguments.length) {
case 3:
this.port = `${port}` || PORT;
this.root = root || ROOT;
this.localOnly = (opts && opts.localOnly) || false;
this.keepAlive = (opts && opts.keepAlive) || false;
break;
case 2:
this.port = `${port}`;
if (typeof(arguments[1]) === 'string') {
this.root = root;
this.localOnly = false;
this.keepAlive = false;
} else {
this.root = ROOT;
this.localOnly = (arguments[1] && arguments[1].localOnly) || false;
this.keepAlive = (arguments[1] && arguments[1].keepAlive) || false;
}
break;
case 1:
if (typeof(arguments[0]) === 'number') {
this.port = `${port}`;
this.root = ROOT;
this.localOnly = false;
this.keepAlive = false;
} else {
this.port = PORT;
this.root = ROOT;
this.localOnly = (arguments[0] && arguments[0].localOnly) || false;
this.keepAlive = (arguments[0] && arguments[0].keepAlive) || false;
}
break;
default:
this.port = PORT;
this.root = ROOT;
this.localOnly = false;
this.keepAlive = false;
}
this.started = false;
this._origin = undefined;
this._handleAppStateChangeFn = this._handleAppStateChange.bind(this);
}
start() {
if( this.running ){
return Promise.resolve(this.origin);
}
this.started = true;
this.running = true;
if (!this.keepAlive && (Platform.OS === 'android')) {
AppState.addEventListener('change', this._handleAppStateChangeFn);
}
return FPStaticServer.start(this.port, this.root, this.localOnly, this.keepAlive)
.then((origin) => {
this._origin = origin;
return origin;
});
}
stop() {
this.running = false;
return FPStaticServer.stop();
}
kill() {
this.stop();
this.started = false;
this._origin = undefined;
AppState.removeEventListener('change', this._handleAppStateChangeFn);
}
_handleAppStateChange(appState) {
if (!this.started) {
return;
}
if (appState === "active" && !this.running) {
this.start();
}
if (appState === "background" && this.running) {
this.stop();
}
if (appState === "inactive" && this.running) {
this.stop();
}
}
get origin() {
return this._origin;
}
isRunning() {
return FPStaticServer.isRunning()
.then(running => {
this.running = running;
return this.running;
})
}
}
export default StaticServer;