Skip to content

A fetch wrapper that leverages Valibot to validate the response with type predicates.

Notifications You must be signed in to change notification settings

chriseagle/lassie

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Lassie

A fetch wrapper with first-class support for type predicate based validation, leveraging Valibot for fast and lean validation via type predicates.

Example Image

Reasoning

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.

Usage

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);
  }
})();

About

A fetch wrapper that leverages Valibot to validate the response with type predicates.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published