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

@brightcove/openapi-validator-hono

v1.0.9

Published

Provides Hono middlewares for OpenAPI validation

Downloads

112

Maintainers

rwbarber2rwbarber2aperezbrightcoveaperezbrightcoveireyes94ireyes94brightcove-adminbrightcove-admintedktedkabradley-brightcoveabradley-brightcovebc-alivebc-alivelasanchezclasanchezcmarguinbcmarguinbcbrightcove-userbrightcove-userkmasonkmasoncbarstowcbarstowhikehhikehmyerramallamyerramallapdiaspdiasjwhisenantjwhisenantmfregozomfregozoadavila1adavila1bc-acgarciabc-acgarciarjunerjunefsalazarbcfsalazarbckhaiphamkhaiphamwswanbeckwswanbeckgastafurovgastafurovadalwaniadalwaniekelson-bcoveekelson-bcovesysengsysengmcarreiromcarreirohwoodburyhwoodburyjblakerjblakerbcmauleonbcmauleonpaco_oblea_bcpaco_oblea_bcbiswaranjanbiswaranjanbarroyobarroyobmartinezbmartinezbc-jcarlsonbc-jcarlsoneledezmaeledezmajcuetojcuetoerodrigueserodriguespsousapsousamarcogaraymarcogarayjavibrightjavibrightbcpsalasbcpsalasetobinetobinackbabeackbabeomartinezomartinezmgonzalez_bcmgonzalez_bcpdohertybcovpdohertybcovmuthukumar.bcmuthukumar.bcbzizmondbzizmondjmpmacedojmpmacedoscorreiascorreialescorciolescorciocavieiracavieiraarunjeyaprasadarunjeyaprasadbvilvanathanbvilvanathanrociosantosrociosantosagarciabcovagarciabcovattinderattinderlauralopezlauralopezskumar85skumar85hrodriguez2hrodriguez2jasilvaantoniojasilvaantoniopalvarezbcpalvarezbcericramosericramoscarlosabajocarlosabajoingrid.s.cruzingrid.s.cruzluis_fernando_lopez_ruizluis_fernando_lopez_ruizluis.garcia.brightcoveluis.garcia.brightcoverodrigofdzrodrigofdzpgutierrezgilpgutierrezgilharish17harish17jjeyaprakashjjeyaprakashrrajendran1698rrajendran1698jlomelijlomelisjimenezsjimenezstuartmhstuartmhjherrerabcovjherrerabcovmshiwalmshiwalptamizhptamizhakamalakkannanakamalakkannanroman-bcroman-bcjvaldez1jvaldez1mdeltorobcovmdeltorobcovtnwannatnwannabsahlas.npmbsahlas.npmdherrera1109dherrera1109hswaminathanhswaminathanechengbcechengbcsbarrettbcsbarrettbcldominguezldominguezrtezerartezeraponeill-bcovponeill-bcovv.kozlov_bcv.kozlov_bckreynoldskreynoldsbc-srimron-soutterbc-srimron-soutterjguerrajguerrabgs-devopsbgs-devopsbcmneilbcmneilbcbcliffordbcbcliffordbrianhsubrianhsumcho-bcmcho-bccarredondocarredondokpandiyarajankpandiyarajanlvohralvohrasharanya.muruganandamsharanya.muruganandamm.morrisonm.morrisonamillerbrightcoveamillerbrightcovekevin.schickkevin.schickdsalnikovdsalnikovcloewer_bccloewer_bcdawnpackodawnpackoxgarcia_npmxgarcia_npmawaldronawaldronebertaudebertaudsstevanussstevanusmsivallsmsivallseolveraeolverajuan-sanchezjuan-sanchezjose.luis.sanchezjose.luis.sanchezttabrilla-bcttabrilla-bclmelchorx1lmelchorx1joeyleshjoeyleshpedro-cruzpedro-cruzrsilva_brightcoversilva_brightcoveabarstowbcabarstowbcsbarathansbarathangestrada-brgestrada-bralbertogomezalbertogomezmiklospocsaji_bcmiklospocsaji_bcuomaruomarddashkevichddashkevichwalterseymourbcwalterseymourbcimoronesimoronesnorma.gonzaleznorma.gonzalezjfloresbcjfloresbcaviel_resnickaviel_resnickalexey.kremsaalexey.kremsamlopez.bmlopez.bmelinda.darvasimelinda.darvasialfredo-reyesalfredo-reyesdaniel_camposdaniel_camposskarukamannaskarukamannajterranovajterranovaareis10areis10vmnavarrovmnavarromaraizamaraizaadambertalanbcadambertalanbcgabor.kiacz.brightcovegabor.kiacz.brightcovedgonzalez89dgonzalez89rwingerrwingerssahssahsravan.pbrsravan.pbrapenigalapatiapenigalapatiijunaidfijunaidflmaultsbylmaultsbybcc-bfranklinbcc-bfranklinmgoncalvesmgoncalvesmbalasubramaniammbalasubramaniamhugocjimhugocjimmadhu_gmadhu_gareveloarevelosachin-brightcovesachin-brightcovebc-jcuevasbc-jcuevas

Keywords

Readme

Hono OpenAPI Validator

package-info NPM NodeJS

Provides Hono middlewares for OpenApi validation

Installation

npm install @brightcove/openapi-validator-hono

Pre-parsing YAML files

If you pass in a path to a YAML file, the library will parse it on initialization into JSON. For particularly large YAML files, this can lead to slow startup times, so the library offers the ability to pre-parse YAML files.

npx @brightcove/openapi-validator-hono parse
Command List

  help      help
  parse     parses all YAML files in the specified folder into JSON

Options

  -i, --import    Folder path to read YAML files from (default: "api")
  -e, --export    Folder path to export JSON files to  (default: "api")

Initialization

The library needs to be initialized with the path to a valid YAML and/or JSON file.

import { Hono } from 'hono';
import path from 'path';
import { OpenApiValidator } from '@brightcove/openapi-validator-hono';

const app = new Hono();

app.use(OpenApiValidator.init([
    {
        name: 'api',
        yamlPath: path.resolve('./api/index.yaml')
    },
    options
]));

Note: If there is only a single API added, the api name can be omitted from all the middleware

Options

Validator Options

| Field | Type | Description | Required | | ------ | -------- | ----------------------------------------------------------------------------------------------- | -------- | | logger | Logger | The logger that will be used for debug messages. Uses console by default if not specified | false |

API Options

| Field | Type | Description | Required | | ------------------------------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | name | string | Name used to retrieve the API | yes | | yamlPath | string | Path to the OpenAPI YAML file | yes, to view docs, or jsonPath must be included | | jsonPath | string | Path to the OpenAPI JSON file | yes, or yamlPath must be included | | emptyRequestValid | boolean | Determines whether empty request bodies, for requests with required: true and no required properties, are considered valid. By default this is true. | no | | errorCodes | object | Allows overriding of the default error code values | no | | errorCodes.InputValidationException | string | Overrides the InputValidationException code. Is "400.00" by default. | no | | errorCodes.OutputValidationException | string | Overrides the OutputValidationException code. Is "500.00" by default. | no |

Validating Routes

The library provides the middleware validateRequest, validateResponse, and validate depending on whether you only want request or response validation, or both.

Note: If the middleware isn't added to the specific route, it will not function properly. This is because the routePath isn't resolved before the matching handler is determined

Any errors will be forwarded to the configured error handler as an InputValidationException or OutputValidationException

import { OpenApiValidator } from '@brightcove/openapi-validator-hono';

app.post(
    '/my/test/route',
    OpenApiValidator.validate('api'),  // alternatively `OpenApiValidator.validate()`
    async (c, next) => {
        ...
    }
);

app.onError((err, c) => {
    // err will be an `InputValidationException` or `OutputValidationException`
    if (err instance of HttpException) {
        return err.getResponse();
    }
});

Caveats

  • anyOf and oneOf aren't properly validated, so it's suggested to avoid these and have the logic for validation elsewhere
  • Nested schema refs will allow additional properties unless explicitely given additionalProperties: false

Information

Information on the API and the current route (if found) is added to the context when any of the validation middleware are attached.

If information is needed without any validation being performed, an info middleware is also available.

import { OpenApiValidator } from '@brightcove/openapi-validator-hono';

app.post(
    '/my/test/route',
    OpenApiValidator.info('api'),
    async (c, next) => {
        const openapi = c.get('openapi');
        const routeSchema = openapi.routeSchema;
        const apiSchema = openapi.schema;
        const operations = openapi.operations;
        ...
    }
);

Helper Functions

Some of the packages helper functions are exposed in the helpers export

import { helpers } from '@brightcove/openapi-validator-hono';

// Merges additional properties (ie. `allOf`) and `properties`
const merged = helpers.mergeSchema(jsonSchema);

// Checks whether an OpenApi schema json is valid, and returns any errors found if it isn't
const { valid, errors } = helpers.validateSchema(jsonSchema);

// Simple check for whether a JSON object is a valid OpenApi schema definition
const isValid = helpers.isValidSchema(json);

Errors

Error classes and helper functions are exposed with the errors export if a custom validation error needs to be thrown.

import { errors } from '@brightcove/openapi-validator-hono';

app.get('/some/route/1', async (c, next) => {
    ...something happens
    throw errors.InputValidationException('failed input validation');
});

app.get('/some/route/2', async (c, next) => {
    ...something happens
    throw errors.OutputValidationException('failed output validation');
});

JSON Schema Route

To view the JSON schema representation of the YAML file, you can use the following middleware

import { OpenApiValidator } from '@brightcove/openapi-validator-hono';

app.get('/schema', OpenApiValidator.schema('api'));

Documentation Route

To view a Swagger UI render of the OpenAPI spec, you can either specify the path to the YAML file (ie. if you're serving static files) or a full url

import { serveStatic } from '@hono/node-server/serve-static'; import { OpenApiValidator } from '@brightcove/openapi-validator-hono';

app.use('/static/*', serveStatic({ root: './api' }));

app.get('/docs', OpenApiValidator.docs('/static/'));