UNPKG

2.11 kBJavaScriptView Raw
1import Http from "http";
2import Url from "url";
3import QueryString from "querystring";
4
5export default function request(url, options){
6 url = Url.parse(url);
7 const method = options && options.method === "POST" ? "POST" : "GET";
8 return new Promise(function(resolve, reject){
9 const req = Http.request({
10 hostname: url.hostname,
11 port: url.port,
12 path: url.path,
13 method: method
14 }, function(res) {
15 const statusCode = res.statusCode;
16 const contentType = res.headers['content-type'];
17
18 let error;
19 if (statusCode < 200 || statusCode >= 300) {
20 reject({
21 type: "status",
22 value: statusCode
23 });
24 res.resume();
25 return;
26 } else if (!/^application\/json/.test(contentType)) {
27 reject({
28 type: "content-type",
29 value: contentType
30 });
31 res.resume();
32 return;
33 }
34
35 res.setEncoding('utf8');
36 let rawData = '';
37 res.on('data', (chunk) => rawData += chunk);
38 res.on('end', () => {
39 try {
40 let parsedData = JSON.parse(rawData);
41 resolve({
42 code: statusCode,
43 value: parsedData
44 });
45 } catch (e) {
46 reject({
47 type: "parse-json",
48 value: e
49 });
50 }
51 });
52 }).on('error', function(e) {
53 reject({
54 type: "other",
55 value: e
56 });
57 });
58
59 if(method === "POST"){
60 req.write(QueryString.stringify(options.data));
61 }
62
63 req.end();
64 });
65}
66
67request.get = function(url){
68 return request(url);
69}
70
71request.post = function(url, data){
72 return request(url, {
73 method: "POST",
74 data: data
75 });
76}
\No newline at end of file