|
| 1 | +const yaml = require('yaml-js'); |
| 2 | +const fs = require('fs-extra'); |
| 3 | +const path = require('path'); |
| 4 | + |
| 5 | +const { OpenApiValidator } = require('../dist/index'); |
| 6 | + |
| 7 | +const spec = fs.readFile(path.join(__dirname, './petstore.yml')).then(file => yaml.load(file.toString())); |
| 8 | + |
| 9 | +const openApiValidator = new OpenApiValidator({ apiSpec: spec }); |
| 10 | +const validator = openApiValidator.createValidator(); |
| 11 | + |
| 12 | +async function passesValidation() { |
| 13 | + const newRequest = { |
| 14 | + // Method |
| 15 | + method: 'GET', |
| 16 | + // Matched openapi specification generic route |
| 17 | + route: '/pets/{petId}', |
| 18 | + |
| 19 | + // expected headers |
| 20 | + headers: { Authorization: 'Bearer Token' }, |
| 21 | + |
| 22 | + // There's no query on this endpoint |
| 23 | + // query: { limit: 10 }, |
| 24 | + |
| 25 | + // There's no body on the get |
| 26 | + // body: { field: true }, |
| 27 | + |
| 28 | + // Path parameters |
| 29 | + pathParameters: { petId: 'my-first-cat' } |
| 30 | + }; |
| 31 | + |
| 32 | + await validator(newRequest); |
| 33 | + console.log('Success: The passed in parameters match the spec'); |
| 34 | +} |
| 35 | + |
| 36 | +async function failsValidation() { |
| 37 | + const newRequest = { |
| 38 | + // Method |
| 39 | + method: 'GET', |
| 40 | + // Matched openapi specification generic route |
| 41 | + route: '/pets/{petId}', |
| 42 | + |
| 43 | + // Invalid path parameters, missing expected `petId` in the path, so this will cause an error. |
| 44 | + path: { otherParameterNotPetId: 'my-first-cat' } |
| 45 | + }; |
| 46 | + |
| 47 | + try { |
| 48 | + await validator(newRequest); |
| 49 | + } catch (error) { |
| 50 | + console.log(error.message); |
| 51 | + // Bad Request: request.path must have required property 'petId', request.path must NOT have additional properties |
| 52 | + |
| 53 | + console.log(error.errors); |
| 54 | + /* |
| 55 | + [ |
| 56 | + { |
| 57 | + path: '.path.petId', |
| 58 | + message: "must have required property 'petId'", |
| 59 | + fullMessage: 'missing required property request.path.petId' |
| 60 | + }, |
| 61 | + { |
| 62 | + path: '.path.otherParameterNotPetId', |
| 63 | + message: 'must NOT have additional properties', |
| 64 | + fullMessage: "request.path must NOT have additional property: 'otherParameterNotPetId'" |
| 65 | + } |
| 66 | + ] |
| 67 | + */ |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +passesValidation(); |
| 72 | +failsValidation(); |
0 commit comments