spectral学习记录

一、安装spectral(使用yarn安装):

1.安装nodejs(版本必须>=10.8)

(1)下载

wget https://npm.taobao.org/mirrors/node/v14.15.1/node-v14.15.1-linux-x64.tar.xz

(2)解压

tar -xvf node-v14.15.1-linux-x64.tar.xz

mv node-v14.15.1-linux-x64 /usr/local/nodejs/

(3)配置环境变量

vim /etc/profile

export NODEJS_HOME=/usr/local/nodejs
export PATH=${NODEJS_HOME}/bin:${PATH}

source /etc/profile

2.安装yarn

npm install -g yarn

3.检验nodejs、npm、yarn是否安装成功

node -v
npm -v 
yarn -v

4.安装spectral

yarn global add @stoplight/spectral

5.检查安装spectral是否成功

spectral  --version

二、使用spectral

spectral lint 需要检测的文件

三、如何添加规则

在规则集文件的rules属性下添加规则。
规则集文件路径: /usr/local/share/.config/yarn/global/node_modules/@stoplight/spectral/dist/rulesets/oas/index.json
如果觉得现有规则集不能满足需要可以添加自定义规则,自定义规则可以使用spectral提供的核心函数(比如要求必须要有operatorId,可以使用核心函数truthy),如果核心函数对自定义规则集还不够,可以创建并使用自定义函数。自定义函数创建过程:首先在functions目录下创建.js文件,该目录应该放在规则集文件旁边,再在规则集文件里的functions数组下(在文件最上部)添加之前创建的函数文件名(不带扩展名)。

1.示例1:在规则集文件的rules属性下添加名为info-should-have-description的规则(使用核心函数):

index.json

"info-should-have-description": {
      "description": "Info object should contain `description` object.", 
      "recommended": true,
      "type": "style",
      "given": "$.info",
      "then": {
        "field": "description",
        "function": "truthy"
        }
    }

2. 示例2:在规则集文件的rules属性下添加名为info-title-hello的规则(创建并使用自定义函数):

index.json

"functions": [
    "oasDocumentSchema",
    "oasExample",
    "oasOp2xxResponse",
    "oasOpFormDataConsumeCheck",
    "oasOpIdUnique",
    "oasOpParams",
    "oasOpSecurityDefined",
    "oasPathParam",
    "oasTagDefined",
    "typedEnum",
    "refSiblings",
    "abc"
  ],

"info-title-hello": {
      "description": "Info title should be `hello` .", 
      "recommended": true,
      "type": "style",
      "given": "$.info.title",
      "then": {
              "function": "abc"
        }
    }

functions/abc.js

module.exports = targetVal => {
  if (targetVal !== "hello") {
    return [
      {
        message: 'Value must equal "hello".',
      },
    ];
  }
};

四、实现在git -commit时使用spectral检测openapi文档

打开项目文件中的.git/hooks/pre-commit.sample,去掉该文件的后缀名,并在其中使用spectral检测文档。
pre-commit

#!/bin/bash
STAGE_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.json' '*.yaml'  '*.yml')
if test ${#STAGE_FILES} -gt 0
then
    echo "Start of spectral examination"

    PASS=true

    for FILE in $STAGE_FILES
    do
        spectral lint $FILE
        if [ $? -eq 1 ]; then
        PASS=false
        fi
    done

    if ! $PASS; then
      echo "Check failed!"
      exit 1
    else
      echo "Check success"
    fi

else
    echo "There are no files to check"
fi

exit 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值