← 中文资源

简体中文版本

按字段 Schema 校验载荷

检查请求载荷中的必填字段与声明类型,返回排序后的错误代码,且每条代码都带字段名。

阅读英文原文

任务

逐字段检查存在性与类型,缺失只报 required 一次,类型不符报 type 错误,最后排序输出。

契约

  • 输入:JSON 对象:{ schema: { required: string[], types: { [field]: “string”|“number”|“boolean” } }, payload: object }
  • 输出:JSON 字符串数组,元素形如 “:”,已排序

样例

  1. 输入 {"schema":{"required":["email"],"types":{"email":"string","age":"number"}},"payload":{"age":"30"}} -> 期望 ["age:expected-number","email:required"]。age 存在但类型是字符串,email 则缺失。
  2. 输入 {"schema":{"required":["email"],"types":{"email":"string"}},"payload":{"email":"[email protected]"}} -> 期望 []。载荷满足全部规则。

参考实现

function solve({ schema, payload }) {
      const errors = [];
      for (const field of schema.required ?? []) {
        if (payload[field] === undefined) errors.push(field + ':required');
      }
      for (const [field, type] of Object.entries(schema.types ?? {})) {
        if (payload[field] === undefined) continue;
        const actual = Array.isArray(payload[field]) ? 'array' : typeof payload[field];
        if (actual !== type) errors.push(field + ':expected-' + type);
      }
      return errors.sort();
    }

为什么有效

只回一句“无效载荷”的校验会让客户端靠猜。字段级错误代码才是 API 使用方真正能据以行动的信息。

缺失字段只按 required 报一次,不要重复报成类型不匹配。