Skip to content

Commit

Permalink
fix: Fixed to treat a single value as an array if it is an array sche…
Browse files Browse the repository at this point in the history
…ma (#49)
  • Loading branch information
chimame authored Dec 27, 2024
1 parent 60c2952 commit 1f0ddf7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
33 changes: 31 additions & 2 deletions coercion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,40 @@ function coerce<T extends GenericSchema | GenericSchemaAsync>(
return pipe(unknown, vTransform(transformFunction), type);
}

/**
* Helpers for coercing array value
* Modify the value only if it's an array, otherwise return the value as-is
*/
function coerceArray<T extends GenericSchema | GenericSchemaAsync>(type: T) {
// `expects` is required to generate error messages for `TupleSchema`, so it is passed to `UnkonwSchema` for coercion.
const unknown = { ...valibotUnknown(), expects: type.expects };
const transformFunction = (output: unknown): unknown => {
if (Array.isArray(output)) {
return output;
}

if (
typeof output === "undefined" ||
typeof coerceFile(coerceString(output)) === "undefined"
) {
return [];
}

return [output];
};

if (type.async) {
return pipeAsync(unknown, vTransform(transformFunction), type);
}

return pipe(unknown, vTransform(transformFunction), type);
}

/**
* Helpers for coercing file
* Modify the value only if it's a file, otherwise return the value as-is
*/
export function coerceFile(file: unknown) {
function coerceFile(file: unknown) {
if (
typeof File !== "undefined" &&
file instanceof File &&
Expand Down Expand Up @@ -205,7 +234,7 @@ export function enableTypeCoercion<
};
return {
coerced: false,
schema: generateReturnSchema(type, arraySchema),
schema: generateReturnSchema(type, coerceArray(arraySchema)),
};
}
case "optional":
Expand Down
11 changes: 9 additions & 2 deletions tests/coercion/schema/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@ describe("array", () => {
test("should pass only arrays", () => {
const schema = object({ select: array(string()) });
const formData = createFormData("select", "1");
const outputForNonArray = parseWithValibot(formData, { schema });

expect(outputForNonArray).toMatchObject({
status: "success",
value: { select: ["1"] },
});

formData.append("select", "2");
formData.append("select", "3");
const output = parseWithValibot(formData, { schema });
const outputForArray = parseWithValibot(formData, { schema });

expect(output).toMatchObject({
expect(outputForArray).toMatchObject({
status: "success",
value: { select: ["1", "2", "3"] },
});
Expand Down

0 comments on commit 1f0ddf7

Please sign in to comment.