A fetch wrapper with first-class support for type predicate based validation, leveraging Valibot for fast and lean validation via type predicates.
Validation of data from internal and trusted sources should still be applied. Skipping validation and only relying on type casting using the "as" operator for type-safety is not sufficient. Lassie aims to provide first-class type predicate based validation for fetch responses.
This light-weight, performance oriented approach is not as strict or heavy as complete object parsing and validation, however it still provides a solid foundation for data based validation.
Lassie is a wrapper around the fetch API that returns an assert functions. The assert function takes a predicate function and returns the data if the predicate is true. If the predicate is false, an error is thrown. This allows for a more concise and readable approach to data validation. Various base predicates are provided for common data types, built around Valibot v.is() function.
import lassie from "../src/core/lassie.js";
import { hasLiteral } from "../src/predicates/index.js";
interface HogwartsStudent {
id: string;
name: string;
alternate_names: string[];
species: string;
gender: string;
house: string;
dateOfBirth: string;
yearOfBirth: number;
wizard: boolean;
ancestry: string;
eyeColour: string;
hairColour: string;
wand: {
wood: string;
core: string;
length: number;
};
patronus: string;
hogwartsStudent: true;
hogWartsStaff: boolean;
actor: string;
alternate_actors: string[];
alive: boolean;
image: string;
}
const API_URL =
"https://hp-api.onrender.com/api/character/9e3f7ce4-b9a7-4244-b709-dae5c1f1d4a8";
(async function example() {
try {
const { assert } = await lassie<HogwartsStudent[]>(API_URL, {
headers: {
"Content-Type": "application/json",
},
});
const data = assert(hasLiteral, "hogwartsStudent", true);
console.log("Received data:", data);
} catch (error) {
console.error("Error:", error);
}
})();
