fix(config): fix array not getting verified after sanitize (@fehmer) (#6849)

This commit is contained in:
Christian Fehmer 2025-08-08 12:17:27 +02:00 committed by GitHub
parent 3b17e9e998
commit 100050fd1e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 29 additions and 6 deletions

View file

@ -268,6 +268,22 @@ describe("misc.ts", () => {
});
});
it("should remove invalid array elements with min size", () => {
const schema = z
.object({
name: z.string(),
tags: z.array(z.enum(["coder", "developer"])).min(2),
})
.partial();
const obj = {
name: "Alice",
tags: ["developer", "unknown"] as any,
};
expect(sanitize(schema, obj)).toEqual({
name: "Alice",
});
});
it("should remove entire property if all array elements are invalid", () => {
const obj = { name: "Alice", age: 30, tags: [123, 456] as any };
const sanitized = sanitize(schema, obj);
@ -312,9 +328,9 @@ describe("misc.ts", () => {
arrayOneTwo: ["one", "nonexistent"],
} as any;
expect(() => {
sanitize(schema.strip(), obj);
sanitize(schema.required().strip(), obj);
}).toThrowError(
"unable to sanitize: arrayOneTwo: Array must contain at least 2 element(s)"
"unable to sanitize: name: Required, age: Required, tags: Required, enumArray: Required"
);
});
});

View file

@ -754,10 +754,17 @@ export function sanitize<T extends z.ZodTypeAny>(
error.length < value.length //not all items in the array are invalid
) {
//some items of the array are invalid
return [
key,
value.filter((_element, index) => !error.includes(index)),
];
const cleanedArray = value.filter(
(_element, index) => !error.includes(index)
);
const cleanedArrayValidation = schema.safeParse(
Object.fromEntries([[key, cleanedArray]])
);
if (cleanedArrayValidation.success) {
return [key, cleanedArray];
} else {
return [key, undefined];
}
} else {
return [key, undefined];
}