示例工程 09-typed-ipc-contracts
09-typed-ipc-contracts/demo-01-validator-trace/validator.ts
type Plan = "free" | "pro";
type SubscribeReq = {
name: string;
email: string;
plan: Plan;
};
class BadRequest extends Error {
readonly code: string;
constructor(code: string, message: string) {
super(message);
this.name = "BadRequest";
this.code = code;
}
}
function parse(value: unknown): SubscribeReq {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new BadRequest("BAD_SHAPE", "请求必须是对象");
}
const record = value as Record<string, unknown>;
for (const key of Object.keys(record)) {
if (!["name", "email", "plan"].includes(key)) {
throw new BadRequest("UNKNOWN_FIELD", `不支持的字段:${key}`);
}
}
if (typeof record.name !== "string" || record.name.trim().length === 0) {
throw new BadRequest("NAME_EMPTY", "name 不能为空");
}
if (record.name.length > 40) {
throw new BadRequest("NAME_TOO_LONG", "name 不能超过 40 字符");
}
if (typeof record.email !== "string" || !record.email.includes("@")) {
throw new BadRequest("EMAIL_INVALID", "email 格式不正确");
}
if (record.email.length > 120) {
throw new BadRequest("EMAIL_TOO_LONG", "email 不能超过 120 字符");
}
if (record.plan !== "free" && record.plan !== "pro") {
throw new BadRequest("PLAN_INVALID", "plan 只能是 free 或 pro");
}
return { name: record.name.trim(), email: record.email, plan: record.plan };
}
const cases: Array<{ name: string; expected: string; input: unknown }> = [
{
name: "合法请求",
expected: "OK",
input: { name: "Ada", email: "ada@example.com", plan: "pro" },
},
{
name: "空 name",
expected: "NAME_EMPTY",
input: { name: " ", email: "ada@example.com", plan: "free" },
},
{
name: "name 超长",
expected: "NAME_TOO_LONG",
input: { name: "x".repeat(41), email: "ada@example.com", plan: "free" },
},
{
name: "email 缺 @",
expected: "EMAIL_INVALID",
input: { name: "Ada", email: "ada.example.com", plan: "free" },
},
{
name: "plan 非法",
expected: "PLAN_INVALID",
input: { name: "Ada", email: "ada@example.com", plan: "team" },
},
{
name: "未知字段",
expected: "UNKNOWN_FIELD",
input: { name: "Ada", email: "ada@example.com", plan: "free", admin: 1 },
},
];
const results = cases.map((item) => {
let actual = "OK";
try {
parse(item.input);
} catch (error) {
actual = error instanceof BadRequest ? error.code : "UNKNOWN";
}
return {
name: item.name,
expected: item.expected,
actual,
ok: actual === item.expected,
};
});
const passed = results.filter((item) => item.ok).length;
console.log(
JSON.stringify({
evt: "smoke",
ok: passed === results.length,
total: results.length,
passed,
cases: results,
}),
);