用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tools-only/X-Skills --skill validate-api-responses命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
基于 SOC 职业分类
| name | validate-api-responses |
| description | Validate API responses against schemas |
| shortcut | val |
Implement comprehensive API response validation using JSON Schema, OpenAPI specifications, and custom business rules to ensure data integrity and contract compliance.
Use /validate-api-responses when you need to:
DON'T use this when:
This command implements JSON Schema + Ajv as the primary approach because:
Alternative considered: OpenAPI/Swagger validation
Alternative considered: Joi/Yup validation
Before running this command:
Create JSON Schema definitions for all API responses with proper constraints.
Set up validation middleware to intercept and validate responses automatically.
Add business-specific validation rules beyond structural validation.
Configure how validation errors are reported to clients and logged.
Build comprehensive test suites for schema validation and edge cases.
The command generates:
schemas/ - JSON Schema definitions for all endpointsvalidators/ - Compiled validator functionsmiddleware/response-validator.js - Express/Koa middlewaretests/schema-validation.test.js - Validation test suitesdocs/api-schemas.md - Human-readable schema documentationmonitoring/validation-metrics.js - Validation failure tracking// schemas/user-response.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "UserResponse",
"type": "object",
"required": ["id", "email", "createdAt"],
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"email": {
"type": "string",
"format": "email",
"maxLength": 255
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"roles": {
"type": "array",
"items": {
"type": "string",
"enum": ["admin", "user", "moderator"]
},
"minItems": 1,
"uniqueItems": true
},
: {
: ,
: {
: {
: ,
: [, , ]
},
: {
:
}
}
},
: {
: ,
:
},
: {
: ,
:
}
},
:
}
= ();
addFormats = ();
fs = ();
path = ();
{
() {
. = ({
: ,
: ,
: ,
: ,
:
});
(.);
.();
. = .();
. = {};
}
() {
..({
: ,
: ,
: () {
() {
(schemaValue) {
:
data. > ().();
:
!data. && data.;
:
;
}
};
}
});
}
() {
schemaDir = path.(__dirname, );
schemas = {};
fs.(schemaDir).( {
(file.()) {
schema = .(
fs.(path.(schemaDir, file), )
);
schemas[schema.] = schema;
..(schema);
}
});
schemas;
}
() {
(!.[schemaId]) {
schema = .[schemaId];
(!schema) {
();
}
.[schemaId] = ..(schema);
}
.[schemaId];
}
() {
validator = .(schemaId);
valid = (data);
(!valid) {
{
: ,
: .(validator.),
: validator.
};
}
{ : };
}
() {
errors.( ({
: err. || ,
: err.,
: err.,
: err.,
: err.
}));
}
}
= ();
() {
validator = ();
{
enabled = ,
strict = ,
logErrors = ,
includeErrorDetails = process.. !==
} = options;
() {
(!enabled) ();
originalJson = res.;
res. = () {
schemaId = (req., res.);
(schemaId) {
result = validator.(schemaId, data);
(!result.) {
(logErrors) {
.(, {
: req.,
: req.,
schemaId,
: result.
});
}
(strict) {
originalJson.(, {
: ,
: includeErrorDetails ? result. :
});
}
}
}
originalJson.(, data);
};
();
};
}
() {
schemaMap = {
: ,
: ,
: ,
: ,
:
};
routeKey = ;
schemaMap[routeKey];
}
. = createResponseValidationMiddleware;
// validators/openapi-validator.js
const OpenAPIValidator = require('express-openapi-validator');
const SwaggerParser = require('@apidevtools/swagger-parser');
const fs = require('fs');
const yaml = require('js-yaml');
class OpenAPIResponseValidator {
constructor(specPath) {
this.specPath = specPath;
this.spec = null;
this.middleware = null;
}
async initialize() {
// Parse and validate OpenAPI spec
this.spec = await SwaggerParser.validate(this.specPath);
// Create validation middleware
this.middleware = OpenAPIValidator.middleware({
apiSpec: this.specPath,
validateRequests: false, // Only validate responses
: {
: ,
: ,
: {
.(, {
: req.,
: req.,
: error.,
: error.
});
}
},
:
});
;
}
() {
.;
}
() {
operation = .(path, method);
(!operation) {
();
}
responseSpec = operation.[status];
(!responseSpec) {
();
}
schema = responseSpec.?.[]?.;
(!schema) {
{ : };
}
.(response, schema);
}
() {
pathItem = ..[path];
pathItem?.[method.()];
}
() {
= ();
ajv = ();
valid = ajv.(schema, data);
{
valid,
: ajv.
};
}
}
validator = ().();
app.(validator.());
// validators/business-rules.js
class BusinessRuleValidator {
constructor() {
this.rules = new Map();
this.registerDefaultRules();
}
registerDefaultRules() {
// User-related rules
this.addRule('user.ageRestriction', (user) => {
if (user.role === 'admin' && user.age < 21) {
return 'Admins must be at least 21 years old';
}
return null;
});
this.addRule('user.emailDomain', (user) => {
if (user.role === 'employee' && !user.email.endsWith('@company.com')) {
return 'Employees must use company email';
}
return null;
});
// Order-related rules
this.addRule('order.minimumAmount', (order) => {
const total = order..(
sum + (item. * item.),
);
(total < ) {
;
}
;
});
.(, (order) => {
( item order.) {
available = (item.);
(available < item.) {
;
}
}
;
});
}
() {
..(name, validator);
}
() {
errors = [];
applicableRules = .(..())
.( name.(context));
( [name, validator] applicableRules) {
{
error = (data);
(error) {
errors.({
: name,
: error
});
}
} (e) {
errors.({
: name,
:
});
}
}
{
: errors. === ,
errors
};
}
}
() {
originalJson = res.;
validator = ();
res. = () {
context = (req.);
(context) {
result = validator.(context, data);
(!result.) {
.(, result.);
(process.. === ) {
originalJson.(, {
: ,
: result.
});
}
}
}
originalJson.(, data);
};
();
}
| Error | Cause | Solution |
|---|---|---|
| "Schema not found" | Missing schema file | Ensure schema exists in schemas/ directory |
| "Invalid schema" | Malformed JSON Schema | Validate schema with JSON Schema validator |
| "Circular reference" | Schema references itself | Refactor schema to avoid circular dependencies |
| "Performance degradation" | Large payload validation | Use streaming validation or async processing |
| "Memory leak" | Schema compilation on every request | Cache compiled validators |
Validation Modes
strict: Reject invalid responses (production)permissive: Log but allow invalid responses (development)monitor: Send metrics without blocking (staging)Performance Tuning
cacheSize: Number of compiled schemas to cache (default: 100)maxDepth: Maximum recursion depth for nested objects (default: 10)timeout: Maximum validation time in ms (default: 1000)DO:
DON'T:
/api-contract-generator - Generate schemas from code/api-documentation-generator - Document schemas/api-testing-framework - Test against schemas/api-versioning-manager - Handle schema evolution