fortify-schema
Version:
A modern TypeScript validation library designed around familiar interface syntax and powerful conditional validation. Experience schema validation that feels natural to TypeScript developers while unlocking advanced runtime validation capabilities.
69 lines (62 loc) โข 2.1 kB
text/typescript
import { Interface } from "../../schema/mode/interfaces/Interface";
const Schema2 = Interface({
role: "admin|user|guest",
config: "any?",
permissions:
"when config.hasPermissions.$exists() *? string[] : ={test: [1]}",
});
const config = {};
// Test 1: Array with number (should pass)
console.log("๐งช Test 1: Array with number [1]");
const result1 = Schema2.safeParse({
config,
permissions: { test: [1] },
role: "admin",
});
if (result1.success) {
console.log("โ
Expected success:", result1.data);
} else {
console.log("โ Unexpected errors:", result1.errors);
}
// Test 2: Array with string (should fail)
console.log("\n๐งช Test 2: Array with string ['1']");
const result2 = Schema2.safeParse({
config,
permissions: ["1"],
role: "admin",
});
if (result2.success) {
console.log("โ
Unexpected success:", result2.data);
} else {
console.log("โ Expected errors:", result2.errors);
}
// Test 3: String instead of array (should fail)
console.log("\n๐งช Test 3: String '[1]'");
const result3 = Schema2.safeParse({
config,
permissions: "[1]",
role: "admin",
});
if (result3.success) {
console.log("โ
Unexpected success:", result3.data);
} else {
console.log("โ Expected errors:", result3.errors);
}
/**
* output: โ Unexpected errors: [ "permissions: Expected constant value '1', got '1'" ]
*
* when we change from "permissions: [1]" to "permissions: "[1]"":
* โ Unexpected errors: [ "permissions: Expected constant value '1', got '[1]'" ]
*/
/**
* We need to add a logic to determine string from other types in a constant values.
* For example:
* 1) =test => should be interpreted as a string
* 2) =['test'] => should be interpreted as ['test']
* 2) =number => even if its a type but we must keep in mind that,
* all normal constant values are interpretted as string
* except some cases "{}" "[]" or others.
* So we need to update the main readme to explain that also. And also the type inference should
* be updated to avoid errors while typing.
*
*/