This repository has been archived by the owner on Apr 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathhttpServer.js
106 lines (78 loc) · 2.61 KB
/
httpServer.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
/**
* @providesModule react-native-http-server
*/
'use strict';
import { DeviceEventEmitter } from 'react-native';
import { NativeModules } from 'react-native';
var RNHS = NativeModules.RNHttpServer;
var validStatusCodes = [ 'ACCEPTED',
'BAD_REQUEST',
'CREATED',
'FORBIDDEN',
'INTERNAL_ERROR',
'METHOD_NOT_ALLOWED',
'NO_CONTENT',
'NOT_FOUND',
'NOT_MODIFIED',
'OK',
'PARTIAL_CONTENT',
'RANGE_NOT_SATISFIABLE',
'REDIRECT',
'UNAUTHORIZED' ];
module.exports = {
// create the server and listen/respond to requests
create: function(options, callback) {
//Validate port
if(options.port == 80){
throw "Invalid server port specified. Port 80 is reserved.";
}
// fire up the server
RNHS.init(options, function() {
// listen for new requests and retrieve appropriate response
DeviceEventEmitter.addListener('reactNativeHttpServerResponse', function(request) {
var success = true;
var promise = new Promise(function(resolve, reject){
callback(request, resolve);
})
.then(function(response){
//Validate status code
if(validStatusCodes.indexOf(response.status) === 0){
success = false;
throw "Invalid response status code specified in RNHttpServer options.";
}
//Set default MIME_TYPE
if(response.type === null){
response.type = "text/plain";
}
//Set default data field to zero length string
if(response.data === null){
response.data = "";
}
if(response.headers === null){
response.headers = {};
}
if(success){
RNHS.setResponse(request.url, response);
}
});
});
}, function(e){
throw "Could not initialise server: " + e;
});
},
// attempt to start the instance of the server - returns a promise object that will be rejected or approved
start: function() {
var promise = new Promise(function(resolve, reject){
RNHS.start(function(){
resolve();
}, function(){
reject();
});
});
return promise;
},
// effectively pause the instance of the server
stop: function() {
RNHS.stop();
}
}