forked from react-native-community/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenURLMiddleware.ts
More file actions
56 lines (47 loc) · 1.19 KB
/
openURLMiddleware.ts
File metadata and controls
56 lines (47 loc) · 1.19 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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {IncomingMessage, ServerResponse} from 'http';
import {json} from 'body-parser';
import connect from 'connect';
import open from 'open';
/**
* Open a URL in the system browser.
*/
async function openURLMiddleware(
req: IncomingMessage & {
// Populated by body-parser
body?: Object;
},
res: ServerResponse,
next: (err?: Error) => void,
) {
if (req.method === 'POST') {
if (req.body == null) {
res.writeHead(400);
res.end('Missing request body');
return;
}
const {url} = req.body as {url: string};
try {
const parsedUrl = new URL(url);
if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
res.writeHead(400);
res.end('Invalid URL protocol');
return;
}
} catch (error) {
res.writeHead(400);
res.end('Invalid URL format');
return;
}
await open(url);
res.writeHead(200);
res.end();
}
next();
}
export default connect().use(json()).use(openURLMiddleware);