Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Replace request with needle #303

Merged
merged 1 commit into from
Jul 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6,687 changes: 3,011 additions & 3,676 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@
"cross-spawn": "^7.0.1",
"libnpmconfig": "^1.2.1",
"mkdirp": "1.0.0",
"needle": "^2.6.0",
"pino": "^6.11.0",
"pino-pretty": "^4.1.0",
"promise-timeout": "^1.3.0",
"request": "2.88.0",
"rimraf": "2.6.2",
"sumchecker": "^2.0.2",
"tar": "4.4.2",
Expand All @@ -82,6 +82,7 @@
"@types/jest": "^25.2.3",
"@types/mkdirp": "^0.5.2",
"@types/mocha": "2.2.48",
"@types/needle": "^2.5.1",
"@types/node": "9.4.6",
"@types/promise-timeout": "^1.3.0",
"@types/rimraf": "^2.0.2",
Expand Down
36 changes: 15 additions & 21 deletions src/service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import path = require('path');
import fs = require('fs');
import events = require('events');
import http = require('request');
import logger, { setLogLevel } from './logger';
import spawn, { CliVerbOptions } from './spawn';
import { ChildProcess } from 'child_process';
import { timeout, TimeoutError } from 'promise-timeout';
import mkdirp = require('mkdirp');
import checkTypes = require('check-types');
import needle = require('needle');

// Get a reference to the global setTimeout object in case it is mocked by a testing library later
const setTimeout = global.setTimeout;
Expand Down Expand Up @@ -313,27 +313,28 @@ export abstract class AbstractService extends events.EventEmitter {
private __call(options: ServiceOptions): Promise<unknown> {
return new Promise<void>((resolve, reject) => {
const config: HTTPConfig = {
uri: `http${options.ssl ? 's' : ''}://${options.host}:${options.port}`,
method: 'GET',
headers: {
'X-Pact-Mock-Service': true,
'X-Pact-Mock-Service': 'true',
'Content-Type': 'application/json',
},
};

if (options.ssl) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
config.agentOptions = {};
config.agentOptions.rejectUnauthorized = false;
config.agentOptions.requestCert = false;
config.agentOptions.agent = false;
config.rejectUnauthorized = false;
config.agent = false;
}

http(config, (err: Error, res) => {
!err && res.statusCode === 200
? resolve()
: reject(`HTTP Error: '${JSON.stringify(err ? err : res)}'`);
});
needle.get(
`http${options.ssl ? 's' : ''}://${options.host}:${options.port}`,
config,
(err: Error | null, res) => {
!err && res.statusCode === 200
? resolve()
: reject(`HTTP Error: '${JSON.stringify(err ? err : res)}'`);
}
);
});
}
}
Expand All @@ -355,16 +356,9 @@ export interface ServiceOptions {
// levels, we'll need to change the type.
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';

export interface HTTPConfig {
uri: string;
method: string;
export interface HTTPConfig extends Omit<needle.NeedleOptions, 'headers'> {
headers: {
'X-Pact-Mock-Service': boolean;
'X-Pact-Mock-Service': string;
'Content-Type': string;
};
agentOptions?: {
rejectUnauthorized?: boolean;
requestCert?: boolean;
agent?: boolean;
};
}
2 changes: 1 addition & 1 deletion src/spawn/arguments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { CanDeployOptions } from '../can-deploy';
import { MessageOptions } from '../message';
import { PublisherOptions } from '../publisher';
import { ServiceOptions } from '../service';
import { VerifierOptions } from '../verifier/types';
import { VerifierOptions } from '../verifier';

import _ = require('underscore');
import checkTypes = require('check-types');
Expand Down
6 changes: 3 additions & 3 deletions src/verifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,9 @@ export class Verifier {
this.__argMapping
);
const output: Array<string | Buffer> = [];
instance.stdout.on('data', l => output.push(l));
instance.stderr.on('data', l => output.push(l));
instance.once('close', code => {
instance.stdout.on('data', (l) => output.push(l));
instance.stderr.on('data', (l) => output.push(l));
instance.once('close', (code) => {
const o = output.join('\n');
code === 0 ? resolve(o) : reject(new Error(o));
});
Expand Down
43 changes: 22 additions & 21 deletions standalone/install.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as http from 'http';
import * as Request from 'request';
import * as needle from 'needle';
import unzipper = require('unzipper');
import tar = require('tar');
import pactEnvironment from '../src/pact-environment';
Expand All @@ -14,13 +14,15 @@ const config = require('libnpmconfig');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const sumchecker = require('sumchecker');

// Sets the request default for all calls through npm environment variables for proxy
const request = Request.defaults({
proxy:
process.env.npm_config_https_proxy ||
process.env.npm_config_proxy ||
undefined,
});
// Sets the needle default for all calls through npm environment variables for proxy
const environmentProxy =
process.env.npm_config_https_proxy || process.env.npm_config_proxy;

if (environmentProxy) {
needle.defaults({
proxy: environmentProxy,
});
}

// Get latest version from https://github.com/pact-foundation/pact-ruby-standalone/releases
export const PACT_STANDALONE_VERSION = '1.88.58';
Expand Down Expand Up @@ -160,16 +162,16 @@ function downloadFileRetry(
if (ca) {
ca = fs.readFileSync(ca);
}
request({
url,
headers: {
'User-Agent': 'https://github.com/pact-foundation/pact-js-core',
},
strictSSL: config.read()['strict-ssl'],
agentOptions: {
needle
.get(url, {
// eslint-disable-next-line @typescript-eslint/camelcase
follow_max: 5,
headers: {
'User-Agent': 'https://github.com/pact-foundation/pact-js-core',
},
rejectUnauthorized: config.read()['strict-ssl'] || false,
ca: ca,
},
})
})
.on('error', (e: string) => reject(e))
.on(
'response',
Expand Down Expand Up @@ -225,9 +227,8 @@ function download(data: Data): Promise<Data> {
// Trying to find all environment variables of all possible CI services to get more accurate stats
// but it's still not 100% since not all systems have unique environment variables for their CI server
const isCI = CIs.some((key) => process.env[key] !== undefined);
request
.post({
url: 'https://www.google-analytics.com/collect',
needle
.post('https://www.google-analytics.com/collect', {
form: {
v: 1,
tid: 'UA-117778936-1', // Tracking ID / Property ID.
Expand Down Expand Up @@ -393,7 +394,7 @@ function setup(platform?: string, arch?: string): Promise<Data> {
});
}

// This function is unused, but I'm not touching it.
// This function is used in the pretest script
export function downloadChecksums(): Promise<void> {
console.log(chalk.gray(`Downloading All Pact Standalone Binary Checksums.`));
return Promise.all(
Expand Down
2 changes: 1 addition & 1 deletion test/integration/broker-mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export default (port: number): Promise<http.Server> => {

// Matrix
server.get('/matrix', (req: express.Request, res: express.Response) => {
if (req.query.q[0].pacticipant === 'Foo') {
if (req.query && req.query.q && req.query.q[0].pacticipant === 'Foo') {
return res.json({
summary: {
deployable: true,
Expand Down
2 changes: 1 addition & 1 deletion test/verifier.integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe('Verifier Integration Spec', () => {
const monkeypatchFile: string = path.resolve(__dirname, 'monkeypatch.rb');

before(() =>
providerMock(PORT).then(s => {
providerMock(PORT).then((s) => {
console.log(`Pact Broker Mock listening on port: ${PORT}`);
server = s;
})
Expand Down