From 2f7bde37ff24c3bdc96809b905f7945db4e3992d Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Sun, 2 Feb 2020 21:01:18 -0800 Subject: [PATCH 1/9] DO NOT MERGE: migrate to gts2 --- .eslintrc.json | 3 + .eslintrc.yml | 15 - .prettierrc | 8 - .prettierrc.json | 3 + browser-test/browser-test-runner.ts | 30 +- browser-test/test.browser.ts | 31 +- karma.conf.js | 40 +-- package.json | 6 +- prettier.config.js | 2 +- samples/package.json | 3 + samples/quickstart.js | 6 +- samples/test/test.samples.js | 14 +- src/.eslintrc.json | 5 + src/common.ts | 30 +- src/gaxios.ts | 66 ++-- src/index.ts | 10 +- src/retry.ts | 22 +- system-test/fixtures/sample/src/index.ts | 4 +- system-test/fixtures/sample/webpack.config.js | 24 +- system-test/test.install.ts | 50 +-- test/test.getch.ts | 290 +++++++++--------- test/test.index.ts | 10 +- test/test.retry.ts | 178 +++++------ tslint.json | 8 - webpack-tests.config.js | 18 +- webpack.config.js | 26 +- 26 files changed, 453 insertions(+), 449 deletions(-) create mode 100644 .eslintrc.json delete mode 100644 .eslintrc.yml delete mode 100644 .prettierrc create mode 100644 .prettierrc.json create mode 100644 src/.eslintrc.json delete mode 100644 tslint.json diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 00000000..78215349 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "./node_modules/gts" +} diff --git a/.eslintrc.yml b/.eslintrc.yml deleted file mode 100644 index 73eeec27..00000000 --- a/.eslintrc.yml +++ /dev/null @@ -1,15 +0,0 @@ ---- -extends: - - 'eslint:recommended' - - 'plugin:node/recommended' - - prettier -plugins: - - node - - prettier -rules: - prettier/prettier: error - block-scoped-var: error - eqeqeq: error - no-warning-comments: warn - no-var: error - prefer-const: error diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index df6eac07..00000000 --- a/.prettierrc +++ /dev/null @@ -1,8 +0,0 @@ ---- -bracketSpacing: false -printWidth: 80 -semi: true -singleQuote: true -tabWidth: 2 -trailingComma: es5 -useTabs: false diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..8803584c --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,3 @@ +{ + "prettier": "./node_modules/gts/build/src/prettier.config.js" +} diff --git a/browser-test/browser-test-runner.ts b/browser-test/browser-test-runner.ts index 0908e231..5d70380a 100644 --- a/browser-test/browser-test-runner.ts +++ b/browser-test/browser-test-runner.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import execa from 'execa'; -import express from 'express'; -import http from 'http'; +import execa from "execa"; +import express from "express"; +import http from "http"; const port = 7172; @@ -35,30 +35,32 @@ async function listen( // tests. async function main() { const app = express(); - app.get('/path', (req: express.Request, res: express.Response) => { - if (req.header('origin')) { - res.set('Access-Control-Allow-Origin', req.header('origin')); + app.get("/path", (req: express.Request, res: express.Response) => { + if (req.header("origin")) { + res.set("Access-Control-Allow-Origin", req.header("origin")); } - res.send('response'); + res.send("response"); }); - app.get('/querystring', (req: express.Request, res: express.Response) => { - if (req.header('origin')) { - res.set('Access-Control-Allow-Origin', req.header('origin')); + app.get("/querystring", (req: express.Request, res: express.Response) => { + if (req.header("origin")) { + res.set("Access-Control-Allow-Origin", req.header("origin")); } const query = req.query.query; - res.send(query || ''); + res.send(query || ""); }); const server = await listen(app, port); console.log(`[http server] I'm listening on port ${port}! Starting karma.`); - const result = await execa('karma', ['start'], {stdio: 'inherit'}); + const result = await execa("karma", ["start"], { stdio: "inherit" }); server.close(); console.log( `[http server] Karma has finished! I'm no longer listening on port ${port}!` ); - process.exit(result.failed ? 1 : 0); + if (result.failed) { + throw new Error("Tests failed."); + } } main().catch(err => { - console.log('Error:', err); + console.log("Error:", err); }); diff --git a/browser-test/test.browser.ts b/browser-test/test.browser.ts index 827eac33..35b18f94 100644 --- a/browser-test/test.browser.ts +++ b/browser-test/test.browser.ts @@ -1,21 +1,34 @@ -import assert from 'assert'; +// Copyright 2019, Google, LLC. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. -import {request} from '../src/index'; +import assert from "assert"; +import { describe, it } from "mocha"; +import { request } from "../src/index"; const port = 7172; // should match the port defined in `webserver.ts` -describe('💻 browser tests', () => { - it('should just work from browser', async () => { - const result = await request({url: `http://localhost:${port}/path`}); +describe("💻 browser tests", () => { + it("should just work from browser", async () => { + const result = await request({ url: `http://localhost:${port}/path` }); assert.strictEqual(result.status, 200); - assert.strictEqual(result.data, 'response'); + assert.strictEqual(result.data, "response"); }); - it('should pass querystring parameters from browser', async () => { + it("should pass querystring parameters from browser", async () => { const result = await request({ url: `http://localhost:${port}/querystring`, - params: {query: 'value'}, + params: { query: "value" } }); assert.strictEqual(result.status, 200); - assert.strictEqual(result.data, 'value'); + assert.strictEqual(result.data, "value"); }); }); diff --git a/karma.conf.js b/karma.conf.js index 954ccfb3..41b59030 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -14,25 +14,25 @@ // Karma configuration // Use `npm run browser-test` to run browser tests with Karma. -const fs = require('fs'); -const isDocker = require('is-docker')(); +const fs = require("fs"); +const isDocker = require("is-docker")(); -const webpackConfig = require('./webpack-tests.config.js'); -process.env.CHROME_BIN = fs.existsSync('/usr/bin/chromium-browser') - ? '/usr/bin/chromium-browser' - : require('puppeteer').executablePath(); +const webpackConfig = require("./webpack-tests.config.js"); +process.env.CHROME_BIN = fs.existsSync("/usr/bin/chromium-browser") + ? "/usr/bin/chromium-browser" + : require("puppeteer").executablePath(); -module.exports = function (config) { +module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', + basePath: "", // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['mocha'], + frameworks: ["mocha"], // list of files / patterns to load in the browser - files: ['./browser-test/test.*.ts'], + files: ["./browser-test/test.*.ts"], // list of files / patterns to exclude exclude: [], @@ -40,9 +40,9 @@ module.exports = function (config) { // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { - './src/*.ts': ['coverage'], - './src/**/*.ts': ['coverage'], - './browser-test/*.ts': ['webpack', 'sourcemap'] + "./src/*.ts": ["coverage"], + "./src/**/*.ts": ["coverage"], + "./browser-test/*.ts": ["webpack", "sourcemap"] }, webpack: webpackConfig, @@ -50,10 +50,10 @@ module.exports = function (config) { // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['progress', 'coverage', 'remap-coverage'], + reporters: ["progress", "coverage", "remap-coverage"], - coverageReporter: { type: 'in-memory' }, - remapCoverageReporter: { html: './coverage' }, + coverageReporter: { type: "in-memory" }, + remapCoverageReporter: { html: "./coverage" }, // web server port port: 9876, @@ -70,13 +70,13 @@ module.exports = function (config) { // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['ChromeCustom'], + browsers: ["ChromeCustom"], customLaunchers: { ChromeCustom: { - base: 'ChromeHeadless', + base: "ChromeHeadless", // We must disable the Chrome sandbox when running Chrome inside Docker (Chrome's sandbox needs // more permissions than Docker allows by default) - flags: isDocker ? ['--no-sandbox'] : [] + flags: isDocker ? ["--no-sandbox"] : [] } }, @@ -90,7 +90,7 @@ module.exports = function (config) { // set correct MIME type when serving .ts files (already compiled to JavaScript): mime: { - 'text/javascript': ['ts'] + "text/javascript": ["ts"] } }); }; diff --git a/package.json b/package.json index 525cc263..1bbeb396 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,9 @@ "docs": "compodoc src/", "docs-test": "linkinator docs", "predocs-test": "npm run docs", - "samples-test": "cd samples/ && npm link ../ && npm test && cd ../" + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "check": "gts check", + "posttest": "npm run check" }, "repository": "JustinBeckwith/gaxios", "keywords": [ @@ -52,7 +54,7 @@ "codecov": "^3.2.0", "execa": "^4.0.0", "express": "^4.16.4", - "gts": "^1.0.0", + "gts": "file:../gts/gts-1.1.2.tgz", "is-docker": "^2.0.0", "karma": "^4.0.0", "karma-chrome-launcher": "^3.0.0", diff --git a/prettier.config.js b/prettier.config.js index a425d3f7..d305ebd0 100644 --- a/prettier.config.js +++ b/prettier.config.js @@ -1,4 +1,4 @@ module.exports = { singleQuote: true, - trailingComma: 'es5', + trailingComma: "es5" }; diff --git a/samples/package.json b/samples/package.json index ffa58ca9..89be4984 100644 --- a/samples/package.json +++ b/samples/package.json @@ -1,6 +1,9 @@ { "name": "gaxios-samples", "private": true, + "files": [ + "*.js" + ], "scripts": { "test": "mocha" }, diff --git a/samples/quickstart.js b/samples/quickstart.js index d41e2f94..46e3016a 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -13,14 +13,14 @@ // limitations under the License. // [START gaxios_quickstart] -const {request} = require('gaxios'); +const { request } = require("gaxios"); /** * Perform a simple `GET` request to a JSON API. */ async function quickstart() { - const url = 'https://www.googleapis.com/discovery/v1/apis/'; - const res = await request({url}); + const url = "https://www.googleapis.com/discovery/v1/apis/"; + const res = await request({ url }); console.log(`status: ${res.status}`); console.log(`data:`); console.log(res.data); diff --git a/samples/test/test.samples.js b/samples/test/test.samples.js index ded929fd..8132f2db 100644 --- a/samples/test/test.samples.js +++ b/samples/test/test.samples.js @@ -12,15 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -const {execSync} = require('child_process'); -const {assert} = require('chai'); -const {describe, it} = require('mocha'); +const { execSync } = require("child_process"); +const { assert } = require("chai"); +const { describe, it } = require("mocha"); -const exec = cmd => execSync(cmd, { encoding: 'utf8'}); +const exec = cmd => execSync(cmd, { encoding: "utf8" }); describe(__filename, () => { - it('should run the quickstart', () => { - const output = exec('node quickstart'); - assert.include(output, 'status: 200'); + it("should run the quickstart", () => { + const output = exec("node quickstart"); + assert.include(output, "status: 200"); }); }); diff --git a/src/.eslintrc.json b/src/.eslintrc.json new file mode 100644 index 00000000..e5a34aec --- /dev/null +++ b/src/.eslintrc.json @@ -0,0 +1,5 @@ +{ + "env": { + "browser": true + } +} diff --git a/src/common.ts b/src/common.ts index 364f911f..780f4c9c 100644 --- a/src/common.ts +++ b/src/common.ts @@ -11,11 +11,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {AbortSignal} from 'abort-controller'; -import {Agent} from 'http'; -import {URL} from 'url'; +import { AbortSignal } from "abort-controller"; +import { Agent } from "http"; +import { URL } from "url"; -// tslint:disable no-any +/* eslint-disable @typescript-eslint/no-explicit-any */ export class GaxiosError extends Error { code?: string; @@ -64,15 +64,15 @@ export interface GaxiosOptions { baseUrl?: string; // deprecated baseURL?: string; method?: - | 'GET' - | 'HEAD' - | 'POST' - | 'DELETE' - | 'PUT' - | 'CONNECT' - | 'OPTIONS' - | 'TRACE' - | 'PATCH'; + | "GET" + | "HEAD" + | "POST" + | "DELETE" + | "PUT" + | "CONNECT" + | "OPTIONS" + | "TRACE" + | "PATCH"; headers?: Headers; data?: any; body?: any; @@ -86,10 +86,10 @@ export interface GaxiosOptions { maxRedirects?: number; follow?: number; params?: any; - paramsSerializer?: (params: {[index: string]: string | number}) => string; + paramsSerializer?: (params: { [index: string]: string | number }) => string; timeout?: number; onUploadProgress?: (progressEvent: any) => void; - responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream'; + responseType?: "arraybuffer" | "blob" | "json" | "text" | "stream"; agent?: Agent | ((parsedUrl: URL) => Agent); validateStatus?: (status: number) => boolean; retryConfig?: RetryConfig; diff --git a/src/gaxios.ts b/src/gaxios.ts index 7f9c294c..8ab49427 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -11,30 +11,30 @@ // See the License for the specific language governing permissions and // limitations under the License. -import extend from 'extend'; -import {Agent} from 'http'; -import nodeFetch, {Response as NodeFetchResponse} from 'node-fetch'; -import qs from 'querystring'; -import stream from 'stream'; -import isStream from 'is-stream'; -import url from 'url'; +import extend from "extend"; +import { Agent } from "http"; +import nodeFetch, { Response as NodeFetchResponse } from "node-fetch"; +import qs from "querystring"; +import isStream from "is-stream"; +import url from "url"; import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse, - Headers, -} from './common'; -import {getRetryConfig} from './retry'; + Headers +} from "./common"; +import { getRetryConfig } from "./retry"; -// tslint:disable no-any +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable node/no-unsupported-features/node-builtins */ const URL = hasURL() ? window.URL : url.URL; const fetch = hasFetch() ? window.fetch : nodeFetch; function hasWindow() { - return typeof window !== 'undefined' && !!window; + return typeof window !== "undefined" && !!window; } function hasURL() { @@ -45,7 +45,6 @@ function hasFetch() { return hasWindow() && !!window.fetch; } -// tslint:disable-next-line variable-name let HttpsProxyAgent: any; // Figure out if we should be using a proxy. Only if it's required, load @@ -57,7 +56,7 @@ function loadProxy() { process.env.HTTP_PROXY || process.env.http_proxy; if (proxy) { - HttpsProxyAgent = require('https-proxy-agent'); + HttpsProxyAgent = require("https-proxy-agent"); } return proxy; } @@ -116,7 +115,7 @@ export class Gaxios { } catch (e) { const err = e as GaxiosError; err.config = opts; - const {shouldRetry, config} = await getRetryConfig(e); + const { shouldRetry, config } = await getRetryConfig(e); if (shouldRetry && config) { err.config.retryConfig!.currentRetryAttempt = config.retryConfig!.currentRetryAttempt; return this._request(err.config); @@ -130,17 +129,20 @@ export class Gaxios { res: Response | NodeFetchResponse ): Promise { switch (opts.responseType) { - case 'stream': + case "stream": return res.body; - case 'json': + case "json": { let data = await res.text(); try { data = JSON.parse(data); - } catch (e) {} + } catch { + // continue + } return data as {}; - case 'arraybuffer': + } + case "arraybuffer": return res.arrayBuffer(); - case 'blob': + case "blob": return res.blob(); default: return res.text(); @@ -154,7 +156,7 @@ export class Gaxios { private validateOpts(options: GaxiosOptions): GaxiosOptions { const opts = extend(true, {}, this.defaults, options); if (!opts.url) { - throw new Error('URL is required.'); + throw new Error("URL is required."); } // baseUrl has been deprecated, remove in 2.0 @@ -177,11 +179,11 @@ export class Gaxios { opts.url = parsedUrl.href; - if (typeof options.maxContentLength === 'number') { + if (typeof options.maxContentLength === "number") { opts.size = options.maxContentLength; } - if (typeof options.maxRedirects === 'number') { + if (typeof options.maxRedirects === "number") { opts.follow = options.maxRedirects; } @@ -189,20 +191,20 @@ export class Gaxios { if (opts.data) { if (isStream.readable(opts.data)) { opts.body = opts.data; - } else if (typeof opts.data === 'object') { + } else if (typeof opts.data === "object") { opts.body = JSON.stringify(opts.data); - opts.headers['Content-Type'] = 'application/json'; + opts.headers["Content-Type"] = "application/json"; } else { opts.body = opts.data; } } opts.validateStatus = opts.validateStatus || this.validateStatus; - opts.responseType = opts.responseType || 'json'; - if (!opts.headers['Accept'] && opts.responseType === 'json') { - opts.headers['Accept'] = 'application/json'; + opts.responseType = opts.responseType || "json"; + if (!opts.headers["Accept"] && opts.responseType === "json") { + opts.headers["Accept"] = "application/json"; } - opts.method = opts.method || 'GET'; + opts.method = opts.method || "GET"; const proxy = loadProxy(); if (proxy) { @@ -229,7 +231,7 @@ export class Gaxios { * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) * @param params key value pars to encode */ - private paramsSerializer(params: {[index: string]: string | number}) { + private paramsSerializer(params: { [index: string]: string | number }) { return qs.stringify(params); } @@ -253,8 +255,8 @@ export class Gaxios { // XMLHttpRequestLike request: { - responseURL: res.url, - }, + responseURL: res.url + } }; } } diff --git a/src/index.ts b/src/index.ts index 9d20638c..17702ec7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,17 +11,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {GaxiosOptions} from './common'; -import {Gaxios} from './gaxios'; +import { GaxiosOptions } from "./common"; +import { Gaxios } from "./gaxios"; export { GaxiosError, GaxiosPromise, GaxiosResponse, Headers, - RetryConfig, -} from './common'; -export {Gaxios, GaxiosOptions}; + RetryConfig +} from "./common"; +export { Gaxios, GaxiosOptions }; /** * The default instance used when the `request` method is directly diff --git a/src/retry.ts b/src/retry.ts index 178d4d53..53516cdf 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -11,23 +11,23 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {GaxiosError} from './common'; +import { GaxiosError } from "./common"; export async function getRetryConfig(err: GaxiosError) { let config = getConfig(err); if (!err || !err.config || (!config && !err.config.retry)) { - return {shouldRetry: false}; + return { shouldRetry: false }; } config = config || {}; config.currentRetryAttempt = config.currentRetryAttempt || 0; config.retry = config.retry === undefined || config.retry === null ? 3 : config.retry; config.httpMethodsToRetry = config.httpMethodsToRetry || [ - 'GET', - 'HEAD', - 'PUT', - 'OPTIONS', - 'DELETE', + "GET", + "HEAD", + "PUT", + "OPTIONS", + "DELETE" ]; config.noResponseRetries = config.noResponseRetries === undefined || config.noResponseRetries === null @@ -46,7 +46,7 @@ export async function getRetryConfig(err: GaxiosError) { // 5xx - Retry (Server errors) [100, 199], [429, 429], - [500, 599], + [500, 599] ]; config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; @@ -56,7 +56,7 @@ export async function getRetryConfig(err: GaxiosError) { // Determine if we should retry the request const shouldRetryFn = config.shouldRetry || shouldRetryRequest; if (!(await shouldRetryFn(err))) { - return {shouldRetry: false, config: err.config}; + return { shouldRetry: false, config: err.config }; } // Calculate time to wait with exponential backoff. @@ -78,7 +78,7 @@ export async function getRetryConfig(err: GaxiosError) { // Return the promise in which recalls Gaxios to retry the request await backoff; - return {shouldRetry: true, config: err.config}; + return { shouldRetry: true, config: err.config }; } /** @@ -90,7 +90,7 @@ function shouldRetryRequest(err: GaxiosError) { // node-fetch raises an AbortError if signaled: // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal - if (err.name === 'AbortError') { + if (err.name === "AbortError") { return false; } diff --git a/system-test/fixtures/sample/src/index.ts b/system-test/fixtures/sample/src/index.ts index ffc92c41..c31302bd 100644 --- a/system-test/fixtures/sample/src/index.ts +++ b/system-test/fixtures/sample/src/index.ts @@ -1,7 +1,7 @@ -import {request} from 'gaxios'; +import { request } from "gaxios"; async function main() { await request({ - url: 'https://www.googleapis.com/discovery/v1/apis/' + url: "https://www.googleapis.com/discovery/v1/apis/" }); } main(); diff --git a/system-test/fixtures/sample/webpack.config.js b/system-test/fixtures/sample/webpack.config.js index 4806fd2c..b07930fa 100644 --- a/system-test/fixtures/sample/webpack.config.js +++ b/system-test/fixtures/sample/webpack.config.js @@ -14,38 +14,38 @@ // Use `npm run webpack` to produce Webpack bundle for this library. -const path = require('path'); +const path = require("path"); module.exports = { - entry: './src/index.ts', + entry: "./src/index.ts", resolve: { - extensions: ['.ts', '.js', '.json'], + extensions: [".ts", ".js", ".json"], alias: { - '../../package.json': path.resolve(__dirname, 'package.json') + "../../package.json": path.resolve(__dirname, "package.json") } }, output: { - filename: 'bundle.min.js', - path: path.resolve(__dirname, 'dist') + filename: "bundle.min.js", + path: path.resolve(__dirname, "dist") }, node: { - child_process: 'empty', - fs: 'empty', - crypto: 'empty' + child_process: "empty", + fs: "empty", + crypto: "empty" }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader' + use: "null-loader" }, { test: /\.ts$/, - use: 'ts-loader', + use: "ts-loader", exclude: /node_modules/ } ] }, - mode: 'production', + mode: "production", plugins: [] }; diff --git a/system-test/test.install.ts b/system-test/test.install.ts index e3ee1b0d..f95de779 100644 --- a/system-test/test.install.ts +++ b/system-test/test.install.ts @@ -12,52 +12,54 @@ // See the License for the specific language governing permissions and // limitations under the License. -import assert from 'assert'; -import execa from 'execa'; -import fs from 'fs'; -import mv from 'mv'; -import {ncp} from 'ncp'; -import path from 'path'; -import tmp from 'tmp'; -import {promisify} from 'util'; +import assert from "assert"; +import execa from "execa"; +import fs from "fs"; +import mv from "mv"; +import { ncp } from "ncp"; +import path from "path"; +import tmp from "tmp"; +import { promisify } from "util"; +import { describe, it, before, after } from "mocha"; const keep = false; const mvp = (promisify(mv) as {}) as (...args: string[]) => Promise; const ncpp = promisify(ncp); -const stagingDir = tmp.dirSync({keep, unsafeCleanup: true}); +const stagingDir = tmp.dirSync({ keep, unsafeCleanup: true }); const stagingPath = stagingDir.name; -const pkg = require('../../package.json'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const pkg = require("../../package.json"); -describe('📦 pack and install', () => { +describe("📦 pack and install", () => { /** * Create a staging directory with temp fixtures used to test on a fresh * application. */ - before('pack and install', async () => { - await execa('npm', ['pack', '--unsafe-perm']); + before("pack and install", async () => { + await execa("npm", ["pack", "--unsafe-perm"]); const tarball = `${pkg.name}-${pkg.version}.tgz`; await mvp(tarball, `${stagingPath}/gaxios.tgz`); - await ncpp('system-test/fixtures/sample', `${stagingPath}/`); - await execa('npm', ['install', '--unsafe-perm'], { + await ncpp("system-test/fixtures/sample", `${stagingPath}/`); + await execa("npm", ["install", "--unsafe-perm"], { cwd: `${stagingPath}/`, - stdio: 'inherit', + stdio: "inherit" }); }); - it('should run the sample', async () => { - await execa('node', ['--throw-deprecation', 'build/src/index.js'], { + it("should run the sample", async () => { + await execa("node", ["--throw-deprecation", "build/src/index.js"], { cwd: `${stagingPath}/`, - stdio: 'inherit', + stdio: "inherit" }); }); - it('should be able to webpack the library', async () => { + it("should be able to webpack the library", async () => { // we expect npm install is executed in the before hook - await execa('npx', ['webpack'], { + await execa("npx", ["webpack"], { cwd: `${stagingPath}/`, - stdio: 'inherit', + stdio: "inherit" }); - const bundle = path.join(stagingPath, 'dist', 'bundle.min.js'); + const bundle = path.join(stagingPath, "dist", "bundle.min.js"); const stat = fs.statSync(bundle); assert(stat.size < 256 * 1024); }).timeout(20000); @@ -65,7 +67,7 @@ describe('📦 pack and install', () => { /** * CLEAN UP - remove the staging directory when done. */ - after('cleanup staging', () => { + after("cleanup staging", () => { if (!keep) { stagingDir.removeCallback(); } diff --git a/test/test.getch.ts b/test/test.getch.ts index aec070f9..ab5dafc1 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -11,23 +11,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -import assert from 'assert'; -import nock from 'nock'; -import sinon from 'sinon'; -import stream from 'stream'; -const assertRejects = require('assert-rejects'); -// tslint:disable-next-line variable-name -const HttpsProxyAgent = require('https-proxy-agent'); +import assert from "assert"; +import nock from "nock"; +import sinon from "sinon"; +import stream from "stream"; +import { describe, it, afterEach } from "mocha"; +import assertRejects = require("assert-rejects"); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const HttpsProxyAgent = require("https-proxy-agent"); import { Gaxios, GaxiosError, request, GaxiosOptions, - GaxiosResponse, -} from '../src'; -import qs from 'querystring'; -import fs from 'fs'; -import {Blob} from 'node-fetch'; + GaxiosResponse +} from "../src"; +import qs from "querystring"; +import fs from "fs"; +import { Blob } from "node-fetch"; nock.disableNetConnect(); @@ -37,123 +38,121 @@ afterEach(() => { nock.cleanAll(); }); -const url = 'https://example.com'; +const url = "https://example.com"; -describe('🦖 option validation', () => { - it('should throw an error if a url is not provided', () => { +describe("🦖 option validation", () => { + it("should throw an error if a url is not provided", () => { assertRejects(request({}), /URL is required/); }); }); -describe('🚙 error handling', () => { - it('should throw on non-2xx responses by default', async () => { +describe("🚙 error handling", () => { + it("should throw on non-2xx responses by default", async () => { const scope = nock(url) - .get('/') + .get("/") .reply(500); - await assertRejects(request({url}), (err: GaxiosError) => { + await assertRejects(request({ url }), (err: GaxiosError) => { scope.done(); - return err.code === '500'; + return err.code === "500"; }); }); }); -describe('🥁 configuration options', () => { - it('should use options passed into the constructor', async () => { +describe("🥁 configuration options", () => { + it("should use options passed into the constructor", async () => { const scope = nock(url) - .head('/') + .head("/") .reply(200); - const inst = new Gaxios({method: 'HEAD'}); - const res = await inst.request({url}); + const inst = new Gaxios({ method: "HEAD" }); + const res = await inst.request({ url }); scope.done(); - assert.strictEqual(res.config.method, 'HEAD'); + assert.strictEqual(res.config.method, "HEAD"); }); - it('should handle nested options passed into the constructor', async () => { + it("should handle nested options passed into the constructor", async () => { const scope = nock(url) - .get('/') + .get("/") .reply(200); - const inst = new Gaxios({headers: {apple: 'juice'}}); - const res = await inst.request({url, headers: {figgy: 'pudding'}}); + const inst = new Gaxios({ headers: { apple: "juice" } }); + const res = await inst.request({ url, headers: { figgy: "pudding" } }); scope.done(); - assert.strictEqual(res.config.headers!.apple, 'juice'); - assert.strictEqual(res.config.headers!.figgy, 'pudding'); + assert.strictEqual(res.config.headers!.apple, "juice"); + assert.strictEqual(res.config.headers!.figgy, "pudding"); }); - it('should allow setting a base url in the options', async () => { + it("should allow setting a base url in the options", async () => { const scope = nock(url) - .get('/v1/mango') + .get("/v1/mango") .reply(200, {}); - const inst = new Gaxios({baseURL: `${url}/v1`}); - const res = await inst.request({url: '/mango'}); + const inst = new Gaxios({ baseURL: `${url}/v1` }); + const res = await inst.request({ url: "/mango" }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it('should allow overriding valid status', async () => { + it("should allow overriding valid status", async () => { const scope = nock(url) - .get('/') + .get("/") .reply(304); - const res = await request({url, validateStatus: () => true}); + const res = await request({ url, validateStatus: () => true }); scope.done(); assert.strictEqual(res.status, 304); }); - it('should allow setting maxContentLength', async () => { - const body = {hello: '🌎'}; + it("should allow setting maxContentLength", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); const maxContentLength = 1; - await assertRejects(request({url, maxContentLength}), /over limit/); + await assertRejects(request({ url, maxContentLength }), /over limit/); scope.done(); }); - it('should support redirects by default', async () => { - const body = {hello: '🌎'}; + it("should support redirects by default", async () => { + const body = { hello: "🌎" }; const scopes = [ nock(url) - .get('/foo') + .get("/foo") .reply(200, body), nock(url) - .get('/') - .reply(302, undefined, {location: '/foo'}), + .get("/") + .reply(302, undefined, { location: "/foo" }) ]; - const res = await request({url}); + const res = await request({ url }); scopes.forEach(x => x.done()); assert.deepStrictEqual(res.data, body); assert.strictEqual(res.request.responseURL, `${url}/foo`); }); - it('should support disabling redirects', async () => { + it("should support disabling redirects", async () => { const scope = nock(url) - .get('/') - .reply(302, undefined, {location: '/foo'}); + .get("/") + .reply(302, undefined, { location: "/foo" }); const maxRedirects = 0; - await assertRejects(request({url, maxRedirects}), /maximum redirect/); + await assertRejects(request({ url, maxRedirects }), /maximum redirect/); scope.done(); }); - it('should allow overriding the adapter', async () => { + it("should allow overriding the adapter", async () => { const response: GaxiosResponse = { - data: {hello: '🌎'}, + data: { hello: "🌎" }, config: {}, status: 200, - statusText: 'OK', + statusText: "OK", headers: {}, request: { - responseURL: url, - }, + responseURL: url + } }; - const adapter = (options: GaxiosOptions) => { - return Promise.resolve(response); - }; - const res = await request({url, adapter}); + const adapter = () => Promise.resolve(response); + const res = await request({ url, adapter }); assert.strictEqual(response, res); }); - it('should encode URL parameters', async () => { - const path = '/?james=kirk&montgomery=scott'; - const opts = {url: `${url}${path}`}; + it("should encode URL parameters", async () => { + const path = "/?james=kirk&montgomery=scott"; + const opts = { url: `${url}${path}` }; const scope = nock(url) .get(path) .reply(200, {}); @@ -163,9 +162,9 @@ describe('🥁 configuration options', () => { scope.done(); }); - it('should encode parameters from the params option', async () => { - const opts = {url, params: {james: 'kirk', montgomery: 'scott'}}; - const path = '/?james=kirk&montgomery=scott'; + it("should encode parameters from the params option", async () => { + const opts = { url, params: { james: "kirk", montgomery: "scott" } }; + const path = "/?james=kirk&montgomery=scott"; const scope = nock(url) .get(path) .reply(200, {}); @@ -175,12 +174,12 @@ describe('🥁 configuration options', () => { scope.done(); }); - it('should merge URL parameters with the params option', async () => { + it("should merge URL parameters with the params option", async () => { const opts = { url: `${url}/?james=beckwith&montgomery=scott`, - params: {james: 'kirk'}, + params: { james: "kirk" } }; - const path = '/?james=kirk&montgomery=scott'; + const path = "/?james=kirk&montgomery=scott"; const scope = nock(url) .get(path) .reply(200, {}); @@ -190,16 +189,16 @@ describe('🥁 configuration options', () => { scope.done(); }); - it('should allow overriding the param serializer', async () => { - const qs = '?oh=HAI'; - const params = {james: 'kirk'}; + it("should allow overriding the param serializer", async () => { + const qs = "?oh=HAI"; + const params = { james: "kirk" }; const opts: GaxiosOptions = { url, params, paramsSerializer: ps => { assert.strictEqual(JSON.stringify(params), JSON.stringify(ps)); - return '?oh=HAI'; - }, + return "?oh=HAI"; + } }; const scope = nock(url) .get(`/${qs}`) @@ -210,125 +209,126 @@ describe('🥁 configuration options', () => { scope.done(); }); - it('should return json by default', async () => { - const body = {hello: '🌎'}; + it("should return json by default", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); - const res = await request({url}); + const res = await request({ url }); scope.done(); assert.deepStrictEqual(body, res.data); }); - it('should send an application/json header by default', async () => { + it("should send an application/json header by default", async () => { const scope = nock(url) - .matchHeader('accept', 'application/json') - .get('/') + .matchHeader("accept", "application/json") + .get("/") .reply(200, {}); - const res = await request({url}); + const res = await request({ url }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it('should use an https proxy if asked nicely', async () => { - sandbox.stub(process, 'env').value({https_proxy: 'https://fake.proxy'}); - const body = {hello: '🌎'}; + it("should use an https proxy if asked nicely", async () => { + sandbox.stub(process, "env").value({ https_proxy: "https://fake.proxy" }); + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); - const res = await request({url}); + const res = await request({ url }); scope.done(); assert.deepStrictEqual(res.data, body); assert.ok(res.config.agent instanceof HttpsProxyAgent); }); - it('should load the proxy from the cache', async () => { - sandbox.stub(process, 'env').value({HTTPS_PROXY: 'https://fake.proxy'}); - const body = {hello: '🌎'}; + it("should load the proxy from the cache", async () => { + sandbox.stub(process, "env").value({ HTTPS_PROXY: "https://fake.proxy" }); + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .twice() .reply(200, body); - const res1 = await request({url}); + const res1 = await request({ url }); const agent = res1.config.agent; - const res2 = await request({url}); + const res2 = await request({ url }); assert.strictEqual(agent, res2.config.agent); scope.done(); }); - it('should include the request data in the response config', async () => { - const body = {hello: '🌎'}; + it("should include the request data in the response config", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .post('/', body) + .post("/", body) .reply(200); - const res = await request({url, method: 'POST', data: body}); + const res = await request({ url, method: "POST", data: body }); scope.done(); assert.deepStrictEqual(res.config.data, body); }); }); -describe('🎏 data handling', () => { - it('should accpet a ReadableStream as request data', async () => { - const body = fs.createReadStream('package.json'); - const contents = require('../../package.json'); +describe("🎏 data handling", () => { + it("should accpet a ReadableStream as request data", async () => { + const body = fs.createReadStream("package.json"); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const contents = require("../../package.json"); const scope = nock(url) - .post('/', contents) + .post("/", contents) .reply(200, {}); - const res = await request({url, method: 'POST', data: body}); + const res = await request({ url, method: "POST", data: body }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it('should accept a string in the request data', async () => { - const body = {hello: '🌎'}; + it("should accept a string in the request data", async () => { + const body = { hello: "🌎" }; const encoded = qs.stringify(body); const scope = nock(url) - .matchHeader('content-type', 'application/x-www-form-urlencoded') - .post('/', encoded) + .matchHeader("content-type", "application/x-www-form-urlencoded") + .post("/", encoded) .reply(200, {}); const res = await request({ url, - method: 'POST', + method: "POST", data: encoded, - headers: {'content-type': 'application/x-www-form-urlencoded'}, + headers: { "content-type": "application/x-www-form-urlencoded" } }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it('should set content-type for object request', async () => { - const body = {hello: '🌎'}; + it("should set content-type for object request", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .matchHeader('content-type', 'application/json') - .post('/', JSON.stringify(body)) + .matchHeader("content-type", "application/json") + .post("/", JSON.stringify(body)) .reply(200, {}); const res = await request({ url, - method: 'POST', - data: body, + method: "POST", + data: body }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it('should return stream if asked nicely', async () => { - const body = {hello: '🌎'}; + it("should return stream if asked nicely", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); - const res = await request({url, responseType: 'stream'}); + const res = await request({ url, responseType: "stream" }); scope.done(); assert(res.data instanceof stream.Readable); }); - it('should return an ArrayBuffer if asked nicely', async () => { - const body = {hello: '🌎'}; + it("should return an ArrayBuffer if asked nicely", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); const res = await request({ url, - responseType: 'arraybuffer', + responseType: "arraybuffer" }); scope.done(); assert(res.data instanceof ArrayBuffer); @@ -338,50 +338,50 @@ describe('🎏 data handling', () => { ); }); - it('should return a blob if asked nicely', async () => { - const body = {hello: '🌎'}; + it("should return a blob if asked nicely", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); - const res = await request({url, responseType: 'blob'}); + const res = await request({ url, responseType: "blob" }); scope.done(); assert.ok(res.data); }); - it('should return text if asked nicely', async () => { - const body = 'hello 🌎'; + it("should return text if asked nicely", async () => { + const body = "hello 🌎"; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); - const res = await request({url, responseType: 'text'}); + const res = await request({ url, responseType: "text" }); scope.done(); assert.strictEqual(res.data, body); }); - it('should return status text', async () => { - const body = {hello: '🌎'}; + it("should return status text", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); - const res = await request({url}); + const res = await request({ url }); scope.done(); assert.ok(res.data); - assert.strictEqual(res.statusText, 'OK'); + assert.strictEqual(res.statusText, "OK"); }); }); -describe('🍂 defaults & instances', () => { - it('should allow creating a new instance', () => { +describe("🍂 defaults & instances", () => { + it("should allow creating a new instance", () => { const requestInstance = new Gaxios(); - assert.strictEqual(typeof requestInstance.request, 'function'); + assert.strictEqual(typeof requestInstance.request, "function"); }); - it('should allow passing empty options', async () => { - const body = {hello: '🌎'}; + it("should allow passing empty options", async () => { + const body = { hello: "🌎" }; const scope = nock(url) - .get('/') + .get("/") .reply(200, body); - const gax = new Gaxios({url}); + const gax = new Gaxios({ url }); const res = await gax.request(); scope.done(); assert.deepStrictEqual(res.data, body); diff --git a/test/test.index.ts b/test/test.index.ts index 36d2760b..b8154528 100644 --- a/test/test.index.ts +++ b/test/test.index.ts @@ -11,12 +11,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -import assert from 'assert'; +import assert from "assert"; +import { describe, it } from "mocha"; +import * as main from "../src/index"; -import * as main from '../src/index'; - -describe('📝 main exports', () => { - it('should export all the types', () => { +describe("📝 main exports", () => { + it("should export all the types", () => { assert(main.Gaxios); assert(main.GaxiosError); }); diff --git a/test/test.retry.ts b/test/test.retry.ts index 15d8ffac..c5a46987 100644 --- a/test/test.retry.ts +++ b/test/test.retry.ts @@ -11,16 +11,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {AbortController} from 'abort-controller'; -import assert from 'assert'; -import nock from 'nock'; -import {Gaxios, GaxiosError, GaxiosOptions, request} from '../src'; - -const assertRejects = require('assert-rejects'); +import { AbortController } from "abort-controller"; +import assert from "assert"; +import nock from "nock"; +import { describe, it, afterEach } from "mocha"; +import { Gaxios, GaxiosError, GaxiosOptions, request } from "../src"; +import assertRejects = require("assert-rejects"); nock.disableNetConnect(); -const url = 'https://example.com'; +const url = "https://example.com"; function getConfig(err: Error) { const e = err as GaxiosError; @@ -34,29 +34,29 @@ afterEach(() => { nock.cleanAll(); }); -describe('🛸 retry & exponential backoff', () => { - it('should provide an expected set of defaults', async () => { +describe("🛸 retry & exponential backoff", () => { + it("should provide an expected set of defaults", async () => { const scope = nock(url) - .get('/') + .get("/") .times(4) .reply(500); - await assertRejects(request({url, retry: true}), (e: Error) => { + await assertRejects(request({ url, retry: true }), (e: Error) => { scope.done(); const config = getConfig(e); if (!config) { - assert.fail('no config available'); + assert.fail("no config available"); } assert.strictEqual(config!.currentRetryAttempt, 3); assert.strictEqual(config!.retry, 3); assert.strictEqual(config!.noResponseRetries, 2); - const expectedMethods = ['GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE']; + const expectedMethods = ["GET", "HEAD", "PUT", "OPTIONS", "DELETE"]; for (const method of config!.httpMethodsToRetry!) { assert(expectedMethods.indexOf(method) > -1); } const expectedStatusCodes = [ [100, 199], [429, 429], - [500, 599], + [500, 599] ]; const statusCodesToRetry = config!.statusCodesToRetry!; for (let i = 0; i < statusCodesToRetry.length; i++) { @@ -69,30 +69,30 @@ describe('🛸 retry & exponential backoff', () => { }); }); - it('should retry on 500 on the main export', async () => { - const body = {buttered: '🥖'}; + it("should retry on 500 on the main export", async () => { + const body = { buttered: "🥖" }; const scopes = [ nock(url) - .get('/') + .get("/") .reply(500), nock(url) - .get('/') - .reply(200, body), + .get("/") + .reply(200, body) ]; const res = await request({ url, - retry: true, + retry: true }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); - it('should not retry on a post', async () => { + it("should not retry on a post", async () => { const scope = nock(url) - .post('/') + .post("/") .reply(500); await assertRejects( - request({url, method: 'POST', retry: true}), + request({ url, method: "POST", retry: true }), (e: Error) => { const config = getConfig(e); return config!.currentRetryAttempt === 0; @@ -101,90 +101,90 @@ describe('🛸 retry & exponential backoff', () => { scope.done(); }); - it('should not retry if user aborted request', async () => { + it("should not retry if user aborted request", async () => { const ac = new AbortController(); const config: GaxiosOptions = { - method: 'GET', - url: 'https://google.com', + method: "GET", + url: "https://google.com", signal: ac.signal, - retryConfig: {retry: 10, noResponseRetries: 10}, + retryConfig: { retry: 10, noResponseRetries: 10 } }; const req = request(config); ac.abort(); try { await req; - throw Error('unreachable'); + throw Error("unreachable"); } catch (err) { assert(err.config); assert.strictEqual(err.config.retryConfig.currentRetryAttempt, 0); } }); - it('should retry at least the configured number of times', async () => { - const body = {dippy: '🥚'}; + it("should retry at least the configured number of times", async () => { + const body = { dippy: "🥚" }; const scopes = [ nock(url) - .get('/') + .get("/") .times(3) .reply(500), nock(url) - .get('/') - .reply(200, body), + .get("/") + .reply(200, body) ]; - const cfg = {url, retryConfig: {retry: 4}}; + const cfg = { url, retryConfig: { retry: 4 } }; const res = await request(cfg); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); - it('should not retry more than configured', async () => { + it("should not retry more than configured", async () => { const scope = nock(url) - .get('/') + .get("/") .twice() .reply(500); - const cfg = {url, retryConfig: {retry: 1}}; + const cfg = { url, retryConfig: { retry: 1 } }; await assertRejects(request(cfg), (e: Error) => { return getConfig(e)!.currentRetryAttempt === 1; }); scope.done(); }); - it('should not retry on 4xx errors', async () => { + it("should not retry on 4xx errors", async () => { const scope = nock(url) - .get('/') + .get("/") .reply(404); - await assertRejects(request({url, retry: true}), (e: Error) => { + await assertRejects(request({ url, retry: true }), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; }); scope.done(); }); - it('should retain the baseUrl on retry', async () => { - const body = {pumpkin: '🥧'}; - const url = '/path'; - const baseUrl = 'http://example.com'; + it("should retain the baseUrl on retry", async () => { + const body = { pumpkin: "🥧" }; + const url = "/path"; + const baseUrl = "http://example.com"; const scope = nock(baseUrl) .get(url) .reply(500) .get(url) .reply(200, body); const gaxios = new Gaxios({ - baseUrl, + baseUrl }); const res = await gaxios.request({ url, - retry: true, + retry: true }); assert.deepStrictEqual(res.data, body); scope.done(); }); - it('should not retry if retries set to 0', async () => { + it("should not retry if retries set to 0", async () => { const scope = nock(url) - .get('/') + .get("/") .reply(500); - const cfg = {url, retryConfig: {retry: 0}}; + const cfg = { url, retryConfig: { retry: 0 } }; await assertRejects(request(cfg), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; @@ -192,15 +192,15 @@ describe('🛸 retry & exponential backoff', () => { scope.done(); }); - it('should notify on retry attempts', async () => { - const body = {buttered: '🥖'}; + it("should notify on retry attempts", async () => { + const body = { buttered: "🥖" }; const scopes = [ nock(url) - .get('/') + .get("/") .reply(500), nock(url) - .get('/') - .reply(200, body), + .get("/") + .reply(200, body) ]; let flipped = false; const config: GaxiosOptions = { @@ -210,23 +210,23 @@ describe('🛸 retry & exponential backoff', () => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; - }, - }, + } + } }; await request(config); assert.strictEqual(flipped, true); scopes.forEach(s => s.done()); }); - it('accepts async onRetryAttempt handler', async () => { - const body = {buttered: '🥖'}; + it("accepts async onRetryAttempt handler", async () => { + const body = { buttered: "🥖" }; const scopes = [ nock(url) - .get('/') + .get("/") .reply(500), nock(url) - .get('/') - .reply(200, body), + .get("/") + .reply(200, body) ]; let flipped = false; const config: GaxiosOptions = { @@ -236,25 +236,25 @@ describe('🛸 retry & exponential backoff', () => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; - }, - }, + } + } }; await request(config); assert.strictEqual(flipped, true); scopes.forEach(s => s.done()); }); - it('should support overriding the shouldRetry method', async () => { + it("should support overriding the shouldRetry method", async () => { const scope = nock(url) - .get('/') + .get("/") .reply(500); const config = { url, retryConfig: { shouldRetry: () => { return false; - }, - }, + } + } }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); @@ -263,17 +263,17 @@ describe('🛸 retry & exponential backoff', () => { scope.done(); }); - it('should support overriding the shouldRetry method with a promise', async () => { + it("should support overriding the shouldRetry method with a promise", async () => { const scope = nock(url) - .get('/') + .get("/") .reply(500); const config = { url, retryConfig: { shouldRetry: async () => { return false; - }, - }, + } + } }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); @@ -282,41 +282,41 @@ describe('🛸 retry & exponential backoff', () => { scope.done(); }); - it('should retry on ENOTFOUND', async () => { - const body = {spicy: '🌮'}; + it("should retry on ENOTFOUND", async () => { + const body = { spicy: "🌮" }; const scopes = [ nock(url) - .get('/') - .replyWithError({code: 'ENOTFOUND'}), + .get("/") + .replyWithError({ code: "ENOTFOUND" }), nock(url) - .get('/') - .reply(200, body), + .get("/") + .reply(200, body) ]; - const res = await request({url, retry: true}); + const res = await request({ url, retry: true }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); - it('should retry on ETIMEDOUT', async () => { - const body = {sizzling: '🥓'}; + it("should retry on ETIMEDOUT", async () => { + const body = { sizzling: "🥓" }; const scopes = [ nock(url) - .get('/') - .replyWithError({code: 'ETIMEDOUT'}), + .get("/") + .replyWithError({ code: "ETIMEDOUT" }), nock(url) - .get('/') - .reply(200, body), + .get("/") + .reply(200, body) ]; - const res = await request({url, retry: true}); + const res = await request({ url, retry: true }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); - it('should allow configuring noResponseRetries', async () => { + it("should allow configuring noResponseRetries", async () => { const scope = nock(url) - .get('/') - .replyWithError({code: 'ETIMEDOUT'}); - const config = {url, retryConfig: {noResponseRetries: 0}}; + .get("/") + .replyWithError({ code: "ETIMEDOUT" }); + const config = { url, retryConfig: { noResponseRetries: 0 } }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; diff --git a/tslint.json b/tslint.json deleted file mode 100644 index 27872a13..00000000 --- a/tslint.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "gts/tslint.json", - "linterOptions": { - "exclude": [ - "**/*.json" - ] - } -} diff --git a/webpack-tests.config.js b/webpack-tests.config.js index 8642393d..6e3764df 100644 --- a/webpack-tests.config.js +++ b/webpack-tests.config.js @@ -14,33 +14,33 @@ // Use `npm run webpack` to produce Webpack bundle for this library. -const path = require('path'); +const path = require("path"); module.exports = { resolve: { - extensions: ['.ts', '.js', '.json'], + extensions: [".ts", ".js", ".json"], alias: { - '../../package.json': path.resolve(__dirname, 'package.json') + "../../package.json": path.resolve(__dirname, "package.json") } }, node: { - child_process: 'empty', - fs: 'empty', - crypto: 'empty' + child_process: "empty", + fs: "empty", + crypto: "empty" }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader' + use: "null-loader" }, { test: /\.ts$/, - use: 'ts-loader', + use: "ts-loader", exclude: /node_modules/ } ] }, - mode: 'production', + mode: "production", plugins: [] }; diff --git a/webpack.config.js b/webpack.config.js index 20812cd3..b27fc461 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -14,39 +14,39 @@ // Use `npm run webpack` to produce Webpack bundle for this library. -const path = require('path'); +const path = require("path"); module.exports = { - entry: './src/index.ts', + entry: "./src/index.ts", resolve: { - extensions: ['.ts', '.js', '.json'], + extensions: [".ts", ".js", ".json"], alias: { - '../../package.json': path.resolve(__dirname, 'package.json') + "../../package.json": path.resolve(__dirname, "package.json") } }, output: { - library: 'gaxios', - filename: 'gaxios.min.js', - path: path.resolve(__dirname, 'dist') + library: "gaxios", + filename: "gaxios.min.js", + path: path.resolve(__dirname, "dist") }, node: { - child_process: 'empty', - fs: 'empty', - crypto: 'empty' + child_process: "empty", + fs: "empty", + crypto: "empty" }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader' + use: "null-loader" }, { test: /\.ts$/, - use: 'ts-loader', + use: "ts-loader", exclude: /node_modules/ } ] }, - mode: 'production', + mode: "production", plugins: [] }; From 0237b7f0c6fff8fa324f6305531fea083499b78c Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Sun, 2 Feb 2020 21:53:18 -0800 Subject: [PATCH 2/9] quooootes --- .prettierrc.js | 3 + .prettierrc.json | 3 - browser-test/browser-test-runner.ts | 28 +- browser-test/test.browser.ts | 18 +- karma.conf.js | 42 +-- prettier.config.js | 2 +- samples/quickstart.js | 4 +- samples/test/test.samples.js | 14 +- src/common.ts | 26 +- src/gaxios.ts | 52 ++-- src/index.ts | 8 +- src/retry.ts | 16 +- system-test/fixtures/sample/src/index.ts | 4 +- system-test/fixtures/sample/webpack.config.js | 34 +-- system-test/test.install.ts | 48 ++-- test/test.getch.ts | 252 +++++++++--------- test/test.index.ts | 10 +- test/test.retry.ts | 162 +++++------ webpack-tests.config.js | 28 +- webpack.config.js | 36 +-- 20 files changed, 395 insertions(+), 395 deletions(-) create mode 100644 .prettierrc.js delete mode 100644 .prettierrc.json diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000..8ed6886c --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,3 @@ +module.exports = { + ...require("gts/.prettierrc.js"), +}; diff --git a/.prettierrc.json b/.prettierrc.json deleted file mode 100644 index 8803584c..00000000 --- a/.prettierrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "prettier": "./node_modules/gts/build/src/prettier.config.js" -} diff --git a/browser-test/browser-test-runner.ts b/browser-test/browser-test-runner.ts index 5d70380a..2ff0500e 100644 --- a/browser-test/browser-test-runner.ts +++ b/browser-test/browser-test-runner.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import execa from "execa"; -import express from "express"; -import http from "http"; +import execa from 'execa'; +import express from 'express'; +import http from 'http'; const port = 7172; @@ -35,32 +35,32 @@ async function listen( // tests. async function main() { const app = express(); - app.get("/path", (req: express.Request, res: express.Response) => { - if (req.header("origin")) { - res.set("Access-Control-Allow-Origin", req.header("origin")); + app.get('/path', (req: express.Request, res: express.Response) => { + if (req.header('origin')) { + res.set('Access-Control-Allow-Origin', req.header('origin')); } - res.send("response"); + res.send('response'); }); - app.get("/querystring", (req: express.Request, res: express.Response) => { - if (req.header("origin")) { - res.set("Access-Control-Allow-Origin", req.header("origin")); + app.get('/querystring', (req: express.Request, res: express.Response) => { + if (req.header('origin')) { + res.set('Access-Control-Allow-Origin', req.header('origin')); } const query = req.query.query; - res.send(query || ""); + res.send(query || ''); }); const server = await listen(app, port); console.log(`[http server] I'm listening on port ${port}! Starting karma.`); - const result = await execa("karma", ["start"], { stdio: "inherit" }); + const result = await execa('karma', ['start'], { stdio: 'inherit' }); server.close(); console.log( `[http server] Karma has finished! I'm no longer listening on port ${port}!` ); if (result.failed) { - throw new Error("Tests failed."); + throw new Error('Tests failed.'); } } main().catch(err => { - console.log("Error:", err); + console.log('Error:', err); }); diff --git a/browser-test/test.browser.ts b/browser-test/test.browser.ts index 35b18f94..3716608c 100644 --- a/browser-test/test.browser.ts +++ b/browser-test/test.browser.ts @@ -11,24 +11,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -import assert from "assert"; -import { describe, it } from "mocha"; -import { request } from "../src/index"; +import assert from 'assert'; +import { describe, it } from 'mocha'; +import { request } from '../src/index'; const port = 7172; // should match the port defined in `webserver.ts` -describe("💻 browser tests", () => { - it("should just work from browser", async () => { +describe('💻 browser tests', () => { + it('should just work from browser', async () => { const result = await request({ url: `http://localhost:${port}/path` }); assert.strictEqual(result.status, 200); - assert.strictEqual(result.data, "response"); + assert.strictEqual(result.data, 'response'); }); - it("should pass querystring parameters from browser", async () => { + it('should pass querystring parameters from browser', async () => { const result = await request({ url: `http://localhost:${port}/querystring`, - params: { query: "value" } + params: { query: 'value' }, }); assert.strictEqual(result.status, 200); - assert.strictEqual(result.data, "value"); + assert.strictEqual(result.data, 'value'); }); }); diff --git a/karma.conf.js b/karma.conf.js index 41b59030..086198a4 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -14,25 +14,25 @@ // Karma configuration // Use `npm run browser-test` to run browser tests with Karma. -const fs = require("fs"); -const isDocker = require("is-docker")(); +const fs = require('fs'); +const isDocker = require('is-docker')(); -const webpackConfig = require("./webpack-tests.config.js"); -process.env.CHROME_BIN = fs.existsSync("/usr/bin/chromium-browser") - ? "/usr/bin/chromium-browser" - : require("puppeteer").executablePath(); +const webpackConfig = require('./webpack-tests.config.js'); +process.env.CHROME_BIN = fs.existsSync('/usr/bin/chromium-browser') + ? '/usr/bin/chromium-browser' + : require('puppeteer').executablePath(); module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: "", + basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ["mocha"], + frameworks: ['mocha'], // list of files / patterns to load in the browser - files: ["./browser-test/test.*.ts"], + files: ['./browser-test/test.*.ts'], // list of files / patterns to exclude exclude: [], @@ -40,9 +40,9 @@ module.exports = function(config) { // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { - "./src/*.ts": ["coverage"], - "./src/**/*.ts": ["coverage"], - "./browser-test/*.ts": ["webpack", "sourcemap"] + './src/*.ts': ['coverage'], + './src/**/*.ts': ['coverage'], + './browser-test/*.ts': ['webpack', 'sourcemap'], }, webpack: webpackConfig, @@ -50,10 +50,10 @@ module.exports = function(config) { // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ["progress", "coverage", "remap-coverage"], + reporters: ['progress', 'coverage', 'remap-coverage'], - coverageReporter: { type: "in-memory" }, - remapCoverageReporter: { html: "./coverage" }, + coverageReporter: { type: 'in-memory' }, + remapCoverageReporter: { html: './coverage' }, // web server port port: 9876, @@ -70,14 +70,14 @@ module.exports = function(config) { // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ["ChromeCustom"], + browsers: ['ChromeCustom'], customLaunchers: { ChromeCustom: { - base: "ChromeHeadless", + base: 'ChromeHeadless', // We must disable the Chrome sandbox when running Chrome inside Docker (Chrome's sandbox needs // more permissions than Docker allows by default) - flags: isDocker ? ["--no-sandbox"] : [] - } + flags: isDocker ? ['--no-sandbox'] : [], + }, }, // Continuous Integration mode @@ -90,7 +90,7 @@ module.exports = function(config) { // set correct MIME type when serving .ts files (already compiled to JavaScript): mime: { - "text/javascript": ["ts"] - } + 'text/javascript': ['ts'], + }, }); }; diff --git a/prettier.config.js b/prettier.config.js index d305ebd0..a425d3f7 100644 --- a/prettier.config.js +++ b/prettier.config.js @@ -1,4 +1,4 @@ module.exports = { singleQuote: true, - trailingComma: "es5" + trailingComma: 'es5', }; diff --git a/samples/quickstart.js b/samples/quickstart.js index 46e3016a..c0500ffa 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -13,13 +13,13 @@ // limitations under the License. // [START gaxios_quickstart] -const { request } = require("gaxios"); +const { request } = require('gaxios'); /** * Perform a simple `GET` request to a JSON API. */ async function quickstart() { - const url = "https://www.googleapis.com/discovery/v1/apis/"; + const url = 'https://www.googleapis.com/discovery/v1/apis/'; const res = await request({ url }); console.log(`status: ${res.status}`); console.log(`data:`); diff --git a/samples/test/test.samples.js b/samples/test/test.samples.js index 8132f2db..dce71952 100644 --- a/samples/test/test.samples.js +++ b/samples/test/test.samples.js @@ -12,15 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -const { execSync } = require("child_process"); -const { assert } = require("chai"); -const { describe, it } = require("mocha"); +const { execSync } = require('child_process'); +const { assert } = require('chai'); +const { describe, it } = require('mocha'); -const exec = cmd => execSync(cmd, { encoding: "utf8" }); +const exec = cmd => execSync(cmd, { encoding: 'utf8' }); describe(__filename, () => { - it("should run the quickstart", () => { - const output = exec("node quickstart"); - assert.include(output, "status: 200"); + it('should run the quickstart', () => { + const output = exec('node quickstart'); + assert.include(output, 'status: 200'); }); }); diff --git a/src/common.ts b/src/common.ts index 780f4c9c..65ff1a99 100644 --- a/src/common.ts +++ b/src/common.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { AbortSignal } from "abort-controller"; -import { Agent } from "http"; -import { URL } from "url"; +import { AbortSignal } from 'abort-controller'; +import { Agent } from 'http'; +import { URL } from 'url'; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -64,15 +64,15 @@ export interface GaxiosOptions { baseUrl?: string; // deprecated baseURL?: string; method?: - | "GET" - | "HEAD" - | "POST" - | "DELETE" - | "PUT" - | "CONNECT" - | "OPTIONS" - | "TRACE" - | "PATCH"; + | 'GET' + | 'HEAD' + | 'POST' + | 'DELETE' + | 'PUT' + | 'CONNECT' + | 'OPTIONS' + | 'TRACE' + | 'PATCH'; headers?: Headers; data?: any; body?: any; @@ -89,7 +89,7 @@ export interface GaxiosOptions { paramsSerializer?: (params: { [index: string]: string | number }) => string; timeout?: number; onUploadProgress?: (progressEvent: any) => void; - responseType?: "arraybuffer" | "blob" | "json" | "text" | "stream"; + responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream'; agent?: Agent | ((parsedUrl: URL) => Agent); validateStatus?: (status: number) => boolean; retryConfig?: RetryConfig; diff --git a/src/gaxios.ts b/src/gaxios.ts index 8ab49427..be9bc7e6 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -11,21 +11,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -import extend from "extend"; -import { Agent } from "http"; -import nodeFetch, { Response as NodeFetchResponse } from "node-fetch"; -import qs from "querystring"; -import isStream from "is-stream"; -import url from "url"; +import extend from 'extend'; +import { Agent } from 'http'; +import nodeFetch, { Response as NodeFetchResponse } from 'node-fetch'; +import qs from 'querystring'; +import isStream from 'is-stream'; +import url from 'url'; import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse, - Headers -} from "./common"; -import { getRetryConfig } from "./retry"; + Headers, +} from './common'; +import { getRetryConfig } from './retry'; /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable node/no-unsupported-features/node-builtins */ @@ -34,7 +34,7 @@ const URL = hasURL() ? window.URL : url.URL; const fetch = hasFetch() ? window.fetch : nodeFetch; function hasWindow() { - return typeof window !== "undefined" && !!window; + return typeof window !== 'undefined' && !!window; } function hasURL() { @@ -56,7 +56,7 @@ function loadProxy() { process.env.HTTP_PROXY || process.env.http_proxy; if (proxy) { - HttpsProxyAgent = require("https-proxy-agent"); + HttpsProxyAgent = require('https-proxy-agent'); } return proxy; } @@ -129,9 +129,9 @@ export class Gaxios { res: Response | NodeFetchResponse ): Promise { switch (opts.responseType) { - case "stream": + case 'stream': return res.body; - case "json": { + case 'json': { let data = await res.text(); try { data = JSON.parse(data); @@ -140,9 +140,9 @@ export class Gaxios { } return data as {}; } - case "arraybuffer": + case 'arraybuffer': return res.arrayBuffer(); - case "blob": + case 'blob': return res.blob(); default: return res.text(); @@ -156,7 +156,7 @@ export class Gaxios { private validateOpts(options: GaxiosOptions): GaxiosOptions { const opts = extend(true, {}, this.defaults, options); if (!opts.url) { - throw new Error("URL is required."); + throw new Error('URL is required.'); } // baseUrl has been deprecated, remove in 2.0 @@ -179,11 +179,11 @@ export class Gaxios { opts.url = parsedUrl.href; - if (typeof options.maxContentLength === "number") { + if (typeof options.maxContentLength === 'number') { opts.size = options.maxContentLength; } - if (typeof options.maxRedirects === "number") { + if (typeof options.maxRedirects === 'number') { opts.follow = options.maxRedirects; } @@ -191,20 +191,20 @@ export class Gaxios { if (opts.data) { if (isStream.readable(opts.data)) { opts.body = opts.data; - } else if (typeof opts.data === "object") { + } else if (typeof opts.data === 'object') { opts.body = JSON.stringify(opts.data); - opts.headers["Content-Type"] = "application/json"; + opts.headers['Content-Type'] = 'application/json'; } else { opts.body = opts.data; } } opts.validateStatus = opts.validateStatus || this.validateStatus; - opts.responseType = opts.responseType || "json"; - if (!opts.headers["Accept"] && opts.responseType === "json") { - opts.headers["Accept"] = "application/json"; + opts.responseType = opts.responseType || 'json'; + if (!opts.headers['Accept'] && opts.responseType === 'json') { + opts.headers['Accept'] = 'application/json'; } - opts.method = opts.method || "GET"; + opts.method = opts.method || 'GET'; const proxy = loadProxy(); if (proxy) { @@ -255,8 +255,8 @@ export class Gaxios { // XMLHttpRequestLike request: { - responseURL: res.url - } + responseURL: res.url, + }, }; } } diff --git a/src/index.ts b/src/index.ts index 17702ec7..a355ef7a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,16 +11,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { GaxiosOptions } from "./common"; -import { Gaxios } from "./gaxios"; +import { GaxiosOptions } from './common'; +import { Gaxios } from './gaxios'; export { GaxiosError, GaxiosPromise, GaxiosResponse, Headers, - RetryConfig -} from "./common"; + RetryConfig, +} from './common'; export { Gaxios, GaxiosOptions }; /** diff --git a/src/retry.ts b/src/retry.ts index 53516cdf..7c8d961b 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { GaxiosError } from "./common"; +import { GaxiosError } from './common'; export async function getRetryConfig(err: GaxiosError) { let config = getConfig(err); @@ -23,11 +23,11 @@ export async function getRetryConfig(err: GaxiosError) { config.retry = config.retry === undefined || config.retry === null ? 3 : config.retry; config.httpMethodsToRetry = config.httpMethodsToRetry || [ - "GET", - "HEAD", - "PUT", - "OPTIONS", - "DELETE" + 'GET', + 'HEAD', + 'PUT', + 'OPTIONS', + 'DELETE', ]; config.noResponseRetries = config.noResponseRetries === undefined || config.noResponseRetries === null @@ -46,7 +46,7 @@ export async function getRetryConfig(err: GaxiosError) { // 5xx - Retry (Server errors) [100, 199], [429, 429], - [500, 599] + [500, 599], ]; config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; @@ -90,7 +90,7 @@ function shouldRetryRequest(err: GaxiosError) { // node-fetch raises an AbortError if signaled: // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal - if (err.name === "AbortError") { + if (err.name === 'AbortError') { return false; } diff --git a/system-test/fixtures/sample/src/index.ts b/system-test/fixtures/sample/src/index.ts index c31302bd..9e327e64 100644 --- a/system-test/fixtures/sample/src/index.ts +++ b/system-test/fixtures/sample/src/index.ts @@ -1,7 +1,7 @@ -import { request } from "gaxios"; +import { request } from 'gaxios'; async function main() { await request({ - url: "https://www.googleapis.com/discovery/v1/apis/" + url: 'https://www.googleapis.com/discovery/v1/apis/', }); } main(); diff --git a/system-test/fixtures/sample/webpack.config.js b/system-test/fixtures/sample/webpack.config.js index b07930fa..b3ced2ce 100644 --- a/system-test/fixtures/sample/webpack.config.js +++ b/system-test/fixtures/sample/webpack.config.js @@ -14,38 +14,38 @@ // Use `npm run webpack` to produce Webpack bundle for this library. -const path = require("path"); +const path = require('path'); module.exports = { - entry: "./src/index.ts", + entry: './src/index.ts', resolve: { - extensions: [".ts", ".js", ".json"], + extensions: ['.ts', '.js', '.json'], alias: { - "../../package.json": path.resolve(__dirname, "package.json") - } + '../../package.json': path.resolve(__dirname, 'package.json'), + }, }, output: { - filename: "bundle.min.js", - path: path.resolve(__dirname, "dist") + filename: 'bundle.min.js', + path: path.resolve(__dirname, 'dist'), }, node: { - child_process: "empty", - fs: "empty", - crypto: "empty" + child_process: 'empty', + fs: 'empty', + crypto: 'empty', }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: "null-loader" + use: 'null-loader', }, { test: /\.ts$/, - use: "ts-loader", - exclude: /node_modules/ - } - ] + use: 'ts-loader', + exclude: /node_modules/, + }, + ], }, - mode: "production", - plugins: [] + mode: 'production', + plugins: [], }; diff --git a/system-test/test.install.ts b/system-test/test.install.ts index f95de779..c67e6780 100644 --- a/system-test/test.install.ts +++ b/system-test/test.install.ts @@ -12,15 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -import assert from "assert"; -import execa from "execa"; -import fs from "fs"; -import mv from "mv"; -import { ncp } from "ncp"; -import path from "path"; -import tmp from "tmp"; -import { promisify } from "util"; -import { describe, it, before, after } from "mocha"; +import assert from 'assert'; +import execa from 'execa'; +import fs from 'fs'; +import mv from 'mv'; +import { ncp } from 'ncp'; +import path from 'path'; +import tmp from 'tmp'; +import { promisify } from 'util'; +import { describe, it, before, after } from 'mocha'; const keep = false; const mvp = (promisify(mv) as {}) as (...args: string[]) => Promise; @@ -28,38 +28,38 @@ const ncpp = promisify(ncp); const stagingDir = tmp.dirSync({ keep, unsafeCleanup: true }); const stagingPath = stagingDir.name; // eslint-disable-next-line @typescript-eslint/no-var-requires -const pkg = require("../../package.json"); +const pkg = require('../../package.json'); -describe("📦 pack and install", () => { +describe('📦 pack and install', () => { /** * Create a staging directory with temp fixtures used to test on a fresh * application. */ - before("pack and install", async () => { - await execa("npm", ["pack", "--unsafe-perm"]); + before('pack and install', async () => { + await execa('npm', ['pack', '--unsafe-perm']); const tarball = `${pkg.name}-${pkg.version}.tgz`; await mvp(tarball, `${stagingPath}/gaxios.tgz`); - await ncpp("system-test/fixtures/sample", `${stagingPath}/`); - await execa("npm", ["install", "--unsafe-perm"], { + await ncpp('system-test/fixtures/sample', `${stagingPath}/`); + await execa('npm', ['install', '--unsafe-perm'], { cwd: `${stagingPath}/`, - stdio: "inherit" + stdio: 'inherit', }); }); - it("should run the sample", async () => { - await execa("node", ["--throw-deprecation", "build/src/index.js"], { + it('should run the sample', async () => { + await execa('node', ['--throw-deprecation', 'build/src/index.js'], { cwd: `${stagingPath}/`, - stdio: "inherit" + stdio: 'inherit', }); }); - it("should be able to webpack the library", async () => { + it('should be able to webpack the library', async () => { // we expect npm install is executed in the before hook - await execa("npx", ["webpack"], { + await execa('npx', ['webpack'], { cwd: `${stagingPath}/`, - stdio: "inherit" + stdio: 'inherit', }); - const bundle = path.join(stagingPath, "dist", "bundle.min.js"); + const bundle = path.join(stagingPath, 'dist', 'bundle.min.js'); const stat = fs.statSync(bundle); assert(stat.size < 256 * 1024); }).timeout(20000); @@ -67,7 +67,7 @@ describe("📦 pack and install", () => { /** * CLEAN UP - remove the staging directory when done. */ - after("cleanup staging", () => { + after('cleanup staging', () => { if (!keep) { stagingDir.removeCallback(); } diff --git a/test/test.getch.ts b/test/test.getch.ts index ab5dafc1..8b20a486 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -11,24 +11,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -import assert from "assert"; -import nock from "nock"; -import sinon from "sinon"; -import stream from "stream"; -import { describe, it, afterEach } from "mocha"; -import assertRejects = require("assert-rejects"); +import assert from 'assert'; +import nock from 'nock'; +import sinon from 'sinon'; +import stream from 'stream'; +import { describe, it, afterEach } from 'mocha'; +import assertRejects = require('assert-rejects'); // eslint-disable-next-line @typescript-eslint/no-var-requires -const HttpsProxyAgent = require("https-proxy-agent"); +const HttpsProxyAgent = require('https-proxy-agent'); import { Gaxios, GaxiosError, request, GaxiosOptions, - GaxiosResponse -} from "../src"; -import qs from "querystring"; -import fs from "fs"; -import { Blob } from "node-fetch"; + GaxiosResponse, +} from '../src'; +import qs from 'querystring'; +import fs from 'fs'; +import { Blob } from 'node-fetch'; nock.disableNetConnect(); @@ -38,86 +38,86 @@ afterEach(() => { nock.cleanAll(); }); -const url = "https://example.com"; +const url = 'https://example.com'; -describe("🦖 option validation", () => { - it("should throw an error if a url is not provided", () => { +describe('🦖 option validation', () => { + it('should throw an error if a url is not provided', () => { assertRejects(request({}), /URL is required/); }); }); -describe("🚙 error handling", () => { - it("should throw on non-2xx responses by default", async () => { +describe('🚙 error handling', () => { + it('should throw on non-2xx responses by default', async () => { const scope = nock(url) - .get("/") + .get('/') .reply(500); await assertRejects(request({ url }), (err: GaxiosError) => { scope.done(); - return err.code === "500"; + return err.code === '500'; }); }); }); -describe("🥁 configuration options", () => { - it("should use options passed into the constructor", async () => { +describe('🥁 configuration options', () => { + it('should use options passed into the constructor', async () => { const scope = nock(url) - .head("/") + .head('/') .reply(200); - const inst = new Gaxios({ method: "HEAD" }); + const inst = new Gaxios({ method: 'HEAD' }); const res = await inst.request({ url }); scope.done(); - assert.strictEqual(res.config.method, "HEAD"); + assert.strictEqual(res.config.method, 'HEAD'); }); - it("should handle nested options passed into the constructor", async () => { + it('should handle nested options passed into the constructor', async () => { const scope = nock(url) - .get("/") + .get('/') .reply(200); - const inst = new Gaxios({ headers: { apple: "juice" } }); - const res = await inst.request({ url, headers: { figgy: "pudding" } }); + const inst = new Gaxios({ headers: { apple: 'juice' } }); + const res = await inst.request({ url, headers: { figgy: 'pudding' } }); scope.done(); - assert.strictEqual(res.config.headers!.apple, "juice"); - assert.strictEqual(res.config.headers!.figgy, "pudding"); + assert.strictEqual(res.config.headers!.apple, 'juice'); + assert.strictEqual(res.config.headers!.figgy, 'pudding'); }); - it("should allow setting a base url in the options", async () => { + it('should allow setting a base url in the options', async () => { const scope = nock(url) - .get("/v1/mango") + .get('/v1/mango') .reply(200, {}); const inst = new Gaxios({ baseURL: `${url}/v1` }); - const res = await inst.request({ url: "/mango" }); + const res = await inst.request({ url: '/mango' }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it("should allow overriding valid status", async () => { + it('should allow overriding valid status', async () => { const scope = nock(url) - .get("/") + .get('/') .reply(304); const res = await request({ url, validateStatus: () => true }); scope.done(); assert.strictEqual(res.status, 304); }); - it("should allow setting maxContentLength", async () => { - const body = { hello: "🌎" }; + it('should allow setting maxContentLength', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); const maxContentLength = 1; await assertRejects(request({ url, maxContentLength }), /over limit/); scope.done(); }); - it("should support redirects by default", async () => { - const body = { hello: "🌎" }; + it('should support redirects by default', async () => { + const body = { hello: '🌎' }; const scopes = [ nock(url) - .get("/foo") + .get('/foo') .reply(200, body), nock(url) - .get("/") - .reply(302, undefined, { location: "/foo" }) + .get('/') + .reply(302, undefined, { location: '/foo' }), ]; const res = await request({ url }); scopes.forEach(x => x.done()); @@ -125,33 +125,33 @@ describe("🥁 configuration options", () => { assert.strictEqual(res.request.responseURL, `${url}/foo`); }); - it("should support disabling redirects", async () => { + it('should support disabling redirects', async () => { const scope = nock(url) - .get("/") - .reply(302, undefined, { location: "/foo" }); + .get('/') + .reply(302, undefined, { location: '/foo' }); const maxRedirects = 0; await assertRejects(request({ url, maxRedirects }), /maximum redirect/); scope.done(); }); - it("should allow overriding the adapter", async () => { + it('should allow overriding the adapter', async () => { const response: GaxiosResponse = { - data: { hello: "🌎" }, + data: { hello: '🌎' }, config: {}, status: 200, - statusText: "OK", + statusText: 'OK', headers: {}, request: { - responseURL: url - } + responseURL: url, + }, }; const adapter = () => Promise.resolve(response); const res = await request({ url, adapter }); assert.strictEqual(response, res); }); - it("should encode URL parameters", async () => { - const path = "/?james=kirk&montgomery=scott"; + it('should encode URL parameters', async () => { + const path = '/?james=kirk&montgomery=scott'; const opts = { url: `${url}${path}` }; const scope = nock(url) .get(path) @@ -162,9 +162,9 @@ describe("🥁 configuration options", () => { scope.done(); }); - it("should encode parameters from the params option", async () => { - const opts = { url, params: { james: "kirk", montgomery: "scott" } }; - const path = "/?james=kirk&montgomery=scott"; + it('should encode parameters from the params option', async () => { + const opts = { url, params: { james: 'kirk', montgomery: 'scott' } }; + const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) .get(path) .reply(200, {}); @@ -174,12 +174,12 @@ describe("🥁 configuration options", () => { scope.done(); }); - it("should merge URL parameters with the params option", async () => { + it('should merge URL parameters with the params option', async () => { const opts = { url: `${url}/?james=beckwith&montgomery=scott`, - params: { james: "kirk" } + params: { james: 'kirk' }, }; - const path = "/?james=kirk&montgomery=scott"; + const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) .get(path) .reply(200, {}); @@ -189,16 +189,16 @@ describe("🥁 configuration options", () => { scope.done(); }); - it("should allow overriding the param serializer", async () => { - const qs = "?oh=HAI"; - const params = { james: "kirk" }; + it('should allow overriding the param serializer', async () => { + const qs = '?oh=HAI'; + const params = { james: 'kirk' }; const opts: GaxiosOptions = { url, params, paramsSerializer: ps => { assert.strictEqual(JSON.stringify(params), JSON.stringify(ps)); - return "?oh=HAI"; - } + return '?oh=HAI'; + }, }; const scope = nock(url) .get(`/${qs}`) @@ -209,31 +209,31 @@ describe("🥁 configuration options", () => { scope.done(); }); - it("should return json by default", async () => { - const body = { hello: "🌎" }; + it('should return json by default', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); const res = await request({ url }); scope.done(); assert.deepStrictEqual(body, res.data); }); - it("should send an application/json header by default", async () => { + it('should send an application/json header by default', async () => { const scope = nock(url) - .matchHeader("accept", "application/json") - .get("/") + .matchHeader('accept', 'application/json') + .get('/') .reply(200, {}); const res = await request({ url }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it("should use an https proxy if asked nicely", async () => { - sandbox.stub(process, "env").value({ https_proxy: "https://fake.proxy" }); - const body = { hello: "🌎" }; + it('should use an https proxy if asked nicely', async () => { + sandbox.stub(process, 'env').value({ https_proxy: 'https://fake.proxy' }); + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); const res = await request({ url }); scope.done(); @@ -241,11 +241,11 @@ describe("🥁 configuration options", () => { assert.ok(res.config.agent instanceof HttpsProxyAgent); }); - it("should load the proxy from the cache", async () => { - sandbox.stub(process, "env").value({ HTTPS_PROXY: "https://fake.proxy" }); - const body = { hello: "🌎" }; + it('should load the proxy from the cache', async () => { + sandbox.stub(process, 'env').value({ HTTPS_PROXY: 'https://fake.proxy' }); + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .twice() .reply(200, body); const res1 = await request({ url }); @@ -255,80 +255,80 @@ describe("🥁 configuration options", () => { scope.done(); }); - it("should include the request data in the response config", async () => { - const body = { hello: "🌎" }; + it('should include the request data in the response config', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .post("/", body) + .post('/', body) .reply(200); - const res = await request({ url, method: "POST", data: body }); + const res = await request({ url, method: 'POST', data: body }); scope.done(); assert.deepStrictEqual(res.config.data, body); }); }); -describe("🎏 data handling", () => { - it("should accpet a ReadableStream as request data", async () => { - const body = fs.createReadStream("package.json"); +describe('🎏 data handling', () => { + it('should accpet a ReadableStream as request data', async () => { + const body = fs.createReadStream('package.json'); // eslint-disable-next-line @typescript-eslint/no-var-requires - const contents = require("../../package.json"); + const contents = require('../../package.json'); const scope = nock(url) - .post("/", contents) + .post('/', contents) .reply(200, {}); - const res = await request({ url, method: "POST", data: body }); + const res = await request({ url, method: 'POST', data: body }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it("should accept a string in the request data", async () => { - const body = { hello: "🌎" }; + it('should accept a string in the request data', async () => { + const body = { hello: '🌎' }; const encoded = qs.stringify(body); const scope = nock(url) - .matchHeader("content-type", "application/x-www-form-urlencoded") - .post("/", encoded) + .matchHeader('content-type', 'application/x-www-form-urlencoded') + .post('/', encoded) .reply(200, {}); const res = await request({ url, - method: "POST", + method: 'POST', data: encoded, - headers: { "content-type": "application/x-www-form-urlencoded" } + headers: { 'content-type': 'application/x-www-form-urlencoded' }, }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it("should set content-type for object request", async () => { - const body = { hello: "🌎" }; + it('should set content-type for object request', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .matchHeader("content-type", "application/json") - .post("/", JSON.stringify(body)) + .matchHeader('content-type', 'application/json') + .post('/', JSON.stringify(body)) .reply(200, {}); const res = await request({ url, - method: "POST", - data: body + method: 'POST', + data: body, }); scope.done(); assert.deepStrictEqual(res.data, {}); }); - it("should return stream if asked nicely", async () => { - const body = { hello: "🌎" }; + it('should return stream if asked nicely', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); - const res = await request({ url, responseType: "stream" }); + const res = await request({ url, responseType: 'stream' }); scope.done(); assert(res.data instanceof stream.Readable); }); - it("should return an ArrayBuffer if asked nicely", async () => { - const body = { hello: "🌎" }; + it('should return an ArrayBuffer if asked nicely', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); const res = await request({ url, - responseType: "arraybuffer" + responseType: 'arraybuffer', }); scope.done(); assert(res.data instanceof ArrayBuffer); @@ -338,48 +338,48 @@ describe("🎏 data handling", () => { ); }); - it("should return a blob if asked nicely", async () => { - const body = { hello: "🌎" }; + it('should return a blob if asked nicely', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); - const res = await request({ url, responseType: "blob" }); + const res = await request({ url, responseType: 'blob' }); scope.done(); assert.ok(res.data); }); - it("should return text if asked nicely", async () => { - const body = "hello 🌎"; + it('should return text if asked nicely', async () => { + const body = 'hello 🌎'; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); - const res = await request({ url, responseType: "text" }); + const res = await request({ url, responseType: 'text' }); scope.done(); assert.strictEqual(res.data, body); }); - it("should return status text", async () => { - const body = { hello: "🌎" }; + it('should return status text', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); const res = await request({ url }); scope.done(); assert.ok(res.data); - assert.strictEqual(res.statusText, "OK"); + assert.strictEqual(res.statusText, 'OK'); }); }); -describe("🍂 defaults & instances", () => { - it("should allow creating a new instance", () => { +describe('🍂 defaults & instances', () => { + it('should allow creating a new instance', () => { const requestInstance = new Gaxios(); - assert.strictEqual(typeof requestInstance.request, "function"); + assert.strictEqual(typeof requestInstance.request, 'function'); }); - it("should allow passing empty options", async () => { - const body = { hello: "🌎" }; + it('should allow passing empty options', async () => { + const body = { hello: '🌎' }; const scope = nock(url) - .get("/") + .get('/') .reply(200, body); const gax = new Gaxios({ url }); const res = await gax.request(); diff --git a/test/test.index.ts b/test/test.index.ts index b8154528..5be639d7 100644 --- a/test/test.index.ts +++ b/test/test.index.ts @@ -11,12 +11,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -import assert from "assert"; -import { describe, it } from "mocha"; -import * as main from "../src/index"; +import assert from 'assert'; +import { describe, it } from 'mocha'; +import * as main from '../src/index'; -describe("📝 main exports", () => { - it("should export all the types", () => { +describe('📝 main exports', () => { + it('should export all the types', () => { assert(main.Gaxios); assert(main.GaxiosError); }); diff --git a/test/test.retry.ts b/test/test.retry.ts index c5a46987..edb8cf09 100644 --- a/test/test.retry.ts +++ b/test/test.retry.ts @@ -11,16 +11,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { AbortController } from "abort-controller"; -import assert from "assert"; -import nock from "nock"; -import { describe, it, afterEach } from "mocha"; -import { Gaxios, GaxiosError, GaxiosOptions, request } from "../src"; -import assertRejects = require("assert-rejects"); +import { AbortController } from 'abort-controller'; +import assert from 'assert'; +import nock from 'nock'; +import { describe, it, afterEach } from 'mocha'; +import { Gaxios, GaxiosError, GaxiosOptions, request } from '../src'; +import assertRejects = require('assert-rejects'); nock.disableNetConnect(); -const url = "https://example.com"; +const url = 'https://example.com'; function getConfig(err: Error) { const e = err as GaxiosError; @@ -34,29 +34,29 @@ afterEach(() => { nock.cleanAll(); }); -describe("🛸 retry & exponential backoff", () => { - it("should provide an expected set of defaults", async () => { +describe('🛸 retry & exponential backoff', () => { + it('should provide an expected set of defaults', async () => { const scope = nock(url) - .get("/") + .get('/') .times(4) .reply(500); await assertRejects(request({ url, retry: true }), (e: Error) => { scope.done(); const config = getConfig(e); if (!config) { - assert.fail("no config available"); + assert.fail('no config available'); } assert.strictEqual(config!.currentRetryAttempt, 3); assert.strictEqual(config!.retry, 3); assert.strictEqual(config!.noResponseRetries, 2); - const expectedMethods = ["GET", "HEAD", "PUT", "OPTIONS", "DELETE"]; + const expectedMethods = ['GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE']; for (const method of config!.httpMethodsToRetry!) { assert(expectedMethods.indexOf(method) > -1); } const expectedStatusCodes = [ [100, 199], [429, 429], - [500, 599] + [500, 599], ]; const statusCodesToRetry = config!.statusCodesToRetry!; for (let i = 0; i < statusCodesToRetry.length; i++) { @@ -69,30 +69,30 @@ describe("🛸 retry & exponential backoff", () => { }); }); - it("should retry on 500 on the main export", async () => { - const body = { buttered: "🥖" }; + it('should retry on 500 on the main export', async () => { + const body = { buttered: '🥖' }; const scopes = [ nock(url) - .get("/") + .get('/') .reply(500), nock(url) - .get("/") - .reply(200, body) + .get('/') + .reply(200, body), ]; const res = await request({ url, - retry: true + retry: true, }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); - it("should not retry on a post", async () => { + it('should not retry on a post', async () => { const scope = nock(url) - .post("/") + .post('/') .reply(500); await assertRejects( - request({ url, method: "POST", retry: true }), + request({ url, method: 'POST', retry: true }), (e: Error) => { const config = getConfig(e); return config!.currentRetryAttempt === 0; @@ -101,35 +101,35 @@ describe("🛸 retry & exponential backoff", () => { scope.done(); }); - it("should not retry if user aborted request", async () => { + it('should not retry if user aborted request', async () => { const ac = new AbortController(); const config: GaxiosOptions = { - method: "GET", - url: "https://google.com", + method: 'GET', + url: 'https://google.com', signal: ac.signal, - retryConfig: { retry: 10, noResponseRetries: 10 } + retryConfig: { retry: 10, noResponseRetries: 10 }, }; const req = request(config); ac.abort(); try { await req; - throw Error("unreachable"); + throw Error('unreachable'); } catch (err) { assert(err.config); assert.strictEqual(err.config.retryConfig.currentRetryAttempt, 0); } }); - it("should retry at least the configured number of times", async () => { - const body = { dippy: "🥚" }; + it('should retry at least the configured number of times', async () => { + const body = { dippy: '🥚' }; const scopes = [ nock(url) - .get("/") + .get('/') .times(3) .reply(500), nock(url) - .get("/") - .reply(200, body) + .get('/') + .reply(200, body), ]; const cfg = { url, retryConfig: { retry: 4 } }; const res = await request(cfg); @@ -137,9 +137,9 @@ describe("🛸 retry & exponential backoff", () => { scopes.forEach(s => s.done()); }); - it("should not retry more than configured", async () => { + it('should not retry more than configured', async () => { const scope = nock(url) - .get("/") + .get('/') .twice() .reply(500); const cfg = { url, retryConfig: { retry: 1 } }; @@ -149,9 +149,9 @@ describe("🛸 retry & exponential backoff", () => { scope.done(); }); - it("should not retry on 4xx errors", async () => { + it('should not retry on 4xx errors', async () => { const scope = nock(url) - .get("/") + .get('/') .reply(404); await assertRejects(request({ url, retry: true }), (e: Error) => { const cfg = getConfig(e); @@ -160,29 +160,29 @@ describe("🛸 retry & exponential backoff", () => { scope.done(); }); - it("should retain the baseUrl on retry", async () => { - const body = { pumpkin: "🥧" }; - const url = "/path"; - const baseUrl = "http://example.com"; + it('should retain the baseUrl on retry', async () => { + const body = { pumpkin: '🥧' }; + const url = '/path'; + const baseUrl = 'http://example.com'; const scope = nock(baseUrl) .get(url) .reply(500) .get(url) .reply(200, body); const gaxios = new Gaxios({ - baseUrl + baseUrl, }); const res = await gaxios.request({ url, - retry: true + retry: true, }); assert.deepStrictEqual(res.data, body); scope.done(); }); - it("should not retry if retries set to 0", async () => { + it('should not retry if retries set to 0', async () => { const scope = nock(url) - .get("/") + .get('/') .reply(500); const cfg = { url, retryConfig: { retry: 0 } }; await assertRejects(request(cfg), (e: Error) => { @@ -192,15 +192,15 @@ describe("🛸 retry & exponential backoff", () => { scope.done(); }); - it("should notify on retry attempts", async () => { - const body = { buttered: "🥖" }; + it('should notify on retry attempts', async () => { + const body = { buttered: '🥖' }; const scopes = [ nock(url) - .get("/") + .get('/') .reply(500), nock(url) - .get("/") - .reply(200, body) + .get('/') + .reply(200, body), ]; let flipped = false; const config: GaxiosOptions = { @@ -210,23 +210,23 @@ describe("🛸 retry & exponential backoff", () => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; - } - } + }, + }, }; await request(config); assert.strictEqual(flipped, true); scopes.forEach(s => s.done()); }); - it("accepts async onRetryAttempt handler", async () => { - const body = { buttered: "🥖" }; + it('accepts async onRetryAttempt handler', async () => { + const body = { buttered: '🥖' }; const scopes = [ nock(url) - .get("/") + .get('/') .reply(500), nock(url) - .get("/") - .reply(200, body) + .get('/') + .reply(200, body), ]; let flipped = false; const config: GaxiosOptions = { @@ -236,25 +236,25 @@ describe("🛸 retry & exponential backoff", () => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; - } - } + }, + }, }; await request(config); assert.strictEqual(flipped, true); scopes.forEach(s => s.done()); }); - it("should support overriding the shouldRetry method", async () => { + it('should support overriding the shouldRetry method', async () => { const scope = nock(url) - .get("/") + .get('/') .reply(500); const config = { url, retryConfig: { shouldRetry: () => { return false; - } - } + }, + }, }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); @@ -263,17 +263,17 @@ describe("🛸 retry & exponential backoff", () => { scope.done(); }); - it("should support overriding the shouldRetry method with a promise", async () => { + it('should support overriding the shouldRetry method with a promise', async () => { const scope = nock(url) - .get("/") + .get('/') .reply(500); const config = { url, retryConfig: { shouldRetry: async () => { return false; - } - } + }, + }, }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); @@ -282,40 +282,40 @@ describe("🛸 retry & exponential backoff", () => { scope.done(); }); - it("should retry on ENOTFOUND", async () => { - const body = { spicy: "🌮" }; + it('should retry on ENOTFOUND', async () => { + const body = { spicy: '🌮' }; const scopes = [ nock(url) - .get("/") - .replyWithError({ code: "ENOTFOUND" }), + .get('/') + .replyWithError({ code: 'ENOTFOUND' }), nock(url) - .get("/") - .reply(200, body) + .get('/') + .reply(200, body), ]; const res = await request({ url, retry: true }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); - it("should retry on ETIMEDOUT", async () => { - const body = { sizzling: "🥓" }; + it('should retry on ETIMEDOUT', async () => { + const body = { sizzling: '🥓' }; const scopes = [ nock(url) - .get("/") - .replyWithError({ code: "ETIMEDOUT" }), + .get('/') + .replyWithError({ code: 'ETIMEDOUT' }), nock(url) - .get("/") - .reply(200, body) + .get('/') + .reply(200, body), ]; const res = await request({ url, retry: true }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); - it("should allow configuring noResponseRetries", async () => { + it('should allow configuring noResponseRetries', async () => { const scope = nock(url) - .get("/") - .replyWithError({ code: "ETIMEDOUT" }); + .get('/') + .replyWithError({ code: 'ETIMEDOUT' }); const config = { url, retryConfig: { noResponseRetries: 0 } }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); diff --git a/webpack-tests.config.js b/webpack-tests.config.js index 6e3764df..d903551d 100644 --- a/webpack-tests.config.js +++ b/webpack-tests.config.js @@ -14,33 +14,33 @@ // Use `npm run webpack` to produce Webpack bundle for this library. -const path = require("path"); +const path = require('path'); module.exports = { resolve: { - extensions: [".ts", ".js", ".json"], + extensions: ['.ts', '.js', '.json'], alias: { - "../../package.json": path.resolve(__dirname, "package.json") - } + '../../package.json': path.resolve(__dirname, 'package.json'), + }, }, node: { - child_process: "empty", - fs: "empty", - crypto: "empty" + child_process: 'empty', + fs: 'empty', + crypto: 'empty', }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: "null-loader" + use: 'null-loader', }, { test: /\.ts$/, - use: "ts-loader", - exclude: /node_modules/ - } - ] + use: 'ts-loader', + exclude: /node_modules/, + }, + ], }, - mode: "production", - plugins: [] + mode: 'production', + plugins: [], }; diff --git a/webpack.config.js b/webpack.config.js index b27fc461..012df506 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -14,39 +14,39 @@ // Use `npm run webpack` to produce Webpack bundle for this library. -const path = require("path"); +const path = require('path'); module.exports = { - entry: "./src/index.ts", + entry: './src/index.ts', resolve: { - extensions: [".ts", ".js", ".json"], + extensions: ['.ts', '.js', '.json'], alias: { - "../../package.json": path.resolve(__dirname, "package.json") - } + '../../package.json': path.resolve(__dirname, 'package.json'), + }, }, output: { - library: "gaxios", - filename: "gaxios.min.js", - path: path.resolve(__dirname, "dist") + library: 'gaxios', + filename: 'gaxios.min.js', + path: path.resolve(__dirname, 'dist'), }, node: { - child_process: "empty", - fs: "empty", - crypto: "empty" + child_process: 'empty', + fs: 'empty', + crypto: 'empty', }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: "null-loader" + use: 'null-loader', }, { test: /\.ts$/, - use: "ts-loader", - exclude: /node_modules/ - } - ] + use: 'ts-loader', + exclude: /node_modules/, + }, + ], }, - mode: "production", - plugins: [] + mode: 'production', + plugins: [], }; From dfba6bbdb8a6919a6e55e93feca7bcbda46bdbf5 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Sun, 2 Feb 2020 22:08:28 -0800 Subject: [PATCH 3/9] spacey --- browser-test/browser-test-runner.ts | 4 +- browser-test/test.browser.ts | 10 +-- karma.conf.js | 4 +- samples/quickstart.js | 4 +- samples/test/test.samples.js | 8 +- src/common.ts | 8 +- src/gaxios.ts | 10 +-- src/index.ts | 6 +- src/retry.ts | 8 +- system-test/fixtures/sample/src/index.ts | 2 +- system-test/test.install.ts | 8 +- test/test.getch.ts | 98 ++++++++++++------------ test/test.index.ts | 2 +- test/test.retry.ts | 46 +++++------ 14 files changed, 109 insertions(+), 109 deletions(-) diff --git a/browser-test/browser-test-runner.ts b/browser-test/browser-test-runner.ts index 2ff0500e..ce267d40 100644 --- a/browser-test/browser-test-runner.ts +++ b/browser-test/browser-test-runner.ts @@ -1,4 +1,4 @@ -// Copyright 2019, Google, LLC. +// Copyright 2019 Google, LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -51,7 +51,7 @@ async function main() { const server = await listen(app, port); console.log(`[http server] I'm listening on port ${port}! Starting karma.`); - const result = await execa('karma', ['start'], { stdio: 'inherit' }); + const result = await execa('karma', ['start'], {stdio: 'inherit'}); server.close(); console.log( `[http server] Karma has finished! I'm no longer listening on port ${port}!` diff --git a/browser-test/test.browser.ts b/browser-test/test.browser.ts index 3716608c..bdf86863 100644 --- a/browser-test/test.browser.ts +++ b/browser-test/test.browser.ts @@ -1,4 +1,4 @@ -// Copyright 2019, Google, LLC. +// Copyright 2019 Google, LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -12,13 +12,13 @@ // limitations under the License. import assert from 'assert'; -import { describe, it } from 'mocha'; -import { request } from '../src/index'; +import {describe, it} from 'mocha'; +import {request} from '../src/index'; const port = 7172; // should match the port defined in `webserver.ts` describe('💻 browser tests', () => { it('should just work from browser', async () => { - const result = await request({ url: `http://localhost:${port}/path` }); + const result = await request({url: `http://localhost:${port}/path`}); assert.strictEqual(result.status, 200); assert.strictEqual(result.data, 'response'); }); @@ -26,7 +26,7 @@ describe('💻 browser tests', () => { it('should pass querystring parameters from browser', async () => { const result = await request({ url: `http://localhost:${port}/querystring`, - params: { query: 'value' }, + params: {query: 'value'}, }); assert.strictEqual(result.status, 200); assert.strictEqual(result.data, 'value'); diff --git a/karma.conf.js b/karma.conf.js index 086198a4..eff7d047 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -52,8 +52,8 @@ module.exports = function(config) { // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage', 'remap-coverage'], - coverageReporter: { type: 'in-memory' }, - remapCoverageReporter: { html: './coverage' }, + coverageReporter: {type: 'in-memory'}, + remapCoverageReporter: {html: './coverage'}, // web server port port: 9876, diff --git a/samples/quickstart.js b/samples/quickstart.js index c0500ffa..d41e2f94 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -13,14 +13,14 @@ // limitations under the License. // [START gaxios_quickstart] -const { request } = require('gaxios'); +const {request} = require('gaxios'); /** * Perform a simple `GET` request to a JSON API. */ async function quickstart() { const url = 'https://www.googleapis.com/discovery/v1/apis/'; - const res = await request({ url }); + const res = await request({url}); console.log(`status: ${res.status}`); console.log(`data:`); console.log(res.data); diff --git a/samples/test/test.samples.js b/samples/test/test.samples.js index dce71952..dcb97a1a 100644 --- a/samples/test/test.samples.js +++ b/samples/test/test.samples.js @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -const { execSync } = require('child_process'); -const { assert } = require('chai'); -const { describe, it } = require('mocha'); +const {execSync} = require('child_process'); +const {assert} = require('chai'); +const {describe, it} = require('mocha'); -const exec = cmd => execSync(cmd, { encoding: 'utf8' }); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); describe(__filename, () => { it('should run the quickstart', () => { diff --git a/src/common.ts b/src/common.ts index 65ff1a99..324974ab 100644 --- a/src/common.ts +++ b/src/common.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { AbortSignal } from 'abort-controller'; -import { Agent } from 'http'; -import { URL } from 'url'; +import {AbortSignal} from 'abort-controller'; +import {Agent} from 'http'; +import {URL} from 'url'; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -86,7 +86,7 @@ export interface GaxiosOptions { maxRedirects?: number; follow?: number; params?: any; - paramsSerializer?: (params: { [index: string]: string | number }) => string; + paramsSerializer?: (params: {[index: string]: string | number}) => string; timeout?: number; onUploadProgress?: (progressEvent: any) => void; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream'; diff --git a/src/gaxios.ts b/src/gaxios.ts index be9bc7e6..55b038ff 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -12,8 +12,8 @@ // limitations under the License. import extend from 'extend'; -import { Agent } from 'http'; -import nodeFetch, { Response as NodeFetchResponse } from 'node-fetch'; +import {Agent} from 'http'; +import nodeFetch, {Response as NodeFetchResponse} from 'node-fetch'; import qs from 'querystring'; import isStream from 'is-stream'; import url from 'url'; @@ -25,7 +25,7 @@ import { GaxiosResponse, Headers, } from './common'; -import { getRetryConfig } from './retry'; +import {getRetryConfig} from './retry'; /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable node/no-unsupported-features/node-builtins */ @@ -115,7 +115,7 @@ export class Gaxios { } catch (e) { const err = e as GaxiosError; err.config = opts; - const { shouldRetry, config } = await getRetryConfig(e); + const {shouldRetry, config} = await getRetryConfig(e); if (shouldRetry && config) { err.config.retryConfig!.currentRetryAttempt = config.retryConfig!.currentRetryAttempt; return this._request(err.config); @@ -231,7 +231,7 @@ export class Gaxios { * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) * @param params key value pars to encode */ - private paramsSerializer(params: { [index: string]: string | number }) { + private paramsSerializer(params: {[index: string]: string | number}) { return qs.stringify(params); } diff --git a/src/index.ts b/src/index.ts index a355ef7a..9d20638c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { GaxiosOptions } from './common'; -import { Gaxios } from './gaxios'; +import {GaxiosOptions} from './common'; +import {Gaxios} from './gaxios'; export { GaxiosError, @@ -21,7 +21,7 @@ export { Headers, RetryConfig, } from './common'; -export { Gaxios, GaxiosOptions }; +export {Gaxios, GaxiosOptions}; /** * The default instance used when the `request` method is directly diff --git a/src/retry.ts b/src/retry.ts index 7c8d961b..178d4d53 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -11,12 +11,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { GaxiosError } from './common'; +import {GaxiosError} from './common'; export async function getRetryConfig(err: GaxiosError) { let config = getConfig(err); if (!err || !err.config || (!config && !err.config.retry)) { - return { shouldRetry: false }; + return {shouldRetry: false}; } config = config || {}; config.currentRetryAttempt = config.currentRetryAttempt || 0; @@ -56,7 +56,7 @@ export async function getRetryConfig(err: GaxiosError) { // Determine if we should retry the request const shouldRetryFn = config.shouldRetry || shouldRetryRequest; if (!(await shouldRetryFn(err))) { - return { shouldRetry: false, config: err.config }; + return {shouldRetry: false, config: err.config}; } // Calculate time to wait with exponential backoff. @@ -78,7 +78,7 @@ export async function getRetryConfig(err: GaxiosError) { // Return the promise in which recalls Gaxios to retry the request await backoff; - return { shouldRetry: true, config: err.config }; + return {shouldRetry: true, config: err.config}; } /** diff --git a/system-test/fixtures/sample/src/index.ts b/system-test/fixtures/sample/src/index.ts index 9e327e64..0166d2a3 100644 --- a/system-test/fixtures/sample/src/index.ts +++ b/system-test/fixtures/sample/src/index.ts @@ -1,4 +1,4 @@ -import { request } from 'gaxios'; +import {request} from 'gaxios'; async function main() { await request({ url: 'https://www.googleapis.com/discovery/v1/apis/', diff --git a/system-test/test.install.ts b/system-test/test.install.ts index c67e6780..6c54733d 100644 --- a/system-test/test.install.ts +++ b/system-test/test.install.ts @@ -16,16 +16,16 @@ import assert from 'assert'; import execa from 'execa'; import fs from 'fs'; import mv from 'mv'; -import { ncp } from 'ncp'; +import {ncp} from 'ncp'; import path from 'path'; import tmp from 'tmp'; -import { promisify } from 'util'; -import { describe, it, before, after } from 'mocha'; +import {promisify} from 'util'; +import {describe, it, before, after} from 'mocha'; const keep = false; const mvp = (promisify(mv) as {}) as (...args: string[]) => Promise; const ncpp = promisify(ncp); -const stagingDir = tmp.dirSync({ keep, unsafeCleanup: true }); +const stagingDir = tmp.dirSync({keep, unsafeCleanup: true}); const stagingPath = stagingDir.name; // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../../package.json'); diff --git a/test/test.getch.ts b/test/test.getch.ts index 8b20a486..8ce0b338 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -15,7 +15,7 @@ import assert from 'assert'; import nock from 'nock'; import sinon from 'sinon'; import stream from 'stream'; -import { describe, it, afterEach } from 'mocha'; +import {describe, it, afterEach} from 'mocha'; import assertRejects = require('assert-rejects'); // eslint-disable-next-line @typescript-eslint/no-var-requires const HttpsProxyAgent = require('https-proxy-agent'); @@ -28,7 +28,7 @@ import { } from '../src'; import qs from 'querystring'; import fs from 'fs'; -import { Blob } from 'node-fetch'; +import {Blob} from 'node-fetch'; nock.disableNetConnect(); @@ -51,7 +51,7 @@ describe('🚙 error handling', () => { const scope = nock(url) .get('/') .reply(500); - await assertRejects(request({ url }), (err: GaxiosError) => { + await assertRejects(request({url}), (err: GaxiosError) => { scope.done(); return err.code === '500'; }); @@ -63,8 +63,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .head('/') .reply(200); - const inst = new Gaxios({ method: 'HEAD' }); - const res = await inst.request({ url }); + const inst = new Gaxios({method: 'HEAD'}); + const res = await inst.request({url}); scope.done(); assert.strictEqual(res.config.method, 'HEAD'); }); @@ -73,8 +73,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/') .reply(200); - const inst = new Gaxios({ headers: { apple: 'juice' } }); - const res = await inst.request({ url, headers: { figgy: 'pudding' } }); + const inst = new Gaxios({headers: {apple: 'juice'}}); + const res = await inst.request({url, headers: {figgy: 'pudding'}}); scope.done(); assert.strictEqual(res.config.headers!.apple, 'juice'); assert.strictEqual(res.config.headers!.figgy, 'pudding'); @@ -84,8 +84,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/v1/mango') .reply(200, {}); - const inst = new Gaxios({ baseURL: `${url}/v1` }); - const res = await inst.request({ url: '/mango' }); + const inst = new Gaxios({baseURL: `${url}/v1`}); + const res = await inst.request({url: '/mango'}); scope.done(); assert.deepStrictEqual(res.data, {}); }); @@ -94,32 +94,32 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/') .reply(304); - const res = await request({ url, validateStatus: () => true }); + const res = await request({url, validateStatus: () => true}); scope.done(); assert.strictEqual(res.status, 304); }); it('should allow setting maxContentLength', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); const maxContentLength = 1; - await assertRejects(request({ url, maxContentLength }), /over limit/); + await assertRejects(request({url, maxContentLength}), /over limit/); scope.done(); }); it('should support redirects by default', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scopes = [ nock(url) .get('/foo') .reply(200, body), nock(url) .get('/') - .reply(302, undefined, { location: '/foo' }), + .reply(302, undefined, {location: '/foo'}), ]; - const res = await request({ url }); + const res = await request({url}); scopes.forEach(x => x.done()); assert.deepStrictEqual(res.data, body); assert.strictEqual(res.request.responseURL, `${url}/foo`); @@ -128,15 +128,15 @@ describe('🥁 configuration options', () => { it('should support disabling redirects', async () => { const scope = nock(url) .get('/') - .reply(302, undefined, { location: '/foo' }); + .reply(302, undefined, {location: '/foo'}); const maxRedirects = 0; - await assertRejects(request({ url, maxRedirects }), /maximum redirect/); + await assertRejects(request({url, maxRedirects}), /maximum redirect/); scope.done(); }); it('should allow overriding the adapter', async () => { const response: GaxiosResponse = { - data: { hello: '🌎' }, + data: {hello: '🌎'}, config: {}, status: 200, statusText: 'OK', @@ -146,13 +146,13 @@ describe('🥁 configuration options', () => { }, }; const adapter = () => Promise.resolve(response); - const res = await request({ url, adapter }); + const res = await request({url, adapter}); assert.strictEqual(response, res); }); it('should encode URL parameters', async () => { const path = '/?james=kirk&montgomery=scott'; - const opts = { url: `${url}${path}` }; + const opts = {url: `${url}${path}`}; const scope = nock(url) .get(path) .reply(200, {}); @@ -163,7 +163,7 @@ describe('🥁 configuration options', () => { }); it('should encode parameters from the params option', async () => { - const opts = { url, params: { james: 'kirk', montgomery: 'scott' } }; + const opts = {url, params: {james: 'kirk', montgomery: 'scott'}}; const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) .get(path) @@ -177,7 +177,7 @@ describe('🥁 configuration options', () => { it('should merge URL parameters with the params option', async () => { const opts = { url: `${url}/?james=beckwith&montgomery=scott`, - params: { james: 'kirk' }, + params: {james: 'kirk'}, }; const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) @@ -191,7 +191,7 @@ describe('🥁 configuration options', () => { it('should allow overriding the param serializer', async () => { const qs = '?oh=HAI'; - const params = { james: 'kirk' }; + const params = {james: 'kirk'}; const opts: GaxiosOptions = { url, params, @@ -210,11 +210,11 @@ describe('🥁 configuration options', () => { }); it('should return json by default', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url }); + const res = await request({url}); scope.done(); assert.deepStrictEqual(body, res.data); }); @@ -224,43 +224,43 @@ describe('🥁 configuration options', () => { .matchHeader('accept', 'application/json') .get('/') .reply(200, {}); - const res = await request({ url }); + const res = await request({url}); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should use an https proxy if asked nicely', async () => { - sandbox.stub(process, 'env').value({ https_proxy: 'https://fake.proxy' }); - const body = { hello: '🌎' }; + sandbox.stub(process, 'env').value({https_proxy: 'https://fake.proxy'}); + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url }); + const res = await request({url}); scope.done(); assert.deepStrictEqual(res.data, body); assert.ok(res.config.agent instanceof HttpsProxyAgent); }); it('should load the proxy from the cache', async () => { - sandbox.stub(process, 'env').value({ HTTPS_PROXY: 'https://fake.proxy' }); - const body = { hello: '🌎' }; + sandbox.stub(process, 'env').value({HTTPS_PROXY: 'https://fake.proxy'}); + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .twice() .reply(200, body); - const res1 = await request({ url }); + const res1 = await request({url}); const agent = res1.config.agent; - const res2 = await request({ url }); + const res2 = await request({url}); assert.strictEqual(agent, res2.config.agent); scope.done(); }); it('should include the request data in the response config', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .post('/', body) .reply(200); - const res = await request({ url, method: 'POST', data: body }); + const res = await request({url, method: 'POST', data: body}); scope.done(); assert.deepStrictEqual(res.config.data, body); }); @@ -274,13 +274,13 @@ describe('🎏 data handling', () => { const scope = nock(url) .post('/', contents) .reply(200, {}); - const res = await request({ url, method: 'POST', data: body }); + const res = await request({url, method: 'POST', data: body}); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should accept a string in the request data', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const encoded = qs.stringify(body); const scope = nock(url) .matchHeader('content-type', 'application/x-www-form-urlencoded') @@ -290,14 +290,14 @@ describe('🎏 data handling', () => { url, method: 'POST', data: encoded, - headers: { 'content-type': 'application/x-www-form-urlencoded' }, + headers: {'content-type': 'application/x-www-form-urlencoded'}, }); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should set content-type for object request', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .matchHeader('content-type', 'application/json') .post('/', JSON.stringify(body)) @@ -312,17 +312,17 @@ describe('🎏 data handling', () => { }); it('should return stream if asked nicely', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url, responseType: 'stream' }); + const res = await request({url, responseType: 'stream'}); scope.done(); assert(res.data instanceof stream.Readable); }); it('should return an ArrayBuffer if asked nicely', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); @@ -339,11 +339,11 @@ describe('🎏 data handling', () => { }); it('should return a blob if asked nicely', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url, responseType: 'blob' }); + const res = await request({url, responseType: 'blob'}); scope.done(); assert.ok(res.data); }); @@ -353,17 +353,17 @@ describe('🎏 data handling', () => { const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url, responseType: 'text' }); + const res = await request({url, responseType: 'text'}); scope.done(); assert.strictEqual(res.data, body); }); it('should return status text', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url }); + const res = await request({url}); scope.done(); assert.ok(res.data); assert.strictEqual(res.statusText, 'OK'); @@ -377,11 +377,11 @@ describe('🍂 defaults & instances', () => { }); it('should allow passing empty options', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const gax = new Gaxios({ url }); + const gax = new Gaxios({url}); const res = await gax.request(); scope.done(); assert.deepStrictEqual(res.data, body); diff --git a/test/test.index.ts b/test/test.index.ts index 5be639d7..ac22903f 100644 --- a/test/test.index.ts +++ b/test/test.index.ts @@ -12,7 +12,7 @@ // limitations under the License. import assert from 'assert'; -import { describe, it } from 'mocha'; +import {describe, it} from 'mocha'; import * as main from '../src/index'; describe('📝 main exports', () => { diff --git a/test/test.retry.ts b/test/test.retry.ts index edb8cf09..88f61ed1 100644 --- a/test/test.retry.ts +++ b/test/test.retry.ts @@ -11,11 +11,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { AbortController } from 'abort-controller'; +import {AbortController} from 'abort-controller'; import assert from 'assert'; import nock from 'nock'; -import { describe, it, afterEach } from 'mocha'; -import { Gaxios, GaxiosError, GaxiosOptions, request } from '../src'; +import {describe, it, afterEach} from 'mocha'; +import {Gaxios, GaxiosError, GaxiosOptions, request} from '../src'; import assertRejects = require('assert-rejects'); nock.disableNetConnect(); @@ -40,7 +40,7 @@ describe('🛸 retry & exponential backoff', () => { .get('/') .times(4) .reply(500); - await assertRejects(request({ url, retry: true }), (e: Error) => { + await assertRejects(request({url, retry: true}), (e: Error) => { scope.done(); const config = getConfig(e); if (!config) { @@ -70,7 +70,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry on 500 on the main export', async () => { - const body = { buttered: '🥖' }; + const body = {buttered: '🥖'}; const scopes = [ nock(url) .get('/') @@ -92,7 +92,7 @@ describe('🛸 retry & exponential backoff', () => { .post('/') .reply(500); await assertRejects( - request({ url, method: 'POST', retry: true }), + request({url, method: 'POST', retry: true}), (e: Error) => { const config = getConfig(e); return config!.currentRetryAttempt === 0; @@ -107,7 +107,7 @@ describe('🛸 retry & exponential backoff', () => { method: 'GET', url: 'https://google.com', signal: ac.signal, - retryConfig: { retry: 10, noResponseRetries: 10 }, + retryConfig: {retry: 10, noResponseRetries: 10}, }; const req = request(config); ac.abort(); @@ -121,7 +121,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry at least the configured number of times', async () => { - const body = { dippy: '🥚' }; + const body = {dippy: '🥚'}; const scopes = [ nock(url) .get('/') @@ -131,7 +131,7 @@ describe('🛸 retry & exponential backoff', () => { .get('/') .reply(200, body), ]; - const cfg = { url, retryConfig: { retry: 4 } }; + const cfg = {url, retryConfig: {retry: 4}}; const res = await request(cfg); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); @@ -142,7 +142,7 @@ describe('🛸 retry & exponential backoff', () => { .get('/') .twice() .reply(500); - const cfg = { url, retryConfig: { retry: 1 } }; + const cfg = {url, retryConfig: {retry: 1}}; await assertRejects(request(cfg), (e: Error) => { return getConfig(e)!.currentRetryAttempt === 1; }); @@ -153,7 +153,7 @@ describe('🛸 retry & exponential backoff', () => { const scope = nock(url) .get('/') .reply(404); - await assertRejects(request({ url, retry: true }), (e: Error) => { + await assertRejects(request({url, retry: true}), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; }); @@ -161,7 +161,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retain the baseUrl on retry', async () => { - const body = { pumpkin: '🥧' }; + const body = {pumpkin: '🥧'}; const url = '/path'; const baseUrl = 'http://example.com'; const scope = nock(baseUrl) @@ -184,7 +184,7 @@ describe('🛸 retry & exponential backoff', () => { const scope = nock(url) .get('/') .reply(500); - const cfg = { url, retryConfig: { retry: 0 } }; + const cfg = {url, retryConfig: {retry: 0}}; await assertRejects(request(cfg), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; @@ -193,7 +193,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should notify on retry attempts', async () => { - const body = { buttered: '🥖' }; + const body = {buttered: '🥖'}; const scopes = [ nock(url) .get('/') @@ -219,7 +219,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('accepts async onRetryAttempt handler', async () => { - const body = { buttered: '🥖' }; + const body = {buttered: '🥖'}; const scopes = [ nock(url) .get('/') @@ -283,31 +283,31 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry on ENOTFOUND', async () => { - const body = { spicy: '🌮' }; + const body = {spicy: '🌮'}; const scopes = [ nock(url) .get('/') - .replyWithError({ code: 'ENOTFOUND' }), + .replyWithError({code: 'ENOTFOUND'}), nock(url) .get('/') .reply(200, body), ]; - const res = await request({ url, retry: true }); + const res = await request({url, retry: true}); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); it('should retry on ETIMEDOUT', async () => { - const body = { sizzling: '🥓' }; + const body = {sizzling: '🥓'}; const scopes = [ nock(url) .get('/') - .replyWithError({ code: 'ETIMEDOUT' }), + .replyWithError({code: 'ETIMEDOUT'}), nock(url) .get('/') .reply(200, body), ]; - const res = await request({ url, retry: true }); + const res = await request({url, retry: true}); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); @@ -315,8 +315,8 @@ describe('🛸 retry & exponential backoff', () => { it('should allow configuring noResponseRetries', async () => { const scope = nock(url) .get('/') - .replyWithError({ code: 'ETIMEDOUT' }); - const config = { url, retryConfig: { noResponseRetries: 0 } }; + .replyWithError({code: 'ETIMEDOUT'}); + const config = {url, retryConfig: {noResponseRetries: 0}}; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; From 6b353c5ffd6f21585e63d078609c6b328d376a19 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Mon, 3 Feb 2020 20:49:29 -0800 Subject: [PATCH 4/9] fixy --- .eslintignore | 2 +- .prettierignore | 8 +- browser-test/browser-test-runner.ts | 2 +- browser-test/test.browser.ts | 8 +- karma.conf.js | 4 +- package.json | 2 +- samples/quickstart.js | 4 +- samples/test/test.samples.js | 8 +- src/common.ts | 8 +- src/gaxios.ts | 10 +-- src/index.ts | 6 +- src/retry.ts | 8 +- system-test/fixtures/sample/src/index.ts | 2 +- system-test/test.install.ts | 8 +- test/test.getch.ts | 98 ++++++++++++------------ test/test.index.ts | 2 +- test/test.retry.ts | 46 +++++------ 17 files changed, 114 insertions(+), 112 deletions(-) diff --git a/.eslintignore b/.eslintignore index 09b31fe7..a4ac7b37 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,5 +1,5 @@ **/node_modules -src/**/doc/* +**/.coverage build/ docs/ protos/ diff --git a/.prettierignore b/.prettierignore index f6fac98b..a4ac7b37 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,3 +1,5 @@ -node_modules/* -samples/node_modules/* -src/**/doc/* +**/node_modules +**/.coverage +build/ +docs/ +protos/ diff --git a/browser-test/browser-test-runner.ts b/browser-test/browser-test-runner.ts index ce267d40..5d408764 100644 --- a/browser-test/browser-test-runner.ts +++ b/browser-test/browser-test-runner.ts @@ -51,7 +51,7 @@ async function main() { const server = await listen(app, port); console.log(`[http server] I'm listening on port ${port}! Starting karma.`); - const result = await execa('karma', ['start'], {stdio: 'inherit'}); + const result = await execa('karma', ['start'], { stdio: 'inherit' }); server.close(); console.log( `[http server] Karma has finished! I'm no longer listening on port ${port}!` diff --git a/browser-test/test.browser.ts b/browser-test/test.browser.ts index bdf86863..68d208fd 100644 --- a/browser-test/test.browser.ts +++ b/browser-test/test.browser.ts @@ -12,13 +12,13 @@ // limitations under the License. import assert from 'assert'; -import {describe, it} from 'mocha'; -import {request} from '../src/index'; +import { describe, it } from 'mocha'; +import { request } from '../src/index'; const port = 7172; // should match the port defined in `webserver.ts` describe('💻 browser tests', () => { it('should just work from browser', async () => { - const result = await request({url: `http://localhost:${port}/path`}); + const result = await request({ url: `http://localhost:${port}/path` }); assert.strictEqual(result.status, 200); assert.strictEqual(result.data, 'response'); }); @@ -26,7 +26,7 @@ describe('💻 browser tests', () => { it('should pass querystring parameters from browser', async () => { const result = await request({ url: `http://localhost:${port}/querystring`, - params: {query: 'value'}, + params: { query: 'value' }, }); assert.strictEqual(result.status, 200); assert.strictEqual(result.data, 'value'); diff --git a/karma.conf.js b/karma.conf.js index eff7d047..086198a4 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -52,8 +52,8 @@ module.exports = function(config) { // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage', 'remap-coverage'], - coverageReporter: {type: 'in-memory'}, - remapCoverageReporter: {html: './coverage'}, + coverageReporter: { type: 'in-memory' }, + remapCoverageReporter: { html: './coverage' }, // web server port port: 9876, diff --git a/package.json b/package.json index 1bbeb396..d091d57f 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,7 @@ "codecov": "^3.2.0", "execa": "^4.0.0", "express": "^4.16.4", - "gts": "file:../gts/gts-1.1.2.tgz", + "gts": "2.0.0-alpha.3", "is-docker": "^2.0.0", "karma": "^4.0.0", "karma-chrome-launcher": "^3.0.0", diff --git a/samples/quickstart.js b/samples/quickstart.js index d41e2f94..c0500ffa 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -13,14 +13,14 @@ // limitations under the License. // [START gaxios_quickstart] -const {request} = require('gaxios'); +const { request } = require('gaxios'); /** * Perform a simple `GET` request to a JSON API. */ async function quickstart() { const url = 'https://www.googleapis.com/discovery/v1/apis/'; - const res = await request({url}); + const res = await request({ url }); console.log(`status: ${res.status}`); console.log(`data:`); console.log(res.data); diff --git a/samples/test/test.samples.js b/samples/test/test.samples.js index dcb97a1a..dce71952 100644 --- a/samples/test/test.samples.js +++ b/samples/test/test.samples.js @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -const {execSync} = require('child_process'); -const {assert} = require('chai'); -const {describe, it} = require('mocha'); +const { execSync } = require('child_process'); +const { assert } = require('chai'); +const { describe, it } = require('mocha'); -const exec = cmd => execSync(cmd, {encoding: 'utf8'}); +const exec = cmd => execSync(cmd, { encoding: 'utf8' }); describe(__filename, () => { it('should run the quickstart', () => { diff --git a/src/common.ts b/src/common.ts index 324974ab..65ff1a99 100644 --- a/src/common.ts +++ b/src/common.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {AbortSignal} from 'abort-controller'; -import {Agent} from 'http'; -import {URL} from 'url'; +import { AbortSignal } from 'abort-controller'; +import { Agent } from 'http'; +import { URL } from 'url'; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -86,7 +86,7 @@ export interface GaxiosOptions { maxRedirects?: number; follow?: number; params?: any; - paramsSerializer?: (params: {[index: string]: string | number}) => string; + paramsSerializer?: (params: { [index: string]: string | number }) => string; timeout?: number; onUploadProgress?: (progressEvent: any) => void; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream'; diff --git a/src/gaxios.ts b/src/gaxios.ts index 55b038ff..be9bc7e6 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -12,8 +12,8 @@ // limitations under the License. import extend from 'extend'; -import {Agent} from 'http'; -import nodeFetch, {Response as NodeFetchResponse} from 'node-fetch'; +import { Agent } from 'http'; +import nodeFetch, { Response as NodeFetchResponse } from 'node-fetch'; import qs from 'querystring'; import isStream from 'is-stream'; import url from 'url'; @@ -25,7 +25,7 @@ import { GaxiosResponse, Headers, } from './common'; -import {getRetryConfig} from './retry'; +import { getRetryConfig } from './retry'; /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable node/no-unsupported-features/node-builtins */ @@ -115,7 +115,7 @@ export class Gaxios { } catch (e) { const err = e as GaxiosError; err.config = opts; - const {shouldRetry, config} = await getRetryConfig(e); + const { shouldRetry, config } = await getRetryConfig(e); if (shouldRetry && config) { err.config.retryConfig!.currentRetryAttempt = config.retryConfig!.currentRetryAttempt; return this._request(err.config); @@ -231,7 +231,7 @@ export class Gaxios { * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) * @param params key value pars to encode */ - private paramsSerializer(params: {[index: string]: string | number}) { + private paramsSerializer(params: { [index: string]: string | number }) { return qs.stringify(params); } diff --git a/src/index.ts b/src/index.ts index 9d20638c..a355ef7a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {GaxiosOptions} from './common'; -import {Gaxios} from './gaxios'; +import { GaxiosOptions } from './common'; +import { Gaxios } from './gaxios'; export { GaxiosError, @@ -21,7 +21,7 @@ export { Headers, RetryConfig, } from './common'; -export {Gaxios, GaxiosOptions}; +export { Gaxios, GaxiosOptions }; /** * The default instance used when the `request` method is directly diff --git a/src/retry.ts b/src/retry.ts index 178d4d53..7c8d961b 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -11,12 +11,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {GaxiosError} from './common'; +import { GaxiosError } from './common'; export async function getRetryConfig(err: GaxiosError) { let config = getConfig(err); if (!err || !err.config || (!config && !err.config.retry)) { - return {shouldRetry: false}; + return { shouldRetry: false }; } config = config || {}; config.currentRetryAttempt = config.currentRetryAttempt || 0; @@ -56,7 +56,7 @@ export async function getRetryConfig(err: GaxiosError) { // Determine if we should retry the request const shouldRetryFn = config.shouldRetry || shouldRetryRequest; if (!(await shouldRetryFn(err))) { - return {shouldRetry: false, config: err.config}; + return { shouldRetry: false, config: err.config }; } // Calculate time to wait with exponential backoff. @@ -78,7 +78,7 @@ export async function getRetryConfig(err: GaxiosError) { // Return the promise in which recalls Gaxios to retry the request await backoff; - return {shouldRetry: true, config: err.config}; + return { shouldRetry: true, config: err.config }; } /** diff --git a/system-test/fixtures/sample/src/index.ts b/system-test/fixtures/sample/src/index.ts index 0166d2a3..9e327e64 100644 --- a/system-test/fixtures/sample/src/index.ts +++ b/system-test/fixtures/sample/src/index.ts @@ -1,4 +1,4 @@ -import {request} from 'gaxios'; +import { request } from 'gaxios'; async function main() { await request({ url: 'https://www.googleapis.com/discovery/v1/apis/', diff --git a/system-test/test.install.ts b/system-test/test.install.ts index 6c54733d..c67e6780 100644 --- a/system-test/test.install.ts +++ b/system-test/test.install.ts @@ -16,16 +16,16 @@ import assert from 'assert'; import execa from 'execa'; import fs from 'fs'; import mv from 'mv'; -import {ncp} from 'ncp'; +import { ncp } from 'ncp'; import path from 'path'; import tmp from 'tmp'; -import {promisify} from 'util'; -import {describe, it, before, after} from 'mocha'; +import { promisify } from 'util'; +import { describe, it, before, after } from 'mocha'; const keep = false; const mvp = (promisify(mv) as {}) as (...args: string[]) => Promise; const ncpp = promisify(ncp); -const stagingDir = tmp.dirSync({keep, unsafeCleanup: true}); +const stagingDir = tmp.dirSync({ keep, unsafeCleanup: true }); const stagingPath = stagingDir.name; // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../../package.json'); diff --git a/test/test.getch.ts b/test/test.getch.ts index 8ce0b338..8b20a486 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -15,7 +15,7 @@ import assert from 'assert'; import nock from 'nock'; import sinon from 'sinon'; import stream from 'stream'; -import {describe, it, afterEach} from 'mocha'; +import { describe, it, afterEach } from 'mocha'; import assertRejects = require('assert-rejects'); // eslint-disable-next-line @typescript-eslint/no-var-requires const HttpsProxyAgent = require('https-proxy-agent'); @@ -28,7 +28,7 @@ import { } from '../src'; import qs from 'querystring'; import fs from 'fs'; -import {Blob} from 'node-fetch'; +import { Blob } from 'node-fetch'; nock.disableNetConnect(); @@ -51,7 +51,7 @@ describe('🚙 error handling', () => { const scope = nock(url) .get('/') .reply(500); - await assertRejects(request({url}), (err: GaxiosError) => { + await assertRejects(request({ url }), (err: GaxiosError) => { scope.done(); return err.code === '500'; }); @@ -63,8 +63,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .head('/') .reply(200); - const inst = new Gaxios({method: 'HEAD'}); - const res = await inst.request({url}); + const inst = new Gaxios({ method: 'HEAD' }); + const res = await inst.request({ url }); scope.done(); assert.strictEqual(res.config.method, 'HEAD'); }); @@ -73,8 +73,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/') .reply(200); - const inst = new Gaxios({headers: {apple: 'juice'}}); - const res = await inst.request({url, headers: {figgy: 'pudding'}}); + const inst = new Gaxios({ headers: { apple: 'juice' } }); + const res = await inst.request({ url, headers: { figgy: 'pudding' } }); scope.done(); assert.strictEqual(res.config.headers!.apple, 'juice'); assert.strictEqual(res.config.headers!.figgy, 'pudding'); @@ -84,8 +84,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/v1/mango') .reply(200, {}); - const inst = new Gaxios({baseURL: `${url}/v1`}); - const res = await inst.request({url: '/mango'}); + const inst = new Gaxios({ baseURL: `${url}/v1` }); + const res = await inst.request({ url: '/mango' }); scope.done(); assert.deepStrictEqual(res.data, {}); }); @@ -94,32 +94,32 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/') .reply(304); - const res = await request({url, validateStatus: () => true}); + const res = await request({ url, validateStatus: () => true }); scope.done(); assert.strictEqual(res.status, 304); }); it('should allow setting maxContentLength', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .reply(200, body); const maxContentLength = 1; - await assertRejects(request({url, maxContentLength}), /over limit/); + await assertRejects(request({ url, maxContentLength }), /over limit/); scope.done(); }); it('should support redirects by default', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scopes = [ nock(url) .get('/foo') .reply(200, body), nock(url) .get('/') - .reply(302, undefined, {location: '/foo'}), + .reply(302, undefined, { location: '/foo' }), ]; - const res = await request({url}); + const res = await request({ url }); scopes.forEach(x => x.done()); assert.deepStrictEqual(res.data, body); assert.strictEqual(res.request.responseURL, `${url}/foo`); @@ -128,15 +128,15 @@ describe('🥁 configuration options', () => { it('should support disabling redirects', async () => { const scope = nock(url) .get('/') - .reply(302, undefined, {location: '/foo'}); + .reply(302, undefined, { location: '/foo' }); const maxRedirects = 0; - await assertRejects(request({url, maxRedirects}), /maximum redirect/); + await assertRejects(request({ url, maxRedirects }), /maximum redirect/); scope.done(); }); it('should allow overriding the adapter', async () => { const response: GaxiosResponse = { - data: {hello: '🌎'}, + data: { hello: '🌎' }, config: {}, status: 200, statusText: 'OK', @@ -146,13 +146,13 @@ describe('🥁 configuration options', () => { }, }; const adapter = () => Promise.resolve(response); - const res = await request({url, adapter}); + const res = await request({ url, adapter }); assert.strictEqual(response, res); }); it('should encode URL parameters', async () => { const path = '/?james=kirk&montgomery=scott'; - const opts = {url: `${url}${path}`}; + const opts = { url: `${url}${path}` }; const scope = nock(url) .get(path) .reply(200, {}); @@ -163,7 +163,7 @@ describe('🥁 configuration options', () => { }); it('should encode parameters from the params option', async () => { - const opts = {url, params: {james: 'kirk', montgomery: 'scott'}}; + const opts = { url, params: { james: 'kirk', montgomery: 'scott' } }; const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) .get(path) @@ -177,7 +177,7 @@ describe('🥁 configuration options', () => { it('should merge URL parameters with the params option', async () => { const opts = { url: `${url}/?james=beckwith&montgomery=scott`, - params: {james: 'kirk'}, + params: { james: 'kirk' }, }; const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) @@ -191,7 +191,7 @@ describe('🥁 configuration options', () => { it('should allow overriding the param serializer', async () => { const qs = '?oh=HAI'; - const params = {james: 'kirk'}; + const params = { james: 'kirk' }; const opts: GaxiosOptions = { url, params, @@ -210,11 +210,11 @@ describe('🥁 configuration options', () => { }); it('should return json by default', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({url}); + const res = await request({ url }); scope.done(); assert.deepStrictEqual(body, res.data); }); @@ -224,43 +224,43 @@ describe('🥁 configuration options', () => { .matchHeader('accept', 'application/json') .get('/') .reply(200, {}); - const res = await request({url}); + const res = await request({ url }); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should use an https proxy if asked nicely', async () => { - sandbox.stub(process, 'env').value({https_proxy: 'https://fake.proxy'}); - const body = {hello: '🌎'}; + sandbox.stub(process, 'env').value({ https_proxy: 'https://fake.proxy' }); + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({url}); + const res = await request({ url }); scope.done(); assert.deepStrictEqual(res.data, body); assert.ok(res.config.agent instanceof HttpsProxyAgent); }); it('should load the proxy from the cache', async () => { - sandbox.stub(process, 'env').value({HTTPS_PROXY: 'https://fake.proxy'}); - const body = {hello: '🌎'}; + sandbox.stub(process, 'env').value({ HTTPS_PROXY: 'https://fake.proxy' }); + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .twice() .reply(200, body); - const res1 = await request({url}); + const res1 = await request({ url }); const agent = res1.config.agent; - const res2 = await request({url}); + const res2 = await request({ url }); assert.strictEqual(agent, res2.config.agent); scope.done(); }); it('should include the request data in the response config', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .post('/', body) .reply(200); - const res = await request({url, method: 'POST', data: body}); + const res = await request({ url, method: 'POST', data: body }); scope.done(); assert.deepStrictEqual(res.config.data, body); }); @@ -274,13 +274,13 @@ describe('🎏 data handling', () => { const scope = nock(url) .post('/', contents) .reply(200, {}); - const res = await request({url, method: 'POST', data: body}); + const res = await request({ url, method: 'POST', data: body }); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should accept a string in the request data', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const encoded = qs.stringify(body); const scope = nock(url) .matchHeader('content-type', 'application/x-www-form-urlencoded') @@ -290,14 +290,14 @@ describe('🎏 data handling', () => { url, method: 'POST', data: encoded, - headers: {'content-type': 'application/x-www-form-urlencoded'}, + headers: { 'content-type': 'application/x-www-form-urlencoded' }, }); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should set content-type for object request', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .matchHeader('content-type', 'application/json') .post('/', JSON.stringify(body)) @@ -312,17 +312,17 @@ describe('🎏 data handling', () => { }); it('should return stream if asked nicely', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({url, responseType: 'stream'}); + const res = await request({ url, responseType: 'stream' }); scope.done(); assert(res.data instanceof stream.Readable); }); it('should return an ArrayBuffer if asked nicely', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .reply(200, body); @@ -339,11 +339,11 @@ describe('🎏 data handling', () => { }); it('should return a blob if asked nicely', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({url, responseType: 'blob'}); + const res = await request({ url, responseType: 'blob' }); scope.done(); assert.ok(res.data); }); @@ -353,17 +353,17 @@ describe('🎏 data handling', () => { const scope = nock(url) .get('/') .reply(200, body); - const res = await request({url, responseType: 'text'}); + const res = await request({ url, responseType: 'text' }); scope.done(); assert.strictEqual(res.data, body); }); it('should return status text', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({url}); + const res = await request({ url }); scope.done(); assert.ok(res.data); assert.strictEqual(res.statusText, 'OK'); @@ -377,11 +377,11 @@ describe('🍂 defaults & instances', () => { }); it('should allow passing empty options', async () => { - const body = {hello: '🌎'}; + const body = { hello: '🌎' }; const scope = nock(url) .get('/') .reply(200, body); - const gax = new Gaxios({url}); + const gax = new Gaxios({ url }); const res = await gax.request(); scope.done(); assert.deepStrictEqual(res.data, body); diff --git a/test/test.index.ts b/test/test.index.ts index ac22903f..5be639d7 100644 --- a/test/test.index.ts +++ b/test/test.index.ts @@ -12,7 +12,7 @@ // limitations under the License. import assert from 'assert'; -import {describe, it} from 'mocha'; +import { describe, it } from 'mocha'; import * as main from '../src/index'; describe('📝 main exports', () => { diff --git a/test/test.retry.ts b/test/test.retry.ts index 88f61ed1..edb8cf09 100644 --- a/test/test.retry.ts +++ b/test/test.retry.ts @@ -11,11 +11,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {AbortController} from 'abort-controller'; +import { AbortController } from 'abort-controller'; import assert from 'assert'; import nock from 'nock'; -import {describe, it, afterEach} from 'mocha'; -import {Gaxios, GaxiosError, GaxiosOptions, request} from '../src'; +import { describe, it, afterEach } from 'mocha'; +import { Gaxios, GaxiosError, GaxiosOptions, request } from '../src'; import assertRejects = require('assert-rejects'); nock.disableNetConnect(); @@ -40,7 +40,7 @@ describe('🛸 retry & exponential backoff', () => { .get('/') .times(4) .reply(500); - await assertRejects(request({url, retry: true}), (e: Error) => { + await assertRejects(request({ url, retry: true }), (e: Error) => { scope.done(); const config = getConfig(e); if (!config) { @@ -70,7 +70,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry on 500 on the main export', async () => { - const body = {buttered: '🥖'}; + const body = { buttered: '🥖' }; const scopes = [ nock(url) .get('/') @@ -92,7 +92,7 @@ describe('🛸 retry & exponential backoff', () => { .post('/') .reply(500); await assertRejects( - request({url, method: 'POST', retry: true}), + request({ url, method: 'POST', retry: true }), (e: Error) => { const config = getConfig(e); return config!.currentRetryAttempt === 0; @@ -107,7 +107,7 @@ describe('🛸 retry & exponential backoff', () => { method: 'GET', url: 'https://google.com', signal: ac.signal, - retryConfig: {retry: 10, noResponseRetries: 10}, + retryConfig: { retry: 10, noResponseRetries: 10 }, }; const req = request(config); ac.abort(); @@ -121,7 +121,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry at least the configured number of times', async () => { - const body = {dippy: '🥚'}; + const body = { dippy: '🥚' }; const scopes = [ nock(url) .get('/') @@ -131,7 +131,7 @@ describe('🛸 retry & exponential backoff', () => { .get('/') .reply(200, body), ]; - const cfg = {url, retryConfig: {retry: 4}}; + const cfg = { url, retryConfig: { retry: 4 } }; const res = await request(cfg); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); @@ -142,7 +142,7 @@ describe('🛸 retry & exponential backoff', () => { .get('/') .twice() .reply(500); - const cfg = {url, retryConfig: {retry: 1}}; + const cfg = { url, retryConfig: { retry: 1 } }; await assertRejects(request(cfg), (e: Error) => { return getConfig(e)!.currentRetryAttempt === 1; }); @@ -153,7 +153,7 @@ describe('🛸 retry & exponential backoff', () => { const scope = nock(url) .get('/') .reply(404); - await assertRejects(request({url, retry: true}), (e: Error) => { + await assertRejects(request({ url, retry: true }), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; }); @@ -161,7 +161,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retain the baseUrl on retry', async () => { - const body = {pumpkin: '🥧'}; + const body = { pumpkin: '🥧' }; const url = '/path'; const baseUrl = 'http://example.com'; const scope = nock(baseUrl) @@ -184,7 +184,7 @@ describe('🛸 retry & exponential backoff', () => { const scope = nock(url) .get('/') .reply(500); - const cfg = {url, retryConfig: {retry: 0}}; + const cfg = { url, retryConfig: { retry: 0 } }; await assertRejects(request(cfg), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; @@ -193,7 +193,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should notify on retry attempts', async () => { - const body = {buttered: '🥖'}; + const body = { buttered: '🥖' }; const scopes = [ nock(url) .get('/') @@ -219,7 +219,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('accepts async onRetryAttempt handler', async () => { - const body = {buttered: '🥖'}; + const body = { buttered: '🥖' }; const scopes = [ nock(url) .get('/') @@ -283,31 +283,31 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry on ENOTFOUND', async () => { - const body = {spicy: '🌮'}; + const body = { spicy: '🌮' }; const scopes = [ nock(url) .get('/') - .replyWithError({code: 'ENOTFOUND'}), + .replyWithError({ code: 'ENOTFOUND' }), nock(url) .get('/') .reply(200, body), ]; - const res = await request({url, retry: true}); + const res = await request({ url, retry: true }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); it('should retry on ETIMEDOUT', async () => { - const body = {sizzling: '🥓'}; + const body = { sizzling: '🥓' }; const scopes = [ nock(url) .get('/') - .replyWithError({code: 'ETIMEDOUT'}), + .replyWithError({ code: 'ETIMEDOUT' }), nock(url) .get('/') .reply(200, body), ]; - const res = await request({url, retry: true}); + const res = await request({ url, retry: true }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); @@ -315,8 +315,8 @@ describe('🛸 retry & exponential backoff', () => { it('should allow configuring noResponseRetries', async () => { const scope = nock(url) .get('/') - .replyWithError({code: 'ETIMEDOUT'}); - const config = {url, retryConfig: {noResponseRetries: 0}}; + .replyWithError({ code: 'ETIMEDOUT' }); + const config = { url, retryConfig: { noResponseRetries: 0 } }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; From 69b5d1cbcb806b0196abad255e103a439cde450d Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Mon, 3 Feb 2020 20:55:21 -0800 Subject: [PATCH 5/9] more --- .prettierrc.js | 3 -- .prettierrc.json | 3 ++ browser-test/test.browser.ts | 2 +- karma.conf.js | 10 ++--- prettier.config.js | 2 +- src/gaxios.ts | 6 +-- src/index.ts | 2 +- src/retry.ts | 4 +- src/web.ts | 0 system-test/fixtures/sample/src/index.ts | 16 +++++++- system-test/fixtures/sample/webpack.config.js | 18 ++++----- system-test/test.install.ts | 6 +-- test/test.getch.ts | 18 ++++----- test/test.retry.ts | 38 +++++++++---------- webpack-tests.config.js | 16 ++++---- webpack.config.js | 18 ++++----- 16 files changed, 88 insertions(+), 74 deletions(-) delete mode 100644 .prettierrc.js create mode 100644 .prettierrc.json delete mode 100644 src/web.ts diff --git a/.prettierrc.js b/.prettierrc.js deleted file mode 100644 index 8ed6886c..00000000 --- a/.prettierrc.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - ...require("gts/.prettierrc.js"), -}; diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..544138be --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,3 @@ +{ + "singleQuote": true +} diff --git a/browser-test/test.browser.ts b/browser-test/test.browser.ts index 68d208fd..124c0754 100644 --- a/browser-test/test.browser.ts +++ b/browser-test/test.browser.ts @@ -26,7 +26,7 @@ describe('💻 browser tests', () => { it('should pass querystring parameters from browser', async () => { const result = await request({ url: `http://localhost:${port}/querystring`, - params: { query: 'value' }, + params: { query: 'value' } }); assert.strictEqual(result.status, 200); assert.strictEqual(result.data, 'value'); diff --git a/karma.conf.js b/karma.conf.js index 086198a4..dbbda4a9 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -42,7 +42,7 @@ module.exports = function(config) { preprocessors: { './src/*.ts': ['coverage'], './src/**/*.ts': ['coverage'], - './browser-test/*.ts': ['webpack', 'sourcemap'], + './browser-test/*.ts': ['webpack', 'sourcemap'] }, webpack: webpackConfig, @@ -76,8 +76,8 @@ module.exports = function(config) { base: 'ChromeHeadless', // We must disable the Chrome sandbox when running Chrome inside Docker (Chrome's sandbox needs // more permissions than Docker allows by default) - flags: isDocker ? ['--no-sandbox'] : [], - }, + flags: isDocker ? ['--no-sandbox'] : [] + } }, // Continuous Integration mode @@ -90,7 +90,7 @@ module.exports = function(config) { // set correct MIME type when serving .ts files (already compiled to JavaScript): mime: { - 'text/javascript': ['ts'], - }, + 'text/javascript': ['ts'] + } }); }; diff --git a/prettier.config.js b/prettier.config.js index a425d3f7..0a2100a3 100644 --- a/prettier.config.js +++ b/prettier.config.js @@ -1,4 +1,4 @@ module.exports = { singleQuote: true, - trailingComma: 'es5', + trailingComma: 'es5' }; diff --git a/src/gaxios.ts b/src/gaxios.ts index be9bc7e6..473465c3 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -23,7 +23,7 @@ import { GaxiosOptions, GaxiosPromise, GaxiosResponse, - Headers, + Headers } from './common'; import { getRetryConfig } from './retry'; @@ -255,8 +255,8 @@ export class Gaxios { // XMLHttpRequestLike request: { - responseURL: res.url, - }, + responseURL: res.url + } }; } } diff --git a/src/index.ts b/src/index.ts index a355ef7a..21025155 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,7 +19,7 @@ export { GaxiosPromise, GaxiosResponse, Headers, - RetryConfig, + RetryConfig } from './common'; export { Gaxios, GaxiosOptions }; diff --git a/src/retry.ts b/src/retry.ts index 7c8d961b..df404ed3 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -27,7 +27,7 @@ export async function getRetryConfig(err: GaxiosError) { 'HEAD', 'PUT', 'OPTIONS', - 'DELETE', + 'DELETE' ]; config.noResponseRetries = config.noResponseRetries === undefined || config.noResponseRetries === null @@ -46,7 +46,7 @@ export async function getRetryConfig(err: GaxiosError) { // 5xx - Retry (Server errors) [100, 199], [429, 429], - [500, 599], + [500, 599] ]; config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; diff --git a/src/web.ts b/src/web.ts deleted file mode 100644 index e69de29b..00000000 diff --git a/system-test/fixtures/sample/src/index.ts b/system-test/fixtures/sample/src/index.ts index 9e327e64..6dad45bd 100644 --- a/system-test/fixtures/sample/src/index.ts +++ b/system-test/fixtures/sample/src/index.ts @@ -1,7 +1,21 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + import { request } from 'gaxios'; async function main() { await request({ - url: 'https://www.googleapis.com/discovery/v1/apis/', + url: 'https://www.googleapis.com/discovery/v1/apis/' }); } main(); diff --git a/system-test/fixtures/sample/webpack.config.js b/system-test/fixtures/sample/webpack.config.js index b3ced2ce..4806fd2c 100644 --- a/system-test/fixtures/sample/webpack.config.js +++ b/system-test/fixtures/sample/webpack.config.js @@ -21,31 +21,31 @@ module.exports = { resolve: { extensions: ['.ts', '.js', '.json'], alias: { - '../../package.json': path.resolve(__dirname, 'package.json'), - }, + '../../package.json': path.resolve(__dirname, 'package.json') + } }, output: { filename: 'bundle.min.js', - path: path.resolve(__dirname, 'dist'), + path: path.resolve(__dirname, 'dist') }, node: { child_process: 'empty', fs: 'empty', - crypto: 'empty', + crypto: 'empty' }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader', + use: 'null-loader' }, { test: /\.ts$/, use: 'ts-loader', - exclude: /node_modules/, - }, - ], + exclude: /node_modules/ + } + ] }, mode: 'production', - plugins: [], + plugins: [] }; diff --git a/system-test/test.install.ts b/system-test/test.install.ts index c67e6780..be2599f6 100644 --- a/system-test/test.install.ts +++ b/system-test/test.install.ts @@ -42,14 +42,14 @@ describe('📦 pack and install', () => { await ncpp('system-test/fixtures/sample', `${stagingPath}/`); await execa('npm', ['install', '--unsafe-perm'], { cwd: `${stagingPath}/`, - stdio: 'inherit', + stdio: 'inherit' }); }); it('should run the sample', async () => { await execa('node', ['--throw-deprecation', 'build/src/index.js'], { cwd: `${stagingPath}/`, - stdio: 'inherit', + stdio: 'inherit' }); }); @@ -57,7 +57,7 @@ describe('📦 pack and install', () => { // we expect npm install is executed in the before hook await execa('npx', ['webpack'], { cwd: `${stagingPath}/`, - stdio: 'inherit', + stdio: 'inherit' }); const bundle = path.join(stagingPath, 'dist', 'bundle.min.js'); const stat = fs.statSync(bundle); diff --git a/test/test.getch.ts b/test/test.getch.ts index 8b20a486..c5b8e03a 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -24,7 +24,7 @@ import { GaxiosError, request, GaxiosOptions, - GaxiosResponse, + GaxiosResponse } from '../src'; import qs from 'querystring'; import fs from 'fs'; @@ -117,7 +117,7 @@ describe('🥁 configuration options', () => { .reply(200, body), nock(url) .get('/') - .reply(302, undefined, { location: '/foo' }), + .reply(302, undefined, { location: '/foo' }) ]; const res = await request({ url }); scopes.forEach(x => x.done()); @@ -142,8 +142,8 @@ describe('🥁 configuration options', () => { statusText: 'OK', headers: {}, request: { - responseURL: url, - }, + responseURL: url + } }; const adapter = () => Promise.resolve(response); const res = await request({ url, adapter }); @@ -177,7 +177,7 @@ describe('🥁 configuration options', () => { it('should merge URL parameters with the params option', async () => { const opts = { url: `${url}/?james=beckwith&montgomery=scott`, - params: { james: 'kirk' }, + params: { james: 'kirk' } }; const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) @@ -198,7 +198,7 @@ describe('🥁 configuration options', () => { paramsSerializer: ps => { assert.strictEqual(JSON.stringify(params), JSON.stringify(ps)); return '?oh=HAI'; - }, + } }; const scope = nock(url) .get(`/${qs}`) @@ -290,7 +290,7 @@ describe('🎏 data handling', () => { url, method: 'POST', data: encoded, - headers: { 'content-type': 'application/x-www-form-urlencoded' }, + headers: { 'content-type': 'application/x-www-form-urlencoded' } }); scope.done(); assert.deepStrictEqual(res.data, {}); @@ -305,7 +305,7 @@ describe('🎏 data handling', () => { const res = await request({ url, method: 'POST', - data: body, + data: body }); scope.done(); assert.deepStrictEqual(res.data, {}); @@ -328,7 +328,7 @@ describe('🎏 data handling', () => { .reply(200, body); const res = await request({ url, - responseType: 'arraybuffer', + responseType: 'arraybuffer' }); scope.done(); assert(res.data instanceof ArrayBuffer); diff --git a/test/test.retry.ts b/test/test.retry.ts index edb8cf09..43b23a0a 100644 --- a/test/test.retry.ts +++ b/test/test.retry.ts @@ -56,7 +56,7 @@ describe('🛸 retry & exponential backoff', () => { const expectedStatusCodes = [ [100, 199], [429, 429], - [500, 599], + [500, 599] ]; const statusCodesToRetry = config!.statusCodesToRetry!; for (let i = 0; i < statusCodesToRetry.length; i++) { @@ -77,11 +77,11 @@ describe('🛸 retry & exponential backoff', () => { .reply(500), nock(url) .get('/') - .reply(200, body), + .reply(200, body) ]; const res = await request({ url, - retry: true, + retry: true }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); @@ -107,7 +107,7 @@ describe('🛸 retry & exponential backoff', () => { method: 'GET', url: 'https://google.com', signal: ac.signal, - retryConfig: { retry: 10, noResponseRetries: 10 }, + retryConfig: { retry: 10, noResponseRetries: 10 } }; const req = request(config); ac.abort(); @@ -129,7 +129,7 @@ describe('🛸 retry & exponential backoff', () => { .reply(500), nock(url) .get('/') - .reply(200, body), + .reply(200, body) ]; const cfg = { url, retryConfig: { retry: 4 } }; const res = await request(cfg); @@ -170,11 +170,11 @@ describe('🛸 retry & exponential backoff', () => { .get(url) .reply(200, body); const gaxios = new Gaxios({ - baseUrl, + baseUrl }); const res = await gaxios.request({ url, - retry: true, + retry: true }); assert.deepStrictEqual(res.data, body); scope.done(); @@ -200,7 +200,7 @@ describe('🛸 retry & exponential backoff', () => { .reply(500), nock(url) .get('/') - .reply(200, body), + .reply(200, body) ]; let flipped = false; const config: GaxiosOptions = { @@ -210,8 +210,8 @@ describe('🛸 retry & exponential backoff', () => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; - }, - }, + } + } }; await request(config); assert.strictEqual(flipped, true); @@ -226,7 +226,7 @@ describe('🛸 retry & exponential backoff', () => { .reply(500), nock(url) .get('/') - .reply(200, body), + .reply(200, body) ]; let flipped = false; const config: GaxiosOptions = { @@ -236,8 +236,8 @@ describe('🛸 retry & exponential backoff', () => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; - }, - }, + } + } }; await request(config); assert.strictEqual(flipped, true); @@ -253,8 +253,8 @@ describe('🛸 retry & exponential backoff', () => { retryConfig: { shouldRetry: () => { return false; - }, - }, + } + } }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); @@ -272,8 +272,8 @@ describe('🛸 retry & exponential backoff', () => { retryConfig: { shouldRetry: async () => { return false; - }, - }, + } + } }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); @@ -290,7 +290,7 @@ describe('🛸 retry & exponential backoff', () => { .replyWithError({ code: 'ENOTFOUND' }), nock(url) .get('/') - .reply(200, body), + .reply(200, body) ]; const res = await request({ url, retry: true }); assert.deepStrictEqual(res.data, body); @@ -305,7 +305,7 @@ describe('🛸 retry & exponential backoff', () => { .replyWithError({ code: 'ETIMEDOUT' }), nock(url) .get('/') - .reply(200, body), + .reply(200, body) ]; const res = await request({ url, retry: true }); assert.deepStrictEqual(res.data, body); diff --git a/webpack-tests.config.js b/webpack-tests.config.js index d903551d..8642393d 100644 --- a/webpack-tests.config.js +++ b/webpack-tests.config.js @@ -20,27 +20,27 @@ module.exports = { resolve: { extensions: ['.ts', '.js', '.json'], alias: { - '../../package.json': path.resolve(__dirname, 'package.json'), - }, + '../../package.json': path.resolve(__dirname, 'package.json') + } }, node: { child_process: 'empty', fs: 'empty', - crypto: 'empty', + crypto: 'empty' }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader', + use: 'null-loader' }, { test: /\.ts$/, use: 'ts-loader', - exclude: /node_modules/, - }, - ], + exclude: /node_modules/ + } + ] }, mode: 'production', - plugins: [], + plugins: [] }; diff --git a/webpack.config.js b/webpack.config.js index 012df506..20812cd3 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -21,32 +21,32 @@ module.exports = { resolve: { extensions: ['.ts', '.js', '.json'], alias: { - '../../package.json': path.resolve(__dirname, 'package.json'), - }, + '../../package.json': path.resolve(__dirname, 'package.json') + } }, output: { library: 'gaxios', filename: 'gaxios.min.js', - path: path.resolve(__dirname, 'dist'), + path: path.resolve(__dirname, 'dist') }, node: { child_process: 'empty', fs: 'empty', - crypto: 'empty', + crypto: 'empty' }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader', + use: 'null-loader' }, { test: /\.ts$/, use: 'ts-loader', - exclude: /node_modules/, - }, - ], + exclude: /node_modules/ + } + ] }, mode: 'production', - plugins: [], + plugins: [] }; From bd9d0cd1088be10a31aac48f3d5fa7045c917357 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Mon, 3 Feb 2020 20:56:31 -0800 Subject: [PATCH 6/9] ugh --- prettier.config.js | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 prettier.config.js diff --git a/prettier.config.js b/prettier.config.js deleted file mode 100644 index 0a2100a3..00000000 --- a/prettier.config.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - singleQuote: true, - trailingComma: 'es5' -}; From a74e437b099ac739846ffe4da463be71a059bfd0 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Mon, 3 Feb 2020 21:04:17 -0800 Subject: [PATCH 7/9] =?UTF-8?q?=F0=9F=98=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/package.json b/package.json index d091d57f..8a7b2784 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,6 @@ "test": "c8 mocha build/test", "presystem-test": "npm run compile", "system-test": "mocha build/system-test --timeout 40000", - "clean": "gts clean", "compile": "tsc -p .", "fix": "gts fix", "prepare": "npm run compile", @@ -23,9 +22,7 @@ "docs": "compodoc src/", "docs-test": "linkinator docs", "predocs-test": "npm run docs", - "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", - "check": "gts check", - "posttest": "npm run check" + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../" }, "repository": "JustinBeckwith/gaxios", "keywords": [ From 3f449f51f67b3ded8be4aab0f64a922654be9130 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Tue, 4 Feb 2020 09:09:55 -0800 Subject: [PATCH 8/9] goo style --- .prettierrc.js | 3 + .prettierrc.json | 3 - browser-test/browser-test-runner.ts | 2 +- browser-test/test.browser.ts | 8 +- karma.conf.js | 14 +-- package.json | 2 +- samples/quickstart.js | 4 +- samples/test/test.samples.js | 8 +- src/common.ts | 8 +- src/gaxios.ts | 16 +-- src/index.ts | 8 +- src/retry.ts | 12 +- system-test/fixtures/sample/src/index.ts | 4 +- system-test/fixtures/sample/webpack.config.js | 18 +-- system-test/test.install.ts | 14 +-- test/test.getch.ts | 110 +++++++++--------- test/test.index.ts | 2 +- test/test.retry.ts | 82 ++++++------- webpack-tests.config.js | 16 +-- webpack.config.js | 18 +-- 20 files changed, 176 insertions(+), 176 deletions(-) create mode 100644 .prettierrc.js delete mode 100644 .prettierrc.json diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000..ff154833 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,3 @@ +module.exports = { + ...require('gts/.prettierrc.json') +} diff --git a/.prettierrc.json b/.prettierrc.json deleted file mode 100644 index 544138be..00000000 --- a/.prettierrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "singleQuote": true -} diff --git a/browser-test/browser-test-runner.ts b/browser-test/browser-test-runner.ts index 5d408764..ce267d40 100644 --- a/browser-test/browser-test-runner.ts +++ b/browser-test/browser-test-runner.ts @@ -51,7 +51,7 @@ async function main() { const server = await listen(app, port); console.log(`[http server] I'm listening on port ${port}! Starting karma.`); - const result = await execa('karma', ['start'], { stdio: 'inherit' }); + const result = await execa('karma', ['start'], {stdio: 'inherit'}); server.close(); console.log( `[http server] Karma has finished! I'm no longer listening on port ${port}!` diff --git a/browser-test/test.browser.ts b/browser-test/test.browser.ts index 124c0754..bdf86863 100644 --- a/browser-test/test.browser.ts +++ b/browser-test/test.browser.ts @@ -12,13 +12,13 @@ // limitations under the License. import assert from 'assert'; -import { describe, it } from 'mocha'; -import { request } from '../src/index'; +import {describe, it} from 'mocha'; +import {request} from '../src/index'; const port = 7172; // should match the port defined in `webserver.ts` describe('💻 browser tests', () => { it('should just work from browser', async () => { - const result = await request({ url: `http://localhost:${port}/path` }); + const result = await request({url: `http://localhost:${port}/path`}); assert.strictEqual(result.status, 200); assert.strictEqual(result.data, 'response'); }); @@ -26,7 +26,7 @@ describe('💻 browser tests', () => { it('should pass querystring parameters from browser', async () => { const result = await request({ url: `http://localhost:${port}/querystring`, - params: { query: 'value' } + params: {query: 'value'}, }); assert.strictEqual(result.status, 200); assert.strictEqual(result.data, 'value'); diff --git a/karma.conf.js b/karma.conf.js index dbbda4a9..eff7d047 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -42,7 +42,7 @@ module.exports = function(config) { preprocessors: { './src/*.ts': ['coverage'], './src/**/*.ts': ['coverage'], - './browser-test/*.ts': ['webpack', 'sourcemap'] + './browser-test/*.ts': ['webpack', 'sourcemap'], }, webpack: webpackConfig, @@ -52,8 +52,8 @@ module.exports = function(config) { // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage', 'remap-coverage'], - coverageReporter: { type: 'in-memory' }, - remapCoverageReporter: { html: './coverage' }, + coverageReporter: {type: 'in-memory'}, + remapCoverageReporter: {html: './coverage'}, // web server port port: 9876, @@ -76,8 +76,8 @@ module.exports = function(config) { base: 'ChromeHeadless', // We must disable the Chrome sandbox when running Chrome inside Docker (Chrome's sandbox needs // more permissions than Docker allows by default) - flags: isDocker ? ['--no-sandbox'] : [] - } + flags: isDocker ? ['--no-sandbox'] : [], + }, }, // Continuous Integration mode @@ -90,7 +90,7 @@ module.exports = function(config) { // set correct MIME type when serving .ts files (already compiled to JavaScript): mime: { - 'text/javascript': ['ts'] - } + 'text/javascript': ['ts'], + }, }); }; diff --git a/package.json b/package.json index 8a7b2784..70b8cb1c 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "codecov": "^3.2.0", "execa": "^4.0.0", "express": "^4.16.4", - "gts": "2.0.0-alpha.3", + "gts": "2.0.0-alpha.4", "is-docker": "^2.0.0", "karma": "^4.0.0", "karma-chrome-launcher": "^3.0.0", diff --git a/samples/quickstart.js b/samples/quickstart.js index c0500ffa..d41e2f94 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -13,14 +13,14 @@ // limitations under the License. // [START gaxios_quickstart] -const { request } = require('gaxios'); +const {request} = require('gaxios'); /** * Perform a simple `GET` request to a JSON API. */ async function quickstart() { const url = 'https://www.googleapis.com/discovery/v1/apis/'; - const res = await request({ url }); + const res = await request({url}); console.log(`status: ${res.status}`); console.log(`data:`); console.log(res.data); diff --git a/samples/test/test.samples.js b/samples/test/test.samples.js index dce71952..dcb97a1a 100644 --- a/samples/test/test.samples.js +++ b/samples/test/test.samples.js @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -const { execSync } = require('child_process'); -const { assert } = require('chai'); -const { describe, it } = require('mocha'); +const {execSync} = require('child_process'); +const {assert} = require('chai'); +const {describe, it} = require('mocha'); -const exec = cmd => execSync(cmd, { encoding: 'utf8' }); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); describe(__filename, () => { it('should run the quickstart', () => { diff --git a/src/common.ts b/src/common.ts index 65ff1a99..324974ab 100644 --- a/src/common.ts +++ b/src/common.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { AbortSignal } from 'abort-controller'; -import { Agent } from 'http'; -import { URL } from 'url'; +import {AbortSignal} from 'abort-controller'; +import {Agent} from 'http'; +import {URL} from 'url'; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -86,7 +86,7 @@ export interface GaxiosOptions { maxRedirects?: number; follow?: number; params?: any; - paramsSerializer?: (params: { [index: string]: string | number }) => string; + paramsSerializer?: (params: {[index: string]: string | number}) => string; timeout?: number; onUploadProgress?: (progressEvent: any) => void; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream'; diff --git a/src/gaxios.ts b/src/gaxios.ts index 473465c3..55b038ff 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -12,8 +12,8 @@ // limitations under the License. import extend from 'extend'; -import { Agent } from 'http'; -import nodeFetch, { Response as NodeFetchResponse } from 'node-fetch'; +import {Agent} from 'http'; +import nodeFetch, {Response as NodeFetchResponse} from 'node-fetch'; import qs from 'querystring'; import isStream from 'is-stream'; import url from 'url'; @@ -23,9 +23,9 @@ import { GaxiosOptions, GaxiosPromise, GaxiosResponse, - Headers + Headers, } from './common'; -import { getRetryConfig } from './retry'; +import {getRetryConfig} from './retry'; /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable node/no-unsupported-features/node-builtins */ @@ -115,7 +115,7 @@ export class Gaxios { } catch (e) { const err = e as GaxiosError; err.config = opts; - const { shouldRetry, config } = await getRetryConfig(e); + const {shouldRetry, config} = await getRetryConfig(e); if (shouldRetry && config) { err.config.retryConfig!.currentRetryAttempt = config.retryConfig!.currentRetryAttempt; return this._request(err.config); @@ -231,7 +231,7 @@ export class Gaxios { * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) * @param params key value pars to encode */ - private paramsSerializer(params: { [index: string]: string | number }) { + private paramsSerializer(params: {[index: string]: string | number}) { return qs.stringify(params); } @@ -255,8 +255,8 @@ export class Gaxios { // XMLHttpRequestLike request: { - responseURL: res.url - } + responseURL: res.url, + }, }; } } diff --git a/src/index.ts b/src/index.ts index 21025155..9d20638c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,17 +11,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { GaxiosOptions } from './common'; -import { Gaxios } from './gaxios'; +import {GaxiosOptions} from './common'; +import {Gaxios} from './gaxios'; export { GaxiosError, GaxiosPromise, GaxiosResponse, Headers, - RetryConfig + RetryConfig, } from './common'; -export { Gaxios, GaxiosOptions }; +export {Gaxios, GaxiosOptions}; /** * The default instance used when the `request` method is directly diff --git a/src/retry.ts b/src/retry.ts index df404ed3..178d4d53 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -11,12 +11,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { GaxiosError } from './common'; +import {GaxiosError} from './common'; export async function getRetryConfig(err: GaxiosError) { let config = getConfig(err); if (!err || !err.config || (!config && !err.config.retry)) { - return { shouldRetry: false }; + return {shouldRetry: false}; } config = config || {}; config.currentRetryAttempt = config.currentRetryAttempt || 0; @@ -27,7 +27,7 @@ export async function getRetryConfig(err: GaxiosError) { 'HEAD', 'PUT', 'OPTIONS', - 'DELETE' + 'DELETE', ]; config.noResponseRetries = config.noResponseRetries === undefined || config.noResponseRetries === null @@ -46,7 +46,7 @@ export async function getRetryConfig(err: GaxiosError) { // 5xx - Retry (Server errors) [100, 199], [429, 429], - [500, 599] + [500, 599], ]; config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; @@ -56,7 +56,7 @@ export async function getRetryConfig(err: GaxiosError) { // Determine if we should retry the request const shouldRetryFn = config.shouldRetry || shouldRetryRequest; if (!(await shouldRetryFn(err))) { - return { shouldRetry: false, config: err.config }; + return {shouldRetry: false, config: err.config}; } // Calculate time to wait with exponential backoff. @@ -78,7 +78,7 @@ export async function getRetryConfig(err: GaxiosError) { // Return the promise in which recalls Gaxios to retry the request await backoff; - return { shouldRetry: true, config: err.config }; + return {shouldRetry: true, config: err.config}; } /** diff --git a/system-test/fixtures/sample/src/index.ts b/system-test/fixtures/sample/src/index.ts index 6dad45bd..e96f788e 100644 --- a/system-test/fixtures/sample/src/index.ts +++ b/system-test/fixtures/sample/src/index.ts @@ -12,10 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { request } from 'gaxios'; +import {request} from 'gaxios'; async function main() { await request({ - url: 'https://www.googleapis.com/discovery/v1/apis/' + url: 'https://www.googleapis.com/discovery/v1/apis/', }); } main(); diff --git a/system-test/fixtures/sample/webpack.config.js b/system-test/fixtures/sample/webpack.config.js index 4806fd2c..b3ced2ce 100644 --- a/system-test/fixtures/sample/webpack.config.js +++ b/system-test/fixtures/sample/webpack.config.js @@ -21,31 +21,31 @@ module.exports = { resolve: { extensions: ['.ts', '.js', '.json'], alias: { - '../../package.json': path.resolve(__dirname, 'package.json') - } + '../../package.json': path.resolve(__dirname, 'package.json'), + }, }, output: { filename: 'bundle.min.js', - path: path.resolve(__dirname, 'dist') + path: path.resolve(__dirname, 'dist'), }, node: { child_process: 'empty', fs: 'empty', - crypto: 'empty' + crypto: 'empty', }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader' + use: 'null-loader', }, { test: /\.ts$/, use: 'ts-loader', - exclude: /node_modules/ - } - ] + exclude: /node_modules/, + }, + ], }, mode: 'production', - plugins: [] + plugins: [], }; diff --git a/system-test/test.install.ts b/system-test/test.install.ts index be2599f6..6c54733d 100644 --- a/system-test/test.install.ts +++ b/system-test/test.install.ts @@ -16,16 +16,16 @@ import assert from 'assert'; import execa from 'execa'; import fs from 'fs'; import mv from 'mv'; -import { ncp } from 'ncp'; +import {ncp} from 'ncp'; import path from 'path'; import tmp from 'tmp'; -import { promisify } from 'util'; -import { describe, it, before, after } from 'mocha'; +import {promisify} from 'util'; +import {describe, it, before, after} from 'mocha'; const keep = false; const mvp = (promisify(mv) as {}) as (...args: string[]) => Promise; const ncpp = promisify(ncp); -const stagingDir = tmp.dirSync({ keep, unsafeCleanup: true }); +const stagingDir = tmp.dirSync({keep, unsafeCleanup: true}); const stagingPath = stagingDir.name; // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../../package.json'); @@ -42,14 +42,14 @@ describe('📦 pack and install', () => { await ncpp('system-test/fixtures/sample', `${stagingPath}/`); await execa('npm', ['install', '--unsafe-perm'], { cwd: `${stagingPath}/`, - stdio: 'inherit' + stdio: 'inherit', }); }); it('should run the sample', async () => { await execa('node', ['--throw-deprecation', 'build/src/index.js'], { cwd: `${stagingPath}/`, - stdio: 'inherit' + stdio: 'inherit', }); }); @@ -57,7 +57,7 @@ describe('📦 pack and install', () => { // we expect npm install is executed in the before hook await execa('npx', ['webpack'], { cwd: `${stagingPath}/`, - stdio: 'inherit' + stdio: 'inherit', }); const bundle = path.join(stagingPath, 'dist', 'bundle.min.js'); const stat = fs.statSync(bundle); diff --git a/test/test.getch.ts b/test/test.getch.ts index c5b8e03a..8ce0b338 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -15,7 +15,7 @@ import assert from 'assert'; import nock from 'nock'; import sinon from 'sinon'; import stream from 'stream'; -import { describe, it, afterEach } from 'mocha'; +import {describe, it, afterEach} from 'mocha'; import assertRejects = require('assert-rejects'); // eslint-disable-next-line @typescript-eslint/no-var-requires const HttpsProxyAgent = require('https-proxy-agent'); @@ -24,11 +24,11 @@ import { GaxiosError, request, GaxiosOptions, - GaxiosResponse + GaxiosResponse, } from '../src'; import qs from 'querystring'; import fs from 'fs'; -import { Blob } from 'node-fetch'; +import {Blob} from 'node-fetch'; nock.disableNetConnect(); @@ -51,7 +51,7 @@ describe('🚙 error handling', () => { const scope = nock(url) .get('/') .reply(500); - await assertRejects(request({ url }), (err: GaxiosError) => { + await assertRejects(request({url}), (err: GaxiosError) => { scope.done(); return err.code === '500'; }); @@ -63,8 +63,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .head('/') .reply(200); - const inst = new Gaxios({ method: 'HEAD' }); - const res = await inst.request({ url }); + const inst = new Gaxios({method: 'HEAD'}); + const res = await inst.request({url}); scope.done(); assert.strictEqual(res.config.method, 'HEAD'); }); @@ -73,8 +73,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/') .reply(200); - const inst = new Gaxios({ headers: { apple: 'juice' } }); - const res = await inst.request({ url, headers: { figgy: 'pudding' } }); + const inst = new Gaxios({headers: {apple: 'juice'}}); + const res = await inst.request({url, headers: {figgy: 'pudding'}}); scope.done(); assert.strictEqual(res.config.headers!.apple, 'juice'); assert.strictEqual(res.config.headers!.figgy, 'pudding'); @@ -84,8 +84,8 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/v1/mango') .reply(200, {}); - const inst = new Gaxios({ baseURL: `${url}/v1` }); - const res = await inst.request({ url: '/mango' }); + const inst = new Gaxios({baseURL: `${url}/v1`}); + const res = await inst.request({url: '/mango'}); scope.done(); assert.deepStrictEqual(res.data, {}); }); @@ -94,32 +94,32 @@ describe('🥁 configuration options', () => { const scope = nock(url) .get('/') .reply(304); - const res = await request({ url, validateStatus: () => true }); + const res = await request({url, validateStatus: () => true}); scope.done(); assert.strictEqual(res.status, 304); }); it('should allow setting maxContentLength', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); const maxContentLength = 1; - await assertRejects(request({ url, maxContentLength }), /over limit/); + await assertRejects(request({url, maxContentLength}), /over limit/); scope.done(); }); it('should support redirects by default', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scopes = [ nock(url) .get('/foo') .reply(200, body), nock(url) .get('/') - .reply(302, undefined, { location: '/foo' }) + .reply(302, undefined, {location: '/foo'}), ]; - const res = await request({ url }); + const res = await request({url}); scopes.forEach(x => x.done()); assert.deepStrictEqual(res.data, body); assert.strictEqual(res.request.responseURL, `${url}/foo`); @@ -128,31 +128,31 @@ describe('🥁 configuration options', () => { it('should support disabling redirects', async () => { const scope = nock(url) .get('/') - .reply(302, undefined, { location: '/foo' }); + .reply(302, undefined, {location: '/foo'}); const maxRedirects = 0; - await assertRejects(request({ url, maxRedirects }), /maximum redirect/); + await assertRejects(request({url, maxRedirects}), /maximum redirect/); scope.done(); }); it('should allow overriding the adapter', async () => { const response: GaxiosResponse = { - data: { hello: '🌎' }, + data: {hello: '🌎'}, config: {}, status: 200, statusText: 'OK', headers: {}, request: { - responseURL: url - } + responseURL: url, + }, }; const adapter = () => Promise.resolve(response); - const res = await request({ url, adapter }); + const res = await request({url, adapter}); assert.strictEqual(response, res); }); it('should encode URL parameters', async () => { const path = '/?james=kirk&montgomery=scott'; - const opts = { url: `${url}${path}` }; + const opts = {url: `${url}${path}`}; const scope = nock(url) .get(path) .reply(200, {}); @@ -163,7 +163,7 @@ describe('🥁 configuration options', () => { }); it('should encode parameters from the params option', async () => { - const opts = { url, params: { james: 'kirk', montgomery: 'scott' } }; + const opts = {url, params: {james: 'kirk', montgomery: 'scott'}}; const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) .get(path) @@ -177,7 +177,7 @@ describe('🥁 configuration options', () => { it('should merge URL parameters with the params option', async () => { const opts = { url: `${url}/?james=beckwith&montgomery=scott`, - params: { james: 'kirk' } + params: {james: 'kirk'}, }; const path = '/?james=kirk&montgomery=scott'; const scope = nock(url) @@ -191,14 +191,14 @@ describe('🥁 configuration options', () => { it('should allow overriding the param serializer', async () => { const qs = '?oh=HAI'; - const params = { james: 'kirk' }; + const params = {james: 'kirk'}; const opts: GaxiosOptions = { url, params, paramsSerializer: ps => { assert.strictEqual(JSON.stringify(params), JSON.stringify(ps)); return '?oh=HAI'; - } + }, }; const scope = nock(url) .get(`/${qs}`) @@ -210,11 +210,11 @@ describe('🥁 configuration options', () => { }); it('should return json by default', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url }); + const res = await request({url}); scope.done(); assert.deepStrictEqual(body, res.data); }); @@ -224,43 +224,43 @@ describe('🥁 configuration options', () => { .matchHeader('accept', 'application/json') .get('/') .reply(200, {}); - const res = await request({ url }); + const res = await request({url}); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should use an https proxy if asked nicely', async () => { - sandbox.stub(process, 'env').value({ https_proxy: 'https://fake.proxy' }); - const body = { hello: '🌎' }; + sandbox.stub(process, 'env').value({https_proxy: 'https://fake.proxy'}); + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url }); + const res = await request({url}); scope.done(); assert.deepStrictEqual(res.data, body); assert.ok(res.config.agent instanceof HttpsProxyAgent); }); it('should load the proxy from the cache', async () => { - sandbox.stub(process, 'env').value({ HTTPS_PROXY: 'https://fake.proxy' }); - const body = { hello: '🌎' }; + sandbox.stub(process, 'env').value({HTTPS_PROXY: 'https://fake.proxy'}); + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .twice() .reply(200, body); - const res1 = await request({ url }); + const res1 = await request({url}); const agent = res1.config.agent; - const res2 = await request({ url }); + const res2 = await request({url}); assert.strictEqual(agent, res2.config.agent); scope.done(); }); it('should include the request data in the response config', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .post('/', body) .reply(200); - const res = await request({ url, method: 'POST', data: body }); + const res = await request({url, method: 'POST', data: body}); scope.done(); assert.deepStrictEqual(res.config.data, body); }); @@ -274,13 +274,13 @@ describe('🎏 data handling', () => { const scope = nock(url) .post('/', contents) .reply(200, {}); - const res = await request({ url, method: 'POST', data: body }); + const res = await request({url, method: 'POST', data: body}); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should accept a string in the request data', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const encoded = qs.stringify(body); const scope = nock(url) .matchHeader('content-type', 'application/x-www-form-urlencoded') @@ -290,14 +290,14 @@ describe('🎏 data handling', () => { url, method: 'POST', data: encoded, - headers: { 'content-type': 'application/x-www-form-urlencoded' } + headers: {'content-type': 'application/x-www-form-urlencoded'}, }); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should set content-type for object request', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .matchHeader('content-type', 'application/json') .post('/', JSON.stringify(body)) @@ -305,30 +305,30 @@ describe('🎏 data handling', () => { const res = await request({ url, method: 'POST', - data: body + data: body, }); scope.done(); assert.deepStrictEqual(res.data, {}); }); it('should return stream if asked nicely', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url, responseType: 'stream' }); + const res = await request({url, responseType: 'stream'}); scope.done(); assert(res.data instanceof stream.Readable); }); it('should return an ArrayBuffer if asked nicely', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); const res = await request({ url, - responseType: 'arraybuffer' + responseType: 'arraybuffer', }); scope.done(); assert(res.data instanceof ArrayBuffer); @@ -339,11 +339,11 @@ describe('🎏 data handling', () => { }); it('should return a blob if asked nicely', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url, responseType: 'blob' }); + const res = await request({url, responseType: 'blob'}); scope.done(); assert.ok(res.data); }); @@ -353,17 +353,17 @@ describe('🎏 data handling', () => { const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url, responseType: 'text' }); + const res = await request({url, responseType: 'text'}); scope.done(); assert.strictEqual(res.data, body); }); it('should return status text', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const res = await request({ url }); + const res = await request({url}); scope.done(); assert.ok(res.data); assert.strictEqual(res.statusText, 'OK'); @@ -377,11 +377,11 @@ describe('🍂 defaults & instances', () => { }); it('should allow passing empty options', async () => { - const body = { hello: '🌎' }; + const body = {hello: '🌎'}; const scope = nock(url) .get('/') .reply(200, body); - const gax = new Gaxios({ url }); + const gax = new Gaxios({url}); const res = await gax.request(); scope.done(); assert.deepStrictEqual(res.data, body); diff --git a/test/test.index.ts b/test/test.index.ts index 5be639d7..ac22903f 100644 --- a/test/test.index.ts +++ b/test/test.index.ts @@ -12,7 +12,7 @@ // limitations under the License. import assert from 'assert'; -import { describe, it } from 'mocha'; +import {describe, it} from 'mocha'; import * as main from '../src/index'; describe('📝 main exports', () => { diff --git a/test/test.retry.ts b/test/test.retry.ts index 43b23a0a..88f61ed1 100644 --- a/test/test.retry.ts +++ b/test/test.retry.ts @@ -11,11 +11,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { AbortController } from 'abort-controller'; +import {AbortController} from 'abort-controller'; import assert from 'assert'; import nock from 'nock'; -import { describe, it, afterEach } from 'mocha'; -import { Gaxios, GaxiosError, GaxiosOptions, request } from '../src'; +import {describe, it, afterEach} from 'mocha'; +import {Gaxios, GaxiosError, GaxiosOptions, request} from '../src'; import assertRejects = require('assert-rejects'); nock.disableNetConnect(); @@ -40,7 +40,7 @@ describe('🛸 retry & exponential backoff', () => { .get('/') .times(4) .reply(500); - await assertRejects(request({ url, retry: true }), (e: Error) => { + await assertRejects(request({url, retry: true}), (e: Error) => { scope.done(); const config = getConfig(e); if (!config) { @@ -56,7 +56,7 @@ describe('🛸 retry & exponential backoff', () => { const expectedStatusCodes = [ [100, 199], [429, 429], - [500, 599] + [500, 599], ]; const statusCodesToRetry = config!.statusCodesToRetry!; for (let i = 0; i < statusCodesToRetry.length; i++) { @@ -70,18 +70,18 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry on 500 on the main export', async () => { - const body = { buttered: '🥖' }; + const body = {buttered: '🥖'}; const scopes = [ nock(url) .get('/') .reply(500), nock(url) .get('/') - .reply(200, body) + .reply(200, body), ]; const res = await request({ url, - retry: true + retry: true, }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); @@ -92,7 +92,7 @@ describe('🛸 retry & exponential backoff', () => { .post('/') .reply(500); await assertRejects( - request({ url, method: 'POST', retry: true }), + request({url, method: 'POST', retry: true}), (e: Error) => { const config = getConfig(e); return config!.currentRetryAttempt === 0; @@ -107,7 +107,7 @@ describe('🛸 retry & exponential backoff', () => { method: 'GET', url: 'https://google.com', signal: ac.signal, - retryConfig: { retry: 10, noResponseRetries: 10 } + retryConfig: {retry: 10, noResponseRetries: 10}, }; const req = request(config); ac.abort(); @@ -121,7 +121,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry at least the configured number of times', async () => { - const body = { dippy: '🥚' }; + const body = {dippy: '🥚'}; const scopes = [ nock(url) .get('/') @@ -129,9 +129,9 @@ describe('🛸 retry & exponential backoff', () => { .reply(500), nock(url) .get('/') - .reply(200, body) + .reply(200, body), ]; - const cfg = { url, retryConfig: { retry: 4 } }; + const cfg = {url, retryConfig: {retry: 4}}; const res = await request(cfg); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); @@ -142,7 +142,7 @@ describe('🛸 retry & exponential backoff', () => { .get('/') .twice() .reply(500); - const cfg = { url, retryConfig: { retry: 1 } }; + const cfg = {url, retryConfig: {retry: 1}}; await assertRejects(request(cfg), (e: Error) => { return getConfig(e)!.currentRetryAttempt === 1; }); @@ -153,7 +153,7 @@ describe('🛸 retry & exponential backoff', () => { const scope = nock(url) .get('/') .reply(404); - await assertRejects(request({ url, retry: true }), (e: Error) => { + await assertRejects(request({url, retry: true}), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; }); @@ -161,7 +161,7 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retain the baseUrl on retry', async () => { - const body = { pumpkin: '🥧' }; + const body = {pumpkin: '🥧'}; const url = '/path'; const baseUrl = 'http://example.com'; const scope = nock(baseUrl) @@ -170,11 +170,11 @@ describe('🛸 retry & exponential backoff', () => { .get(url) .reply(200, body); const gaxios = new Gaxios({ - baseUrl + baseUrl, }); const res = await gaxios.request({ url, - retry: true + retry: true, }); assert.deepStrictEqual(res.data, body); scope.done(); @@ -184,7 +184,7 @@ describe('🛸 retry & exponential backoff', () => { const scope = nock(url) .get('/') .reply(500); - const cfg = { url, retryConfig: { retry: 0 } }; + const cfg = {url, retryConfig: {retry: 0}}; await assertRejects(request(cfg), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; @@ -193,14 +193,14 @@ describe('🛸 retry & exponential backoff', () => { }); it('should notify on retry attempts', async () => { - const body = { buttered: '🥖' }; + const body = {buttered: '🥖'}; const scopes = [ nock(url) .get('/') .reply(500), nock(url) .get('/') - .reply(200, body) + .reply(200, body), ]; let flipped = false; const config: GaxiosOptions = { @@ -210,8 +210,8 @@ describe('🛸 retry & exponential backoff', () => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; - } - } + }, + }, }; await request(config); assert.strictEqual(flipped, true); @@ -219,14 +219,14 @@ describe('🛸 retry & exponential backoff', () => { }); it('accepts async onRetryAttempt handler', async () => { - const body = { buttered: '🥖' }; + const body = {buttered: '🥖'}; const scopes = [ nock(url) .get('/') .reply(500), nock(url) .get('/') - .reply(200, body) + .reply(200, body), ]; let flipped = false; const config: GaxiosOptions = { @@ -236,8 +236,8 @@ describe('🛸 retry & exponential backoff', () => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; - } - } + }, + }, }; await request(config); assert.strictEqual(flipped, true); @@ -253,8 +253,8 @@ describe('🛸 retry & exponential backoff', () => { retryConfig: { shouldRetry: () => { return false; - } - } + }, + }, }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); @@ -272,8 +272,8 @@ describe('🛸 retry & exponential backoff', () => { retryConfig: { shouldRetry: async () => { return false; - } - } + }, + }, }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); @@ -283,31 +283,31 @@ describe('🛸 retry & exponential backoff', () => { }); it('should retry on ENOTFOUND', async () => { - const body = { spicy: '🌮' }; + const body = {spicy: '🌮'}; const scopes = [ nock(url) .get('/') - .replyWithError({ code: 'ENOTFOUND' }), + .replyWithError({code: 'ENOTFOUND'}), nock(url) .get('/') - .reply(200, body) + .reply(200, body), ]; - const res = await request({ url, retry: true }); + const res = await request({url, retry: true}); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); it('should retry on ETIMEDOUT', async () => { - const body = { sizzling: '🥓' }; + const body = {sizzling: '🥓'}; const scopes = [ nock(url) .get('/') - .replyWithError({ code: 'ETIMEDOUT' }), + .replyWithError({code: 'ETIMEDOUT'}), nock(url) .get('/') - .reply(200, body) + .reply(200, body), ]; - const res = await request({ url, retry: true }); + const res = await request({url, retry: true}); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); @@ -315,8 +315,8 @@ describe('🛸 retry & exponential backoff', () => { it('should allow configuring noResponseRetries', async () => { const scope = nock(url) .get('/') - .replyWithError({ code: 'ETIMEDOUT' }); - const config = { url, retryConfig: { noResponseRetries: 0 } }; + .replyWithError({code: 'ETIMEDOUT'}); + const config = {url, retryConfig: {noResponseRetries: 0}}; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; diff --git a/webpack-tests.config.js b/webpack-tests.config.js index 8642393d..d903551d 100644 --- a/webpack-tests.config.js +++ b/webpack-tests.config.js @@ -20,27 +20,27 @@ module.exports = { resolve: { extensions: ['.ts', '.js', '.json'], alias: { - '../../package.json': path.resolve(__dirname, 'package.json') - } + '../../package.json': path.resolve(__dirname, 'package.json'), + }, }, node: { child_process: 'empty', fs: 'empty', - crypto: 'empty' + crypto: 'empty', }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader' + use: 'null-loader', }, { test: /\.ts$/, use: 'ts-loader', - exclude: /node_modules/ - } - ] + exclude: /node_modules/, + }, + ], }, mode: 'production', - plugins: [] + plugins: [], }; diff --git a/webpack.config.js b/webpack.config.js index 20812cd3..012df506 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -21,32 +21,32 @@ module.exports = { resolve: { extensions: ['.ts', '.js', '.json'], alias: { - '../../package.json': path.resolve(__dirname, 'package.json') - } + '../../package.json': path.resolve(__dirname, 'package.json'), + }, }, output: { library: 'gaxios', filename: 'gaxios.min.js', - path: path.resolve(__dirname, 'dist') + path: path.resolve(__dirname, 'dist'), }, node: { child_process: 'empty', fs: 'empty', - crypto: 'empty' + crypto: 'empty', }, module: { rules: [ { test: /node_modules\/https-proxy-agent\//, - use: 'null-loader' + use: 'null-loader', }, { test: /\.ts$/, use: 'ts-loader', - exclude: /node_modules/ - } - ] + exclude: /node_modules/, + }, + ], }, mode: 'production', - plugins: [] + plugins: [], }; From d415ed2f5c9e8e01b9ee8c537c8d4266855cad62 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Tue, 4 Feb 2020 09:12:03 -0800 Subject: [PATCH 9/9] lic --- .prettierrc.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.prettierrc.js b/.prettierrc.js index ff154833..08cba377 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -1,3 +1,17 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + module.exports = { ...require('gts/.prettierrc.json') }