2.0.8 • Published 1 year ago

@juigorg/fuga-voluptas v2.0.8

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

@juigorg/fuga-voluptas

CI NPM version js-standard-style

A simple plugin that enables response validation for Fastify.
The use of this plugin will slow down your overall performance, so we suggest using it only during development.

Install

npm i @juigorg/fuga-voluptas

Usage

You just need to register the plugin and you will have response validation enabled:

import fastify from 'fastify'

const app = fastify()

await app.register(require('@juigorg/fuga-voluptas'))

app.route({
  method: 'GET',
  path: '/',
  schema: {
    response: {
      '2xx': {
        type: 'object',
        properties: {
          answer: { type: 'number' }
        }
      }
    }
  },
  handler: async (req, reply) => {
    return { answer: '42' }
  }
})

app.inject({
  method: 'GET',
  path: '/'
}, (err, res) => {
  if (err) throw err
  console.log(res.payload)
})

Different content types responses are supported by @juigorg/fuga-voluptas, @fastify/swagger and fastify. Please use content for the response otherwise Fastify itself will fail to compile the schema:

{
  response: {
    200: {
      description: 'Description and all status-code based properties are working',
      content: {
        'application/json': {
          schema: { 
            name: { type: 'string' }, 
            image: { type: 'string' }, 
            address: { type: 'string' } 
          }
        }, 
        'application/vnd.v1+json': {
          schema: { 
            fullName: { type: 'string' }, 
            phone: { type: 'string' } 
          }
        }
      }
    }
  }
}

If you want to override the default ajv configuration, you can do that by using the ajv option:

// Default configuration:
//    coerceTypes: false
//    useDefaults: true
//    removeAdditional: true
//    allErrors: true

import responseValidator from '@juigorg/fuga-voluptas'

// ... App setup

await fastify.register(responseValidator, {
  ajv: {
    coerceTypes: true
  }
})

You can also pass in an instance of ajv

// Default configuration:
//    coerceTypes: false
//    useDefaults: true
//    removeAdditional: true
//    allErrors: true

import responseValidator from '@juigorg/fuga-voluptas'
import Ajv from 'ajv'

// ... App setup

const ajv = new Ajv()
await fastify.register(responseValidator, { ajv })

By default the response validation is enabled on every route that has a response schema defined. If needed you can disable it all together with responseValidation: false:

import responseValidator from '@juigorg/fuga-voluptas'

// ... App setup
await fastify.register(responseValidator, {
  responseValidation: false
})

Alternatively, you can disable a specific route with the same option:

fastify.route({
  method: 'GET',
  path: '/',
  responseValidation: false,
  schema: {
    response: {
      '2xx': {
        type: 'object',
        properties: {
          answer: { type: 'number' }
        }
      }
    }
  },
  handler: async (req, reply) => {
    return { answer: '42' }
  }
})

Plugins

You can also extend the functionalities of the ajv instance embedded in this validator by adding new ajv plugins.

fastify.register(require('fastify-response-validation'), {
  ajv: {
    plugins: [
      require('ajv-formats'),
      [require('ajv-errors'), { singleError: false }]
      // Usage: [plugin, pluginOptions] - Plugin with options
      // Usage: plugin - Plugin without options
    ]
  }
})

License

MIT

transformreact-hook-formsqsreactfast-clonetrimeventDispatchertimefilterrandomemrrestfulutilitiesprotobufjson-schema-validationgetintrinsicObjectparsecallbind__proto__everyhardlinkscircularUint8Arrayprotocol-bufferses2016superstructsyntaxappweb-0quoteargsbrowserslistbinariesES5redux-toolkitoptimizerclisearchwgetparentchaiECMAScript 2022cloudfrontdeepcopystablefindLastIndexkarmasuperagentstringifierschemajson-schema-validatorloadbalancingtraverseObject.assignpostcss-pluginenvironmentprocesssetworkflowtypescriptsubprocessgroupByES2022restjasminehookformeventsforkcloudsearchHyBiRxJSefficientutilasciinegative zeroselfperformantimportexportjsonschemaexpresscolorsObject.keyselbmake dirreducekoreanasyncjQueryartuninstalldescriptiondescriptorsio-tsiteratorfind-up6to5matchAllloggergetoptenderutilitycall-bindinstrumentationdescriptorinpipeminimalreversedfigletpackage.jsondiffhttpapolloreadablecssrmruntimedatafunctionalobjhashwhatwgdatereadUint32Arrayinternalpurerfc4122consolezxclassesflatbrowsersetImmediateflatMapdependency managerURLSearchParamsObservablesbundlingRxatomsymbolbyteOffsetfastconsumedebuggerRegExp#flagsES2018fantasy-landWeakSettrimRightenumerableidleSymbolnodejsmodulepositivepyyamlgenericses-shimspnpm9String.prototype.trimrequireprefixextendreact-testing-libraryECMAScript 2015offseteslint-pluginbeanstalkmanipulationaccessormoveroute53phonemapreducewidthutilsreal-timestylesfilespringwritableincludesprogressbusycallbackIteratorformatconcatcolourcss-in-jstouchproxymanagerregexes-abstractbannerhtmlarrayinferenceownomites8shellspinnerssideassertionString.prototype.matchAllwafES2023nativecryptogitignorettyECMAScript 7argvBigUint64ArrayYAMLtakeoncestyled-componentstextes-shim APInamesSetrgbtypedarraymkdirsxhrspawnsymlinksl10nwalkingunicodermdircopyconfigurableloadingpicomatchvarguidReactiveXdeletespecapiawesomesaucesesglobal objectArray.prototype.flatconfigamazonzeroquerystringreducer.envqueueweakmapinputArray.prototype.filterECMAScript 3parentsframeworkschemerouterintrinsicparserlocalarraysdeterministic_.extendistanbulframerreact posecallsimpledbi18ndeepcloneprivatemocharecursivefsfolderinstallerequalvestfppolyfillESnextregexpFloat64ArrayFunction.prototype.namebinaryglobalThisjestArray.prototype.findLaststyleguidepoint-freeavawalkgdprflattenthreechannelexpressionstructuredClonevpcshebangautoprefixerprunesafeshamtestingStyleSheetjson-schematypeentriesJSON-SchemaECMAScript 2017full-widthsettingsloggingsetPrototypeOfcodesdeep-cloneInt16ArrayasteriskscharacterArray.prototype.flatMapmapvalidationec2forEachnegativeform-validationbrowserlistbddclassnamestoragegatewaycode pointssnsbuffersnpmignorehasfast-deep-cloneES2020rm -frprototype256MicrosoftSystem.globalcommanderdynamodbsource mapisConcatSpreadablecheckES3ES2016streamstrimLefttoSortedes2015stylingfixed-widthoptimistrobustmonorepodependenciesyuptransportES6urlObject.entriessinatratoobjectECMAScript 2016Object.getPrototypeOfsetterjsxrequestgraphqltacitastlistenerspostcsspushsymbolsgetPrototypeOfassignReactiveExtensionsroutezodperformanceURLnodeformsautoscalingcurriedtslibcolorReflect.getPrototypeOfdefinePropertynopespinnerUnderscorenamecensorjavascriptcreatebyteLengthgestureskeywritebabelAsyncIteratortoStringTagdirectoryeast-asian-widthes5airbnbES2019estreepopmotionchineseclass-validatorhelpersboundworkspace:*Int8Arrayweaksetinternal slotfullwidthfnmatchenvdataviewcurltrimStartcore-jsrapidtermxmlObject.valuesyamlslicetypeerrorimmer3dtypedarraysinvariantsorted.gitignoreagentcoverageCSSeslintconfigtoArrayArray.prototype.findLastIndexsortes7redirectinspectStreamsfeedignorees2018
2.0.8

1 year ago

2.0.7

1 year ago

2.0.6

1 year ago

2.0.5

1 year ago

2.0.4

1 year ago

2.0.3

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.0.0

1 year ago