|
2 | 2 |
|
3 | 3 | Validate JSON payloads against OpenAPI 3.0/3.1 specs. Catch mock drift before it hits production. |
4 | 4 |
|
5 | | -## Purpose |
| 5 | +## Why |
6 | 6 |
|
7 | 7 | Frontend teams write mock responses in tests that drift from reality over time. Fields get renamed, removed, or added in the API but mocks stay frozen. Tests pass, code ships, and the app breaks in production. |
8 | 8 |
|
9 | 9 | This package validates mock payloads against the OpenAPI spec — the source of truth. No YAML parsing, no URL fetching — consumers handle I/O, this package handles validation. |
10 | 10 |
|
11 | 11 | ## Install |
12 | 12 |
|
| 13 | +```bash |
13 | 14 | npm install openapi-mock-validator |
| 15 | +``` |
14 | 16 |
|
15 | | -## Usage |
| 17 | +## Quick Start |
16 | 18 |
|
| 19 | +```typescript |
17 | 20 | import { OpenAPIMockValidator } from 'openapi-mock-validator'; |
| 21 | +import fs from 'node:fs'; |
18 | 22 |
|
19 | | -// Consumers load the spec themselves (fetch, readFile, etc.) |
| 23 | +// Load the spec yourself (fetch, readFile, etc.) |
20 | 24 | const spec = JSON.parse(fs.readFileSync('./openapi.json', 'utf-8')); |
21 | 25 |
|
22 | 26 | const validator = new OpenAPIMockValidator(spec); |
23 | 27 | await validator.init(); |
24 | 28 |
|
25 | 29 | // Match a mock URL to a spec path |
26 | 30 | const match = validator.matchPath('/v1/orders/abc-123/status', 'GET'); |
27 | | -// { path: '/v1/orders/{id}/status', params: { id: 'abc-123' } } |
| 31 | +// → { path: '/v1/orders/{id}/status', params: { id: 'abc-123' } } |
28 | 32 |
|
29 | | -// Validate mock response against the spec |
30 | | -const result = validator.validateResponse(match.path, 'GET', 200, mockPayload); |
31 | | -// { valid: false, errors: [...], warnings: [...] } |
| 33 | +if (match) { |
| 34 | + // Validate the mock response against the spec |
| 35 | + const result = validator.validateResponse(match.path, 'GET', 200, mockPayload); |
| 36 | + // → { valid: false, errors: [...], warnings: [...] } |
| 37 | +} |
| 38 | +``` |
32 | 39 |
|
33 | | -// Validate request body |
34 | | -const reqResult = validator.validateRequest('/v1/orders', 'POST', requestBody); |
| 40 | +## API |
35 | 41 |
|
36 | | -## Options |
| 42 | +### `new OpenAPIMockValidator(spec, options?)` |
37 | 43 |
|
38 | | -const validator = new OpenAPIMockValidator(spec, { strict: false }); |
39 | | -// strict (default: true) — reject additional properties not in spec |
| 44 | +Creates a validator instance. The spec must be a parsed OpenAPI 3.x JSON object. |
40 | 45 |
|
41 | | -// Can also override per call: |
| 46 | +```typescript |
| 47 | +const validator = new OpenAPIMockValidator(spec, { |
| 48 | + strict: true, // default: true — reject additional properties not in spec |
| 49 | +}); |
| 50 | +``` |
| 51 | + |
| 52 | +### `validator.init()` |
| 53 | + |
| 54 | +Dereferences all `$ref`s, normalizes OpenAPI 3.0 schemas to 3.1 format, and compiles path matchers. Must be called before any validation. |
| 55 | + |
| 56 | +```typescript |
| 57 | +await validator.init(); |
| 58 | +``` |
| 59 | + |
| 60 | +### `validator.matchPath(url, method)` |
| 61 | + |
| 62 | +Matches a URL against the spec's paths. Returns the matched spec path and extracted parameters, or `null`. |
| 63 | + |
| 64 | +```typescript |
| 65 | +const match = validator.matchPath('/v1/pets/abc-123', 'GET'); |
| 66 | +// → { path: '/v1/pets/{petId}', params: { petId: 'abc-123' } } |
| 67 | +// → null if no match |
| 68 | +``` |
| 69 | + |
| 70 | +- Strips trailing slashes and query strings automatically |
| 71 | +- Prefers literal path segments over parameterized ones (`/orders/pending` beats `/orders/{id}`) |
| 72 | + |
| 73 | +### `validator.validateResponse(path, method, status, payload, options?)` |
| 74 | + |
| 75 | +Validates a response payload against the schema defined in the spec. |
| 76 | + |
| 77 | +```typescript |
| 78 | +const result = validator.validateResponse('/v1/pets/{petId}', 'GET', 200, { |
| 79 | + id: 1, |
| 80 | + name: 'Fido', |
| 81 | +}); |
| 82 | +``` |
| 83 | + |
| 84 | +Returns: |
| 85 | + |
| 86 | +```typescript |
| 87 | +{ |
| 88 | + valid: boolean; |
| 89 | + errors: ValidationError[]; // field-level mismatches |
| 90 | + warnings: ValidationWarning[]; // undocumented status codes, missing schemas |
| 91 | +} |
| 92 | +``` |
| 93 | + |
| 94 | +### `validator.validateRequest(path, method, payload, options?)` |
| 95 | + |
| 96 | +Validates a request body payload against the spec's `requestBody` schema. |
| 97 | + |
| 98 | +```typescript |
| 99 | +const result = validator.validateRequest('/v1/pets', 'POST', { |
| 100 | + name: 'Fido', |
| 101 | + tag: 'dog', |
| 102 | +}); |
| 103 | +``` |
| 104 | + |
| 105 | +### Per-call options |
| 106 | + |
| 107 | +Override the constructor's `strict` option per call: |
| 108 | + |
| 109 | +```typescript |
42 | 110 | validator.validateResponse(path, method, status, payload, { strict: false }); |
| 111 | +``` |
| 112 | + |
| 113 | +## Errors and Warnings |
| 114 | + |
| 115 | +### Errors |
| 116 | + |
| 117 | +Returned when the payload doesn't match the schema: |
| 118 | + |
| 119 | +```typescript |
| 120 | +{ |
| 121 | + path: '/id', // JSON pointer to the field |
| 122 | + message: 'must be integer', // human-readable |
| 123 | + keyword: 'type', // AJV keyword |
| 124 | + expected: 'integer', // what the spec says |
| 125 | + received: 'string', // what the payload has |
| 126 | +} |
| 127 | +``` |
| 128 | + |
| 129 | +### Warnings |
| 130 | + |
| 131 | +Returned when the validator can't fully validate — the payload isn't wrong, but it's not contract-tested either: |
| 132 | + |
| 133 | +| Type | When | |
| 134 | +|------|------| |
| 135 | +| `UNMATCHED_STATUS` | Status code not documented in the spec | |
| 136 | +| `MISSING_SCHEMA` | No schema defined for this path/method/status | |
| 137 | +| `EMPTY_SPEC_RESPONSE` | Response exists but has no `content` (e.g., 204) | |
43 | 138 |
|
44 | 139 | ## OpenAPI Support |
45 | 140 |
|
46 | | -- OpenAPI 3.0 — nullable fields normalized automatically |
47 | | -- OpenAPI 3.1 — native JSON Schema Draft 2020-12 |
48 | | -- Full $ref resolution (nested, circular) |
49 | | -- oneOf / anyOf / allOf composition |
50 | | -- discriminator support |
| 141 | +- **OpenAPI 3.0** — `nullable` fields normalized to 3.1 format automatically |
| 142 | +- **OpenAPI 3.1** — native JSON Schema Draft 2020-12 |
| 143 | +- **$ref resolution** — nested, deeply nested, components referencing components |
| 144 | +- **Composition** — `oneOf`, `anyOf`, `allOf` with full validation |
| 145 | +- **Discriminator** — `discriminator.propertyName` support |
| 146 | +- **Strict mode** — `additionalProperties: false` enforced by default |
| 147 | + |
| 148 | +### Known Limitation |
| 149 | + |
| 150 | +Strict mode (`additionalProperties: false`) can conflict with `allOf` schemas. When `allOf` branches define different properties, each branch rejects the other's properties as "additional." Use `{ strict: false }` for endpoints that use `allOf` composition, or define `additionalProperties` explicitly in your spec. |
| 151 | + |
| 152 | +## Design Decisions |
| 153 | + |
| 154 | +- **JSON only** — no YAML parsing, no URL fetching. Consumers handle I/O. |
| 155 | +- **Strict by default** — if the spec is the source of truth, mocks should match it exactly. |
| 156 | +- **Warnings, not silence** — undocumented status codes and missing schemas are surfaced, never silently skipped. |
| 157 | +- **Parse once, validate many** — the `init()` step is expensive (dereferencing, normalization, path compilation). Validation calls are fast. |
51 | 158 |
|
52 | 159 | ## License |
53 | 160 |
|
|
0 commit comments