Détail du package

@studio/json-request

javascript-studio11.5kMIT4.0.0

A tiny Node HTTP(S) request wrapper, for JSON requests and responses

http, https, json, request

readme

Studio JSON Request

📡 A tiny Node HTTP(S) request wrapper for JSON APIs.

  • Transparent JSON request / response handling
  • Timeout support
  • Status code validation and default validation for 2xx responses
  • Follows redirects, but only once
  • Unified error handling with status codes
  • Consistent logging with Studio Log

Usage

const request = require('@studio/json-request');

request({
  method: 'POST',
  hostname: 'some-host',
  path: '/some-path',
  timeout: 5000
}, { some: 'payload' }, (err, data, res) => {
  // ...
});

API

  • request(options[, data], callback): Creates a new HTTPS request, passing the options to Node http.request, except for these properties:
    • protocol: The protocol to use. Must be either "http:" or "https:". Defaults to "https:".
    • timeout: The number of milliseconds after which the request should time out, causing en E_TIMEOUT error.
    • expect: The expected status code(s). This can be a number or an array of numbers.
    • stream: If true, the callback is invoked with (null, res) once the header was retrieved to allow to stream the response.
    • log: A parent logger to use for the "Request" logger.

Behavior

  • If the timeout option is specified, a timer is installed which will abort the request and invoke the callback with an error.
  • If the expect option is specified, it validates the response HTTP status code. If it's a number the status code has to equal that number. If an array is given, any number in the array is accepted. If the option is not given, the request will fail for non 2xx status codes.
  • If the stream option is specified, the response is returned immediately after the status code was checked. No further response processing is done by this library. It is the callers responsibility to consume the response.
  • If data is given, it is stringified and passed as the request body and the request is sent. The Content-Type header is set to application/json, unless this header was already provided. The Content-Length is set to the request body length.
  • If data is set to null, the request is sent without a body.
  • If data is omitted, the request object is returned and it's the callers responsibility to invoke req.end() to complete the request.

Callback

The callback is invoked with (err, data, response).

  • err: An error object or null. The error will have a code property with these possible string values:
    • E_TIMEOUT: The request timed out.
    • E_EXPECT: The response status code does not match the expectation. The statusCode property on the error object is set to the response status code.
    • E_JSON: Could not parse the response body as JSON. In this case data is the raw body.
    • E_ERROR: If an error event was thrown.
  • data: The parsed response data, or if it could not be parsed the raw body.
  • response: The response object.

Logging

Every request produces a log entry when the response was processed with this data:

  • request:
    • protocol: The protocol used
    • method: The request method used
    • host: The host name
    • path: The path
    • headers: The request headers, if any
    • port: The port, if specified
    • body: The request body, if given
  • response:
    • statusCode: The response status code
    • headers: The response headers
    • body: The response body, if available
  • ms_head: The time it took to receive the response header
  • ms_body: The time it took to receive the response body

If stream was set, the log entry is produced once the response header was received without the response and ms_body properties, and another log entry is produced when the response body was received with ms_body.

To remove confidential information from the logs, you can use Studio Log X. For example, you can X-out all Authorization headers from the logs like this:

const logger = require('@studio/log');
const Console = require('@studio/log-format/console');
const logX = require('@studio/log-x');

// Install filter on namespace "Request":
logger
  .pipe(logX('request.headers.Authorization'))
  .pipe(new Console());

Related modules

License

MIT

Made with ❤️ on 🌍

changelog

Changes

4.0.0

  • 💥 71e18e1 Drop node 12 and 14, support node 18 and 20
  • 💥 65e3d9b Use Studio Fail
  • 💥 ddbd041 Destroy request instead of abort
  • 🍏 9ce212a Add types
  • 0d510aa Upgrade Studio Changes
  • df96e6b Update Studio Log and Studio Log X
  • 4d1de86 Upgrade eslint-config and eslint and use URL
  • 57bb923 Replace sinon spy and stub with fakes
  • f23a336 Replace assert and sinon with referee-sinon
  • 2def327 Upgrade mocha to v10

Released by Maximilian Antoni on 2024-01-30.

3.0.1

  • 🐛 f8e06d4 Log cause on request and response error
  • 🛡 11c3a34 Bump lodash from 4.17.10 to 4.17.19 (dependabot[bot])
  • 9eab585 Configure GitHub actions
  • 0739619 Upgrade sinon
  • 12ce96f Upgrade mocha
  • 07ba17a Upgrade eslint
  • 7c5ba13 Update Studio ESLint Config
  • 9a1fbc0 Upgrade Studio Changes to v2
  • a8e06e0 Add .gitignore

Released by Maximilian Antoni on 2021-05-25.

3.0.0

  • 💥 685b9ab BREAKING: Use Studio Log v2
  • 📚 9d827ee Change example code for Studio Log v2 changes
  • 404184f Use Studio Changes --commits option

2.2.0

  • 🍏 Add child logger support and document logging
  • 📚 Add feature list
  • 📚 Document how to x-out confidential information

2.1.1

  • ✨ Improve error handing and logging

2.1.0

  • 🍏 Expose response status code on E_EXPECT error

2.0.3

  • ✨ Log parsed JSON response body

2.0.2

  • 📚 Improve documentation

2.0.1

  • 📚 Add related modules section
  • ✨ Add keywords, description, homepage and repository
  • ✨ Add MIT license
  • ✨ Add package-lock.json

2.0.0

  • ✨ Breaking: Reduce API to single function

    Removed http_request and https_request and instead support an additional protocol option.

1.4.2

  • 🙈 Support Node 4

1.4.1

  • 🐛 Fix log.finished -> log.finish

1.4.0

  • Use @studio/log
  • Include body in error log if parse failed

1.3.1

  • Always log body on unexpected response

1.3.0

  • Support sending streams

1.2.3

  • Print text response for unexpected response
  • Missing colon in logs if protocol is http

1.2.2

  • Log request / response header and body in error cases

1.2.1

  • Add console logs until we have a real logger

1.2.0

Follow redirects if the expect array contains 302 and a location header is in the response. A second redirect will not be followed and result in an E_EXPECT error.

1.1.0

  • Add stream option to yield the raw response

    This option is intended for stream processing or if the response is expected to contain non-JSON data.

  • Validate the statusCode before consuming the body

  • Fix timeout edge cases

1.0.1

  • Parse JSON if content-type includes charset

1.0.0

  • Inception