npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

swagger-json-output

v1.1.3

Published

Used with [`swagger-node-runner`][1], this is a cherry picked pipe fitting to handle yielded errors and/or yielded results to JSON.

Downloads

11

Readme

#swagger-json-output

Used with swagger-node-runner, this is a cherry picked pipe fitting to handle yielded errors and/or yielded results to JSON.

This fitting is useful only for projects that are using swagger-node-runner version 0.7 or above.

Important

Generally, the fitting sets for swagger-node-runner the ctx.statusCode and ctx.output based on ctx.error and ctx.output that it is provided with, which in turn are used by swagger-node-runner it to emit the response, as seen at the _finish handler of the underlying connect_middleware.

This pipe works with error, statusCode, and output that it finds on the context that it's given. As a result, it cannot work with data passed to response.write nor to response.writeHead.

In order for the fitting to work as expected user controllers should communicate with the runner using the context object and the value yielded to the next callback, and should not use not use the response object to write to the response or response headers.

If you cannot work this way, this fitting is not for you :(

We recommend to work with controllerInterface: pipe.

installing

npm install swagger-json-output --save

Using it as an onError handler

Pass it as onError handler to your main pipe.

If you're using the template created by swagger cli:

  1. Find the definition of your main pipe
  2. replace
      - onError: json_error_handler

with

      - onError: swagger-json-output

Using it as output JSON formatter

  1. add this fitting as a last step to your main pipe:
      - swagger-json-output

How does it work

Whenever an error is thrown in any of the fitting in that pipe, bagpipes captures the error as context.error and passes the cotnext to this fitting.

Regardless to errors, user controllers are expected to pass the response body as 2nd argument to the next callback. This value is passed by bagpipes to this fitting as context.output.

As this fitting finishes, wether by error or not - the context has:

  • a defined statusCode
  • a defined response content-type, matching Accept http header and the produces defined on the operation.
  • a well-formatted body (currently guaranteed only for application/json)

Flow:

  • In case of error, make sure statusCode is escalated to >= 400 by using the first code that is indeed set and is >= 400:
    • context.statusCode
    • context.response.statusCode
    • context.error.statusCode
    • use 500 as default error code
  • assure that the content-type of the response matches the content-type defined by the produces section of the openapi-spec of the processed operation.
  • ** In case of error**:
    • creates context.output as a serializable clone of the error, making sure the clone will include the err.message and if includeErrStack is truthful - err.stack as well, together with any enumerable property that the error is decorated with.
  • if ctx._preOutput handler is found - execute it, and pass it the context as argument. The handler is executed synchronously (no callback involved).
  • if the content-type of the response should be JSON - it formats the
    output as JSON. Whenever the serialization fails
    • the response code escalates to 500 response body will be a beautified JSON object which includes:
      • message: unable to stringify body properly,

      • stringifyErr: the stringification error message

      • bodyInspect: Array lines resulted by util.inspecting the body.

Configuring the fitting

Supported options:

  • includeErrStack - whenever truthful, in case of error is thrown or yielded by fittings in the pipe, the error stack is included in responses.
  • beautifyJson - meant for Dev/Integration envs, where you want to curl your API and just read. The error-stack is optimized for this beautification.
  1. Create a fitting definition before your pipe
  2. Use the configured fitting instead the raw fitting name.

Example:

in default.yaml

  bagpipes: 
    _output:
      name:                   swagger-json-output
      beautifyJson:           false
      includeErrStack:        false

    _router:
      name:                   swagger_router
      controllersInterface:   pipe

    swagger_controllers:
      - onError:              _output
      - swagger_cors
      - swagger_params_parser
      - swagger_security
      - swagger_validate
      - express_compatibility
      - _router
      - _output

in dev.yaml

  bagpipes: 
    _output:
      beautifyJson:           true
      includeErrStack:        true

Last minute modifications to output

If you need to perform a last-minute modification to the output, you can provide a synchronous handler and place it on the context as ctx._preOutput.

The function is provided one argument - the context itself, so you don't have to use the keyword this.

Example:

module.exports = function(fittingDef) {
  return function(ctx, next) {
      ctx._preOutput = lastMomentModifyCtx;
      next()
  }
}

function lastMomentModifyCtx(ctx) {
    //ctx.output - will contain the output, or the output created 
    //  from a thrown/yielded error
}

The usecase that brought this feature is a proprietary fitting that executes early in the pipeline, collects tools (di) and prepares an envelope response, where by corporate rules any reponse provided by any step must be contained in this envelope.

So, in fact, the fitting does all the di and prepare the envelope before all user-code parts (mainly security-handlers and router controllers), gathers data to this envelope as execution of the request progresses, and uses the hook to enrich and contain the response using the ctx._preOutput hook.

Future

  • design handling of multiple content-types

Contribute

  • Using PRs :). If you intend to add functionality - please discuss it with us first on an issue - just to help maintain the spirit of the project :)
  • make sure all tests pass

Thanks!

Lisence

MIT, and that's it :)