如何用Redocly强制OpenAPI Schema名称遵循PascalCase规范?
关于Redocly校验Schema PascalCase命名规范的解决方案
1. 自定义规则实现Schema名称PascalCase校验的方法
Redocly支持通过JavaScript编写自定义规则来实现该校验,核心逻辑是遍历components.schemas下的所有键名,用正则匹配验证是否符合PascalCase格式(首字母大写,后续单词首字母也大写,无下划线、连字符等分隔符),然后在配置文件中引入该规则。
2. 是否有内置规则?
Redocly官方推荐的recommended规则集中,没有直接强制Schema名称为PascalCase的内置规则,需要通过自定义规则实现。
3. 自定义规则示例
步骤1:编写自定义规则文件
在项目根目录创建rules/pascal-case-schemas.js文件,内容如下:
module.exports = { meta: { type: 'style', docs: { description: '强制Schema名称使用PascalCase格式', category: '风格规范', recommended: true, }, schema: [], }, create(context) { return { // 遍历components.schemas下的所有Schema节点 'components.schemas.*'(node, path) { const schemaName = path[path.length - 1]; // PascalCase正则:首字母大写,后续为大小写字母或数字,无特殊分隔符 const pascalCaseRegex = /^[A-Z][a-zA-Z0-9]*$/; if (!pascalCaseRegex.test(schemaName)) { context.report({ message: `Schema名称 "${schemaName}" 必须使用PascalCase格式`, path: path, }); } }, }; }, };
步骤2:配置redocly.yaml
修改你的redocly.yaml文件,引入自定义规则:
extends: - recommended # 指定自定义规则存放目录(如果规则不在默认的.redocly/rules下) rulesDir: ./rules rules: # 保留原有禁用/调整的规则 operation-operationId: severity: off security-defined: severity: off operation-summary: severity: off # 启用自定义规则,设置校验级别(error/warning/off) custom/pascal-case-schemas: severity: error
验证效果
运行Redocly校验命令(如redocly lint your-api.yaml),不符合PascalCase格式的my_schema会被检测出来,抛出对应的错误提示。
内容的提问来源于stack exchange,提问作者PARANJAY
相关产品推荐
相关产品推荐

