Skip to content

Commit 3087ae7

Browse files
committed
Add example using the petstore api spec. fix #3
1 parent 70e2843 commit 3087ae7

6 files changed

Lines changed: 210 additions & 5 deletions

File tree

.vscode/launch.json

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,16 @@
1616
// "program": "${workspaceFolder}/node_modules/nodemon/bin/nodemon",
1717
// "args": ["${workspaceFolder}/integrationTests/modelValidator.test.js"],
1818
"cwd": "${workspaceFolder}/src/"
19-
}
19+
},
20+
{
21+
"type": "node-terminal",
22+
"request": "launch",
23+
"name": "Debug examples",
24+
"skipFiles": [
25+
"<node_internals>/**"
26+
],
27+
"command": "node examples/petstore.js"
28+
},
2029
]
2130
}
2231

README.md

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,22 @@ const spec = require('./openapi.json');
1717
const openApiValidator = new OpenApiValidator({ apiSpec: spec });
1818
const validator = openApiValidator.createValidator();
1919

20+
// Configure this to the client's request. It will resolve the expected schema in the spec using the method and route defined, and validate the request parameters.
2021
const newRequest = {
2122
method: 'GET',
23+
// Matched openapi specification generic route, this should be the generic `path` from the spec, such as `/resources/{resourceId}/`, it must match one of them exactly.
24+
route: request.route
25+
2226
headers: { Authorization: 'Bearer Token' },
27+
28+
// Query string parameters from the request
2329
query: { limit: 10 },
30+
31+
// Body already parsed to JSON
2432
body: { field: true },
25-
path: { user: 'userId' },
2633

27-
// Matched openapi specification generic route
28-
route: request.route
34+
// Path parameters
35+
path: { user: 'userId' }
2936
};
3037
await validator(newRequest);
3138
```

examples/petstore.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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();

examples/petstore.yml

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
openapi: "3.0.0"
2+
info:
3+
version: 1.0.0
4+
title: Swagger Petstore
5+
license:
6+
name: MIT
7+
servers:
8+
- url: http://petstore.swagger.io/v1
9+
paths:
10+
/pets:
11+
get:
12+
summary: List all pets
13+
operationId: listPets
14+
tags:
15+
- pets
16+
parameters:
17+
- name: limit
18+
in: query
19+
description: How many items to return at one time (max 100)
20+
required: false
21+
schema:
22+
type: integer
23+
format: int32
24+
responses:
25+
'200':
26+
description: A paged array of pets
27+
headers:
28+
x-next:
29+
description: A link to the next page of responses
30+
schema:
31+
type: string
32+
content:
33+
application/json:
34+
schema:
35+
$ref: "#/components/schemas/Pets"
36+
default:
37+
description: unexpected error
38+
content:
39+
application/json:
40+
schema:
41+
$ref: "#/components/schemas/Error"
42+
post:
43+
summary: Create a pet
44+
operationId: createPets
45+
tags:
46+
- pets
47+
responses:
48+
'201':
49+
description: Null response
50+
default:
51+
description: unexpected error
52+
content:
53+
application/json:
54+
schema:
55+
$ref: "#/components/schemas/Error"
56+
/pets/{petId}:
57+
get:
58+
summary: Info for a specific pet
59+
operationId: showPetById
60+
tags:
61+
- pets
62+
parameters:
63+
- name: petId
64+
in: path
65+
required: true
66+
description: The id of the pet to retrieve
67+
schema:
68+
type: string
69+
responses:
70+
'200':
71+
description: Expected response to a valid request
72+
content:
73+
application/json:
74+
schema:
75+
$ref: "#/components/schemas/Pet"
76+
default:
77+
description: unexpected error
78+
content:
79+
application/json:
80+
schema:
81+
$ref: "#/components/schemas/Error"
82+
components:
83+
schemas:
84+
Pet:
85+
type: object
86+
required:
87+
- id
88+
- name
89+
properties:
90+
id:
91+
type: integer
92+
format: int64
93+
name:
94+
type: string
95+
tag:
96+
type: string
97+
Pets:
98+
type: array
99+
items:
100+
$ref: "#/components/schemas/Pet"
101+
Error:
102+
type: object
103+
required:
104+
- code
105+
- message
106+
properties:
107+
code:
108+
type: integer
109+
format: int32
110+
message:
111+
type: string

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@
6767
"sinon": "^11.1.2",
6868
"source-map-support": "0.5.19",
6969
"ts-node": "^9.1.1",
70-
"typescript": "^4.4.4"
70+
"typescript": "^4.4.4",
71+
"yaml-js": "^0.3.1"
7172
},
7273
"engines": {
7374
"node": ">=14.5.0"

yarn.lock

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3220,6 +3220,11 @@ yallist@^4.0.0:
32203220
resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
32213221
integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==
32223222

3223+
yaml-js@^0.3.1:
3224+
version "0.3.1"
3225+
resolved "https://registry.yarnpkg.com/yaml-js/-/yaml-js-0.3.1.tgz#8f6f4300063364c2778be30f220736ae5e92c23c"
3226+
integrity sha512-LjoIFHCtSfkGzPsmYmfDsW+TShtQBcY7lwH1yLQ5brJHXRhjteUnVE2ThCbz1madq8JUZIAjFiavfnIFeTO8CQ==
3227+
32233228
yargs-parser@20.2.4:
32243229
version "20.2.4"
32253230
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.4.tgz#b42890f14566796f85ae8e3a25290d205f154a54"

0 commit comments

Comments
 (0)