Skip to content

Commit

Permalink
Keep-alive (reuse) connections running in NodeJS environment to reduc…
Browse files Browse the repository at this point in the history
…e the number of new connections

Ref: near/nearcore#1316
  • Loading branch information
frol committed Oct 4, 2019
1 parent 2485e64 commit 2cf6dca
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
23 changes: 22 additions & 1 deletion lib/utils/web.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 23 additions & 1 deletion src.ts/utils/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,29 @@ export interface ConnectionInfo {
headers?: { [key: string]: string | number };
}

const fetch = (typeof window === 'undefined' || window.name === 'nodejs') ? require('node-fetch') : window.fetch;
let fetch;
if (typeof window === 'undefined' || window.name === 'nodejs') {
const nodeFetch = require('node-fetch');
const http = require('http');
const https = require('https');

const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });

function agent(_parsedURL) {
if (_parsedURL.protocol === 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}

fetch = function(resource, init) {
return nodeFetch(resource, { agent, ...init });
};
} else {
fetch = window.fetch;
}

export async function fetchJson(connection: string | ConnectionInfo, json?: string): Promise<any> {
let url: string = null;
Expand Down

0 comments on commit 2cf6dca

Please sign in to comment.