json-validator.de

Ratgeber · JSON Schema 2020-12

JSON-Validation in CI/CD: Schema-Checks vor jedem Deploy

Pre-Commit: husky + lint-staged + ajv compile. Build-Step: ajv-cli compile. Vitest: Schema-Tests pro Endpoint, fail-fast bei Drift.

Foto von Mateusz Viola

Von Mateusz Viola

Entwicklung und Konzeption json-validator.de

Drei Validation-Stufen im Build-Prozess

Schema-Validation in CI/CD hat drei sinnvolle Stufen:

StufeWas validiert wirdTool
1. Schema-Selbst-ValidationSind die *.schema.json Files gültiges JSON Schema?ajv-cli compile
2. Fixture-ValidationPassen Test-Fixtures zu den Schemas?Vitest + Ajv
3. Contract-TestsLiefern Endpoints Schema-konforme Responses?Supertest + Ajv

Stufe 1: Schemas selbst sind valides JSON Schema

Klassischer Lookup-Fehler: "required": "name" statt "required": ["name"]. Wird beim Build sofort gefangen mit ajv-cli:

{
  "scripts": {
    "validate:schemas": "ajv compile --strict=true --spec=draft2020 -c ajv-formats -s 'src/schemas/**/*.schema.json'"
  }
}

Nötig sind die Dev-Dependencies ajv-cli und ajv-formats. --spec=draft2020 ist wichtig für Schemas mit $schema 2020-12, sonst meldet ajv-cli „no schema with key or ref“. -c ajv-formats lädt die Format-Prüfer, sonst scheitert jedes Schema mit format. Mit --strict=true werden unbekannte Keywords gemeldet (Tippfehler wie requiered), ebenso nicht auflösbare $ref. Ein Schema mit "required": "name" bricht mit „schema is invalid: data/required must be array“ ab.

Stufe 2: Test-Fixtures gegen Schemas

Wenn dein Code Test-Fixtures hat (JSON-Dateien mit Sample-Payloads), sollten die zum Schema passen:

// vitest test
import { describe, it, expect } from 'vitest';
import Ajv2020 from 'ajv/dist/2020.js';
import addFormats from 'ajv-formats';
import userSchema from '../schemas/user.schema.json';
import userFixture from '../fixtures/users/valid-user.json';

const ajv = new Ajv2020();
addFormats(ajv);
const validate = ajv.compile(userSchema);

describe('user fixture', () => {
  it('matches the schema', () => {
    const ok = validate(userFixture);
    expect(ok, JSON.stringify(validate.errors)).toBe(true);
  });
});

Bei Schema-Änderungen: Tests werden rot, du siehst sofort welche Fixtures angepasst werden müssen.

Stufe 3: Response-Validation als Contract-Test

Endpoint-Tests, die das Response-Body gegen das Response-Schema prüfen:

import { describe, it, expect } from 'vitest';
import request from 'supertest';
import Ajv2020 from 'ajv/dist/2020.js';
import addFormats from 'ajv-formats';
import { app } from '../app';
import responseSchema from '../schemas/users-get.response.schema.json';

const ajv = new Ajv2020();
addFormats(ajv);
const validate = ajv.compile(responseSchema);

describe('GET /users/:id', () => {
  it('returns a user matching the schema', async () => {
    const res = await request(app).get('/users/123');
    expect(res.status).toBe(200);
    expect(validate(res.body), JSON.stringify(validate.errors)).toBe(true);
  });
});

GitLab-CI-Beispiel

# .gitlab-ci.yml
stages:
  - validate
  - test
  - build

validate:schemas:
  stage: validate
  image: node:22-alpine
  script:
    - npm ci
    - npm run validate:schemas
  rules:
    - changes:
        - 'src/schemas/**/*.schema.json'

test:contracts:
  stage: test
  image: node:22-alpine
  script:
    - npm ci
    - npm run test
  needs:
    - job: validate:schemas
      optional: true

Das optional: true ist nötig, weil validate:schemas wegen rules:changes nicht in jeder Pipeline existiert. Ohne diese Angabe lässt GitLab die Pipeline gar nicht erst entstehen, wenn der benötigte Job fehlt (siehe GitLab-Dokumentation zu needs).

Pre-Commit-Hook für lokale Validation

Mit husky + lint-staged, Datei .lintstagedrc.json. lint-staged hängt die geänderten Dateien hinter den Befehl, daher endet er auf -s:

{
  "src/schemas/**/*.schema.json": [
    "ajv compile --strict=true --spec=draft2020 -c ajv-formats -s"
  ],
  "src/fixtures/**/*.json": [
    "node scripts/validate-fixture.mjs"
  ]
}

Vorteil: Schema-Fehler werden sofort beim Commit gefangen, nicht erst im CI.

OpenAPI-Linting parallel

Wenn du eine OpenAPI-Spec hast: Redocly CLI im selben Build-Step:

npx @redocly/cli lint openapi.yaml
npx @redocly/cli stats openapi.yaml

Typische CI-Fehler und Fix

FehlerFix
"strict mode: unknown keyword: "example""example ist OpenAPI-spezifisch - aus dem Schema entfernen, im Ajv-Code mit ajv.addVocabulary(['example']) bekannt machen oder strict lockern
"can't resolve reference ..."Pfad im $ref prüfen. Liegt das Ziel in einer anderen Datei, in ajv-cli mit -r mitgeben, in Ajv per addSchema oder loadSchema bereitstellen
"unknown format "date-time" ignored in schema"ajv-formats fehlt: in ajv-cli -c ajv-formats, im Code addFormats(ajv) vor ajv.compile()
"schema is invalid: data/required must be array"required ist ein Array von Strings, kein String und kein Objekt
"no schema with key or ref "https://json-schema.org/draft/2020-12/schema""Draft-Version nicht passend: ajv-cli mit --spec=draft2020, im Code Ajv2020 aus ajv/dist/2020.js

Performance-Tipp: pre-compile zur Deploy-Zeit

Ajv kann Schemas vor-kompilieren und als JS-Modul exportieren:

npx ajv-cli compile --spec=draft2020 -c ajv-formats -s schemas/user.schema.json -o dist/user-validate.js

Das fertige Modul lädst du dann zur Laufzeit: keine Compile-Zeit mehr beim App-Start und kein Schema-Parsing. Ganz ohne Pakete kommt es nicht aus: Je nach Schema bindet das erzeugte Modul kleine Hilfsmodule ein, bei format: email zum Beispiel ajv-formats.

Mehr zum Thema

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige