You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Spectral JavaScript API校验OpenAPI规范返回空结果问题排查

Spectral校验OpenAPI规范返回空数组问题排查

问题描述

尝试使用Spectral的JavaScript API校验OpenAPI规范,但即使规范明显不符合规则,校验结果始终返回空数组。

测试代码(Jest)

const myLinter = require('#root/src/main/linter.js');
test('will it work?', async () => {
   await myLinter.lint("open-api.yaml", "rules.yaml");
});

Linter核心代码(linter.js)

const { fetch } = require('@stoplight/spectral-runtime')
const { Spectral, Document } = require('@stoplight/spectral-core')
const Parsers = require('@stoplight/spectral-parsers')
const fs = require('fs')
const path = require('path')
const { bundleAndLoadRuleset } = require('@stoplight/spectral-ruleset-bundler/with-loader')
const { DiagnosticSeverity } = require('@stoplight/types')

const lint = async (openApiFileName, rulesetFileName) => {
    const ruleset = await bundleAndLoadRuleset(path.resolve(path.join('src/test', rulesetFileName)), { fs, fetch });
    const spectral = new Spectral();
    spectral.setRuleset(ruleset);

    const resolved = path.resolve(path.join('src/test', openApiFileName));
    const body = fs.readFileSync(resolved, 'utf8');
    let document = new Document(body, Parsers.Yaml, resolved);

    let results = await spectral.run(document);
    console.log(results);
}

module.exports = {lint}

测试规则(rules.yaml)

rules:
  resource-names-plural:
    severity: warn
    message: "Resource names should generally be plural"
    given: "$.paths"
    then:
      function: pattern
      functionOptions:
        match: "^hello$"

问题原因

规则中的given: "$.paths"指向的是整个paths对象,而pattern函数默认会校验该对象的值(即各个路径的具体定义,比如get/post方法配置),而非paths对象的键(也就是你要检查的路径名称)。这就导致规则实际校验的目标和预期完全不符,自然不会返回任何结果。

解决方案

修改规则,让pattern函数作用于paths对象的键(路径名称),有两种写法可选:

写法一:使用property指定校验对象的键

rules:
  resource-names-plural:
    severity: warn
    message: "Resource names should generally be plural"
    given: "$.paths"
    then:
      function: pattern
      functionOptions:
        match: "^hello$"
        property: "@keys" # 指定校验paths对象的所有键

写法二:通过field定位到键

rules:
  resource-names-plural:
    severity: warn
    message: "Resource names should generally be plural"
    given: "$.paths"
    then:
      - field: "@keys" # 定位到paths的所有键
        function: pattern
        functionOptions:
          match: "^hello$"

修改后再运行校验,就能正确检测到不符合规则的路径名称,返回对应的校验结果。

内容的提问来源于stack exchange,提问作者Tobias Neubert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 00:48:38