forked from Strainy/react-native-http-server
-
Notifications
You must be signed in to change notification settings - Fork 2
/
httpServer.js
49 lines (37 loc) · 1.55 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
/**
* @providesModule react-native-http-server
*/
'use strict';
import {DeviceEventEmitter} from 'react-native';
import {NativeModules} from 'react-native';
const 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',
];
const nativeServerModule = NativeModules.RNHttpServer;
module.exports = {
init: (options, callback) => {
// listen for new requests and retrieve appropriate response
DeviceEventEmitter.addListener('reactNativeHttpServerResponse', async function (request) {
let response = await new Promise((resolve) => { callback(request, resolve); })
//Validate status code
if (validStatusCodes.indexOf(response.status) === -1) {
throw new Error("Invalid response status code specified in RNHttpServer options.");
}
if (response.type == null) {
response.type = "text/plain";
}
if (response.data == null) {
response.data = "";
}
if (response.headers == null) {
response.headers = {};
}
nativeServerModule.setResponse(request.url, response);
});
nativeServerModule.init(options);
},
start: nativeServerModule != null ? nativeServerModule.start : undefined,
stop: nativeServerModule != null ? nativeServerModule.stop : undefined,
}