Skip to content

Commit

Permalink
use the https library to support secure and insecure requests
Browse files Browse the repository at this point in the history
  • Loading branch information
craig-day committed Mar 2, 2018
1 parent 7b216c0 commit e6f9c03
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions app/components/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import React from 'react';
import ReactDOM from 'react-dom';
import GraphiQL from 'graphiql/dist';
import Modal from 'react-modal/lib/index';
import { ClientRequest } from 'http';
import { request as httpRequest } from 'http';
import { request as httpsRequest } from 'https';

Modal.setAppElement(document.getElementById('react-root'));

Expand Down Expand Up @@ -183,7 +184,8 @@ export default class App extends React.Component {

graphQLFetcher = (graphQLParams) => {
const defaultHeaders = {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
'User-Agent': 'graphiql-app'
};

const error = {
Expand Down Expand Up @@ -222,17 +224,16 @@ export default class App extends React.Component {
url.search = `query=${query}&variables=${variables}`;
}

const request = new ClientRequest({
const requestOptions = {
method,
protocol: url.protocol,
hostname: url.hostname,
port: url.port,
path: url.pathname + url.search,
});
headers: requestHeaders,
};

for (const header in requestHeaders) {
request.setHeader(header, requestHeaders[header]);
}
const request = url.protocol === 'https:' ? httpsRequest(requestOptions) : httpRequest(requestOptions);

return new Promise((resolve, reject) => {
request.on('response', response => {
Expand All @@ -241,10 +242,17 @@ export default class App extends React.Component {
chunks.push(Buffer.from(data));
});
response.on('end', end => {
resolve(JSON.parse(Buffer.concat(chunks).toString()));
const data = Buffer.concat(chunks).toString();
if (response.statusCode >= 400) {
reject(data);
} else {
resolve(JSON.parse(data));
}
});
});

request.on('error', reject);

if (method == "get") {
request.end();
} else {
Expand Down

0 comments on commit e6f9c03

Please sign in to comment.