New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@bbc/http-transport

Package Overview
Dependencies
Maintainers
19
Versions
60
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bbc/http-transport - npm Package Compare versions

Comparing version 3.5.7-0 to 3.5.7-1

test/middleware/asJson.js

32

docs.md

@@ -230,5 +230,33 @@ # HttpTransport

#### TODO: Client Setup
#### Callback support
HttpTransport does not support callbacks. However, to integrate with legacy code, use the [callback adapter](https://github.com/bbc/http-transport-callbacks)
#### Setting default behaviour of underlying http transport
Make a HTTP GET request by passing default configuration to RequestTransport, and supplying the configured RequestTransport to `.createClient`
```js
const url = 'http://example.com/';
const HttpTransport = require('@bbc/http-transport');
const defaultConfig = {
agentOpts: { // Here you can pass in any options for the https agent https://nodejs.org/api/https.html#class-httpsagent
keepAlive: true,
maxSockets: 1000
},
defaults: {
timeout: 2000
compress: true // support gzip/deflate content encoding. false to disable
}
};
const requestTransport = new HttpTransport.RequestTransport(defaultConfig);
const res = await HttpTransport.createClient(requestTransport);
.get(url)
.asResponse();
if (res.statusCode === 200) {
console.log(res.body);
}
```

43

index.js

@@ -1,21 +0,24 @@

'use strict';
import HttpTransportBuilder from './lib/builder.js';
import DefaultTransport from './lib/transport/node-fetch.js';
import transport from './lib/transport/transport.js';
import context from './lib/context.js';
import toJson from './lib/middleware/asJson.js';
import logger from './lib/middleware/logger.js';
import setContextProperty from './lib/middleware/setContextProperty.js';
const HttpTransportBuilder = require('./lib/builder');
const DefaultTransport = require('./lib/transport/node-fetch');
module.exports.defaultTransport = DefaultTransport;
module.exports.FetchTransport = DefaultTransport;
module.exports.builder = HttpTransportBuilder;
module.exports.transport = require('./lib/transport/transport');
module.exports.context = require('./lib/context');
module.exports.toJson = require('./lib/middleware/asJson');
module.exports.logger = require('./lib/middleware/logger');
module.exports.setContextProperty = require('./lib/middleware/setContextProperty');
module.exports.createClient = () => {
return new HttpTransportBuilder(new DefaultTransport()).createClient();
};
module.exports.createBuilder = (transport) => {
return new HttpTransportBuilder(transport || new DefaultTransport());
};
export default {
defaultTransport: DefaultTransport,
FetchTransport: DefaultTransport,
builder: HttpTransportBuilder,
transport,
context,
toJson,
logger,
setContextProperty,
createClient: () => {
return new HttpTransportBuilder(new DefaultTransport()).createClient();
},
createBuilder: (transport) => {
return new HttpTransportBuilder(transport || new DefaultTransport());
}
}

@@ -1,3 +0,1 @@

'use strict';
function isMethod(propertyName, value) {

@@ -7,3 +5,3 @@ return propertyName !== 'constructor' && typeof value === 'function';

module.exports = (obj) => {
export default (obj) => {
const propertyNames = Object.getOwnPropertyNames(obj.constructor.prototype);

@@ -10,0 +8,0 @@ propertyNames.forEach((propertyName) => {

@@ -1,7 +0,4 @@

'use strict';
import _ from 'lodash';
import HttpTransportClient from './client.js';
const _ = require('lodash');
const HttpTransportClient = require('./client');
function validatePlugin(plugin) {

@@ -93,3 +90,2 @@ if (typeof plugin !== 'function') throw new TypeError('Plugin is not a function');

*
* @param {function} fn - a global plugin
* @return a HttpTransport instance

@@ -105,2 +101,2 @@ * @example

module.exports = HttpTransportBuilder;
export default HttpTransportBuilder;

@@ -1,8 +0,6 @@

'use strict';
import compose from 'koa-compose';
import context from './context.js';
import rejectedPromise from './rejectedPromise.js';
import bind from './bind.js';
const compose = require('koa-compose');
const context = require('./context');
const rejectedPromise = require('./rejectedPromise');
const bind = require('./bind');
/** Core client */

@@ -44,3 +42,3 @@ class HttpTransportClient {

*
* @param {string} url
* @param {string} baseUrl
* @return a HttpTransport instance

@@ -62,3 +60,3 @@ * @example

*
* @param {string} url
* @param {string} baseUrl
* @param {object} request body

@@ -70,10 +68,10 @@ * @return a HttpTransport instance

* const response = await httpTransport.createClient()
* .post(url, requestBody)
* .post(baseUrl, requestBody)
* .asResponse();
*/
post(url, body) {
post(baseUrl, body) {
this._ctx.req
.method('POST')
.body(body)
.baseUrl(url);
.baseUrl(baseUrl);
return this;

@@ -85,3 +83,3 @@ }

*
* @param {string} url
* @param {string} baseUrl
* @param {object} request body

@@ -93,10 +91,10 @@ * @return a HttpTransport instance

* const response = await httpTransport.createClient()
* .put(url, requestBody)
* .put(baseUrl, requestBody)
* .asResponse();
*/
put(url, body) {
put(baseUrl, body) {
this._ctx.req
.method('PUT')
.body(body)
.baseUrl(url);
.baseUrl(baseUrl);
return this;

@@ -108,4 +106,3 @@ }

*
* @param {string} url
* @param {object} request body
* @param {string} baseUrl
* @return a HttpTransport instance

@@ -116,7 +113,7 @@ * @example

* const response = await httpTransport.createClient()
* .delete(url)
* .delete(baseUrl)
* .asResponse();
*/
delete(url) {
this._ctx.req.method('DELETE').baseUrl(url);
delete(baseUrl) {
this._ctx.req.method('DELETE').baseUrl(baseUrl);
return this;

@@ -128,3 +125,3 @@ }

*
* @param {string} url
* @param {string} baseUrl
* @param {object} request body

@@ -136,10 +133,10 @@ * @return a HttpTransport instance

* const response = await httpTransport.createClient()
* .put(url, requestBody)
* .put(baseUrl, requestBody)
* .asResponse();
*/
patch(url, body) {
patch(baseUrl, body) {
this._ctx.req
.method('PATCH')
.body(body)
.baseUrl(url);
.baseUrl(baseUrl);
return this;

@@ -151,3 +148,3 @@ }

*
* @param {string} url
* @param {string} baseUrl
* @return a HttpTransport instance

@@ -158,7 +155,7 @@ * @example

* const response = await httpTransport.createClient()
* .head(url)
* .head(baseUrl)
* .asResponse();
*/
head(url) {
this._ctx.req.method('HEAD').baseUrl(url);
head(baseUrl) {
this._ctx.req.method('HEAD').baseUrl(baseUrl);
return this;

@@ -216,3 +213,3 @@ }

*
* @param {integer} timeout - timeout in seconds
* @param {integer} time - timeout in seconds
* @return a HttpTransport instance

@@ -226,4 +223,4 @@ * @example

*/
timeout(secs) {
this._ctx.req.timeout(secs);
timeout(time) {
this._ctx.req.timeout(time);
return this;

@@ -235,3 +232,3 @@ }

*
* @param {integer} timeout - number of times to retry a failed request
* @param {integer} retries - number of times to retry a failed request
* @return a HttpTransport instance

@@ -253,3 +250,3 @@ * @example

*
* @param {integer} timeout - number of ms to wait between retries (default: 100)
* @param {integer} delay - number of ms to wait between retries (default: 100)
* @return a HttpTransport instance

@@ -264,4 +261,4 @@ * @example

*/
retryDelay(ms) {
this._ctx.retryDelay = ms;
retryDelay(delay) {
this._ctx.retryDelay = delay;
return this;

@@ -274,3 +271,4 @@ }

* @return a Promise. If the Promise fulfils,
* the fulfilment value is the response body, as a string by default.
* the fulfilment value is the response body. If the content-type response header contains 'json' or 'text',
* then the body type will be json or text respectively. Otherwise, the body will not be altered.
* @example

@@ -398,2 +396,2 @@ * const httpTransport = require('@bbc/http-transport');

module.exports = HttpTransportClient;
export default HttpTransportClient;

@@ -1,10 +0,11 @@

'use strict';
import Request from './request.js';
import Response from './response.js';
import { readFile } from 'fs/promises';
const { name, version } = JSON.parse(
await readFile(new URL('../package.json', import.meta.url))
);
const Request = require('./request');
const Response = require('./response');
const packageInfo = require('../package');
const RETRIES = 0;
const RETRY_DELAY = 100;
const USER_AGENT = `${packageInfo.name}/${packageInfo.version}`;
const USER_AGENT = `${name}/${version}`;

@@ -48,2 +49,2 @@ class Context {

module.exports = Context;
export default Context;

@@ -1,3 +0,1 @@

'use strict';
const jsonRegex = /^application\/([a-z0-9-+]+)?json/;

@@ -15,3 +13,3 @@

module.exports = (opts) => {
export default (opts) => {
opts = opts || {};

@@ -18,0 +16,0 @@ const throwOnConflict = opts.throwOnConflict;

@@ -1,3 +0,1 @@

'use strict';
function isRetry(ctx) {

@@ -13,3 +11,3 @@ const attempts = ctx.retryAttempts || [];

function hasElapsedTime(ctx) {
return !!ctx.res?.elapsedTime;
return ctx.res?.elapsedTime !== undefined;
}

@@ -37,3 +35,3 @@

module.exports = (customLogger) => {
export default (customLogger) => {
const logger = customLogger || console;

@@ -40,0 +38,0 @@

@@ -1,6 +0,4 @@

'use strict';
import _ from 'lodash';
const _ = require('lodash');
module.exports = (opts, path) => {
export default (opts, path) => {
return (ctx, next) => {

@@ -7,0 +5,0 @@ _.set(ctx, path, opts);

@@ -1,4 +0,2 @@

'use strict';
module.exports = (timeInMs) => {
export default (timeInMs) => {
return (reason) => {

@@ -5,0 +3,0 @@ return new Promise((resolve, reject) => {

@@ -1,5 +0,3 @@

'use strict';
import qs from 'qs';
const qs = require('qs');
class Request {

@@ -103,2 +101,2 @@ constructor() {

module.exports = Request;
export default Request;

@@ -1,3 +0,1 @@

'use strict';
const REQUIRED_PROPERTIES = [

@@ -67,2 +65,2 @@ 'url',

module.exports = Response;
export default Response;

@@ -1,8 +0,6 @@

'use strict';
import https from 'node:https';
import http from 'node:http';
import fetch from 'node-fetch';
import Transport from './transport.js';
const Transport = require('./transport');
const https = require('node:https');
// eslint-disable-next-line func-style
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const REQUIRED_PROPERTIES = [

@@ -20,3 +18,4 @@ 'body',

if (options?.agentOpts) {
this._agent = new https.Agent(options.agentOpts);
this._httpAgent = new http.Agent(options.agentOpts);
this._httpsAgent = new https.Agent(options.agentOpts);
}

@@ -35,2 +34,3 @@

opts.compress = this.defaults?.compress;
if (opts.time === undefined) opts.time = true;

@@ -84,3 +84,3 @@ if (req.hasQueries()) opts.searchParams = new URLSearchParams(req.getQueries());

method,
agent: this._agent,
agent: new URL(ctx.req.getUrl()).protocol === 'http:' ? this._httpAgent : this._httpsAgent,
signal: controller.signal

@@ -96,3 +96,3 @@ };

fetchedResponse = await this._fetch(ctx.req.getUrl(), opts);
fetchedResponse.elapsedTime = Math.round(Number(process.hrtime.bigint() - start) / 1e6); // nanoseconds to milliseconds
fetchedResponse.elapsedTime = opts.time ? Math.round(Number(process.hrtime.bigint() - start) / 1e6) : undefined; // nanoseconds to milliseconds
} catch (err) {

@@ -112,2 +112,2 @@ if (err.name === 'AbortError') {

module.exports = FetchTransport;
export default FetchTransport;

@@ -1,4 +0,2 @@

'use strict';
class Transport {
export default class Transport {
toError(err, ctx) {

@@ -28,3 +26,1 @@ return this.createError(err, ctx);

}
module.exports = Transport;
{
"name": "@bbc/http-transport",
"version": "3.5.7-0",
"version": "3.5.7-1",
"description": "A flexible, modular REST client built for ease-of-use and resilience.",
"main": "index.js",
"exports": "./index.js",
"types": "index.d.ts",
"type": "module",
"scripts": {

@@ -51,3 +52,2 @@ "test": "mocha",

"dependencies": {
"@types/request": "^2.47.1",
"koa-compose": "^4.0.0",

@@ -65,3 +65,4 @@ "lodash": "^4.17.4",

"parserOptions": {
"ecmaVersion": "latest"
"ecmaVersion": "latest",
"sourceType": "module"
},

@@ -68,0 +69,0 @@ "rules": {

@@ -67,3 +67,3 @@

## Opting Out
If you don't want to type your plugin, simply use `any` as the type. This is not recomemnded though as it means all plugins later in the chain will loose the types too, because they have no idea what changes were made.
If you don't want to type your plugin, simply use `any` as the type. This is not recommended though as it means all plugins later in the chain will lose the types too, because they have no idea what changes were made.

@@ -70,0 +70,0 @@ ```ts

@@ -1,15 +0,17 @@

'use strict';
import chai from 'chai';
import nock from 'nock';
import sinon from 'sinon';
import { readFile } from 'fs/promises';
const assert = require('chai').assert;
const nock = require('nock');
const sinon = require('sinon');
const HttpTransport = require('..');
const Transport = require('../lib/transport/transport');
const toJson = require('../lib/middleware/asJson');
const setContextProperty = require('../lib/middleware/setContextProperty');
const log = require('../lib/middleware/logger');
const packageInfo = require('../package');
const toError = require('./toError');
import HttpTransport from '../index.js';
import Transport from '../lib/transport/transport.js';
import toJson from '../lib/middleware/asJson.js';
import setContextProperty from '../lib/middleware/setContextProperty.js';
import log from '../lib/middleware/logger.js';
import toError from './toError.js';
const sandbox = sinon.sandbox.create();
const { name, version } = JSON.parse(
await readFile(new URL('../package.json', import.meta.url))
);
const assert = chai.assert;

@@ -87,3 +89,3 @@ const url = 'http://www.example.com/';

reqheaders: {
'User-Agent': `${packageInfo.name}/${packageInfo.version}`
'User-Agent': `${name}/${version}`
}

@@ -382,3 +384,3 @@ })

const HeaderValue = `${packageInfo.name}/${packageInfo.version}`;
const HeaderValue = `${name}/${version}`;
nock(host, {

@@ -446,8 +448,8 @@ reqheaders: {

it('ignores empty query objects', async () => {
const res = await HttpTransport.createClient()
const body = await HttpTransport.createClient()
.query({})
.get(url)
.asResponse();
.asBody();
assert.deepEqual(res.body, simpleResponseBody);
assert.deepEqual(body, simpleResponseBody);
});

@@ -559,3 +561,3 @@ });

const res = client
const res = await client
.use(setContextProperty({

@@ -562,0 +564,0 @@ time: false

@@ -1,6 +0,4 @@

'use strict';
import assert from 'assert';
import Context from '../lib/context.js';
const assert = require('assert');
const Context = require('../lib/context');
describe('Context', () => {

@@ -7,0 +5,0 @@ it('defaults retries to an empty array', () => {

@@ -1,6 +0,4 @@

'use strict';
import assert from 'assert';
import Request from '../lib/request.js';
const assert = require('assert');
const Request = require('../lib/request');
const HOST = 'https://example.com';

@@ -7,0 +5,0 @@

@@ -1,6 +0,4 @@

'use strict';
import assert from 'assert';
import Response from '../lib/response.js';
const assert = require('assert');
const Response = require('../lib/response');
describe('Response', () => {

@@ -7,0 +5,0 @@ it('creates response from static factory', () => {

@@ -1,3 +0,1 @@

'use strict';
function toError() {

@@ -16,2 +14,2 @@ return async (ctx, next) => {

module.exports = toError;
export default toError;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc