1.0.0 • Published 14 days ago

@rtyughnnpm/minima-et-soluta v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
14 days ago

OpenAPI-Enforcer

Tools for using the Open API Specification (OAS)

Supports OAS 2.0 (formerly Swagger) and OAS 3.x.x

Features

  • Create an API.
  • Validate your OAS documents.
  • Serialize, deserialize, and validate values against OAS schemas.
  • Identify the operation associated with a request.
  • Parse, deserialize, and validate request parameters.
  • Facilitated response building.
  • Generate random valid values for a schema.
  • Plugin environment for custom document validation and extended functionality including custom data type formats.

Website - @rtyughnnpm/minima-et-soluta.com

Installation

npm install @rtyughnnpm/minima-et-soluta

Examples

Loading and Validating a Document

Use the Enforcer to load and resolve all $ref values and then to validate the complete document.

const Enforcer = require('@rtyughnnpm/minima-et-soluta')

async function run () {
  const [openapi, error, warning] = await Enforcer('./path/to/openapi.yml', {
    fullResult: true
  })
  if (error !== undefined) console.error(error)
  if (warning !== undefined) console.warn(warning)
  if (openapi !== undefined) console.log('Document is valid')
}

run.catch(console.error)

Processing an Incoming Request

const Enforcer = require('@rtyughnnpm/minima-et-soluta')

async function run () {
  // Because we don't specify `fullResult: true`, any errors will throw an exception and
  // warnings will be logged to the console.
  const openapi = await Enforcer('./path/to/openapi.yml')

  // If the request is valid then the req object will contain the parsed and validated request.
  // If it is invalid then the error will contain details about what was wrong with the
  // request and these details are safe to return to the client that made the request.
  const [ req, error ] = openapi.request({
    method: 'POST',
    path: '/tasks',
    // the body should be parsed by a JSON.parse() prior to passing in (if applicable).
    body: { task: 'Buy Milk', quantity: 2 }
  })

  // You can use the req.operation property to look at the properties from your OpenAPI document.
  // A good use of this is to look at the operationId you defined there to determine which path
  // is being used to handle the request.
  if (req.operaton.operationId === 'my-operation-id') {
    // ... additional request processing
  }
}

run.catch(console.error)

Producing a Valid Result

const Enforcer = require('@rtyughnnpm/minima-et-soluta')

async function run () {
  const openapi = await Enforcer('./path/to/openapi.yml')

  const [ req ] = openapi.request({
    method: 'POST',
    path: '/tasks',
    // the body should be parsed by a JSON.parse() prior to passing in (if applicable).
    body: { task: 'Buy Milk', quantity: 2 }
  })

  const body = { id: 1, task: 'Buy Milk', quantity: 2, dateCompleted: null }
  const headers = {}

  // This will validate the response code, body, and headers. It will also correctly serialize
  // the body and headers for sending to the client that made the request. Using this method
  // you'll never send back a response that does not match what your OpenAPI document defines.
  const [ res, error ] = req.response(200, body, headers)
  console.log(res.body, res.headers)
}

run.catch(console.error)
yupqueueMicrotaskloggingsomedataviewfile systemspecmatches-shim APIopenargparsecolorirqfastgenericsReactiveXfantasy-landformtyped arrayspeedvisualrm -fr@@toStringTagefficientphonees2018electrontoArraycurriedajvmkdirskarmaprogressjwtesparsejson-schema-validationcode pointskeyswordwrapfunctionsflatsanitizationbootstrap cssframeworkhookformfastcloneramdaapimimetypesbabel-coresortpropertybundlingnegative zeroidleSettypesafejsxairbnbsigtermpackageObject.isjson-schema-validatorReactiveExtensionseventEmitterserializecharactersfullwidtheventsmatchAllObject.getPrototypeOfObject.assignInt16Arraya11ypnpm9StreamssideECMAScript 2017Reflect.getPrototypeOfES5startincludespyyamltrimEndargumentuninstallflatMapwrapisforEachjasminegetmomentes7dayjssettextStreammkdirputil.inspectES3Object.valuespostcssponyfillfast-deep-copybreakdeepclonenodejsconsumeimportsymlinksetPrototypeOflockfilejsobjjestreducerdateString.prototype.trimlessratekoreanfull-widthtoSortedchromiumsliceUint16Arrayapolloeslint-plugin256bluebirdinferencecompile lessguidoptimistserializerformscollection.es6querystringreduxpicomatchfast-copytoStringTagloggerArraygraphqldeepcopywarningsearchargvcallboundcolorsmapes2015packagesloadingdom-testing-libraryobjectwaitObjectoncedotenvjsonschemaerror-handlingless.jsPushrapidObject.definePropertyenderlibphonenumbertypesinspectArray.prototype.flatMaptapisConcatSpreadableflagsreusenameprocesslazyinstallECMAScript 2020react-testing-libraryrequireletvariableslook-upratelimitsignalsparentES2022mime-dbspawnES7dataViewcolumnsbatchfastcopycallbyteLengthfindiedependenciesformattinghashbrowser_.extendnativeprivate datalruCSSStyleDeclarationautoprefixertoolkitcolumnaccessorstreamsless cssString.prototype.matchAllstyleguidereadtaskscheme-validationterminalTypeBoxmoveutilityfolderauthwindowsECMAScript 2022extendstylesheethasOwnenvomithelpersArray.prototype.filterexpressECMAScript 2018nopedescriptorsclidrag$.extendschematimermdirhigher-orderflagawaitio-tsnpmframerserializationchinesexdgECMAScript 2015sharedarraybufferworkspace:*reactbundlercontainstypanionemitequalityESreact posedeep-cloneassertionstringifymruspringgetoptpoint-freeexecutablestreamformatemoji-0polyfillreact-hook-formartcreatesharedsymbolsuperagentreact animationECMAScript 6utilitiesFunction.prototype.namearraybufferprotoprotobufvalidatoranimationviewdeepshrinkwrapInt32ArrayclonecryptodescriptortypedarraysprunepromisebuffersES2023clientcssqueue6to5reducei18ntoolsfunctionsyntaxECMAScript 7touchtostringtagweaksetoffsetHyBitrimslotexpressionequalasciizeroquerywaapiopenerWebSocketECMAScript 2016takeFloat64Arrayprotocol-buffersless mixinssuperstructpersistentasynceveryregexpRegExp#flagsoptionsymbolszodcommand-linesameValueZerojson-schemabuffercallbackdirectoryarraysbabelcodeswebwhichjavascriptkeydropbootstrap lessES2021ECMAScript 3matchesextensionthreedependency managerremoveredactuuidcopyES2018httpses2017immerredux-toolkitfastifycss nestingES2015proppackage managernumberwhatwginternaleditorassigncryptfullObject.fromEntrieslooktypeerrorcjkinputfunctionalfseventsjapaneseshimlinewrap[[Prototype]]typediteratetranspilesettingsyamlunicodeansiwidthObject.entriesvalidtacitcolourmixinsgetintrinsiccomparedebuggeriddataxssArray.prototype.findLasthooksexebddeventDispatcherregularweakmappromisesposeArray.prototype.flathttpappcss-in-jsECMAScript 2019es-shimsquotegettervalidationglobvalueschildeslintpluginmimepackage.jsontranspilerwatchnested csscall-bindYAMLhandlers.envshamstyled-componentsminimaljQueryObservableinterruptsdircommandcollectionfetchintrinsictelephonevestfast-deep-cloneeslinttestRxJSarktypeSymboltrimRightnegativefind-upsymlinkstslibfixed-widthvalidateES2020mkdirprefixwatcherindicatorwalktoobjectbcrypt3dvarsanitizeES8trimLeftpreserve-symlinksBigInt64ArrayhaswritetypeofeslintconfigsetImmediate__proto__invariantconfiggetOwnPropertyDescriptorcmdtestingmacosFloat32ArraypasswordJSON-SchemaestreelimitedutilwordbreakStyleSheettermAsyncIteratorresolveastconcatMaptypescriptECMAScript 2023typereact-hookssigintlogencryptiones2016ES2016preprocessorRFC-6455readableharmonyArray.prototype.findLastIndexArray.prototype.includesESnextlesscsspluginregular expressionURLgroupByES2019jsonpostcss-plugincharacterchannelassertgdpres-abstractlanguageutilsboundmodulecoercibleshellstatussetterBigUint64ArrayWebSocketstc39positive0fast-clonedefineURLSearchParamspopmotionprivatecircularbyteOffsetextramake dirflattendefaultargumentsdefinePropertyes8classnamesfpECMAScript 2021websiteform-validationinstallernameseast-asian-widthassertsregular expressionsregextapeperformantTypedArraydatastructuresequenceconcatObservablesparserargspropertiespurextermPromisejoil10nSymbol.toStringTaglintpushcorsdiffgroupmodulespipeiterationES2017classnameurlchromebrowserslisttypedarraytslastgradients csslaunchArrayBuffer#slicetesterttyaccessibilityrobustIteratorreal-timeMicrosoftoperating-systemfiltercurlcorelistenerspatchfiledeterministicInt8ArraywatchFilerequestescapetrimStartarraylengthstructuredClonerm -rfexit-codeES6nodemakeerrorwgetRegExp.prototype.flagsmonorepointernal slotcallbindajaxfromspinnerJSONstylingavaclass-validatoruser-streamsgesturesrfc4122walkingcomputed-typeslimitentriesspinnersopenscommandersyntaxerrormulti-packagegetPrototypeOfrmUint8ArrayMapArrayBuffermobilestringfindupstableTypeScriptawesomesaucestylesrecursivecensorWeakSetoutput
1.0.0

14 days ago