npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

schemas-lib

v3.0.0-next.0

Published

Table of contents

Downloads

186

Readme

schemas-lib

Table of contents

Table of contents

Introdução

schemas-lib é uma biblioteca Node.js inspirada no Zod, desenvolvida para validação de esquemas e tipagem estática em TypeScript. Assim como o Zod, schemas-lib oferece uma interface intuitiva e expressiva para definir e validar estruturas de dados, proporcionando uma experiência de desenvolvimento robusta e confiável.

Diferenças com outras libs

A primeira diferença é que schemas-lib foca em fazer parsing de query strings e forms, então alguns campos como boolean aceitam valores como "on" por padrão

Então um object ou array ao receber uma string, já considera que seja um json e faz parse

const obj = object({ id: int() });
obj.parse('{ "id": 1 }'); // { id: 1 }

Uma das diferenças entre uma lib como a zod é que o schemas-lib possui o foco em reusar instancias como trimmed, salvando um pouco de performance de maneira geral (linter, build, production)

E o schemas-lib faz uso extenso do trimmed, assim quase todos os campos costumam receber trim por padrão

import { z } from 'zod';
import { trimmed, string } from 'schemas-lib';

const zodSchema = z.string().trim();
const schemaLib = trimmed(); // trimmed é o mesmo que zod.string().trim()

Quando se faz qualquer operação com o trimmed ele é clonado como no zod para não alterar o schema original e manter a integridade do schema

O schemas-lib gera a tipagem do objeto em uma propriedade do meta, meta.jsTypeaonde possue um Type do TypeScript

Basic usage

Creating a simple string schema

import { trimmed, string } from 'schemas-lib';

// creating a schema for strings
const mySchema = trimmed();

// parsing
trimmed().parse('tuna'); // => "tuna"
trimmed().parse(12); // => throws ZodError

// "safe" parsing (doesn't throw error if validation fails)
string().safeParse('tuna'); // => 'tuna'
string().safeParse(12); // => Issue object

Creating an object schema

import { object, trimmed, Infer } from 'schemas-lib';

const user_schema = object({
  username: trimmed(),
});

user_schema.parse({ username: 'Ludwig   ' }); // { username: 'Ludwig' }

// extract the inferred type
type User = infer<typeof User>;
// { username: string }

Primitives

import {
  array,
  boolean,
  datetimeUTC,
  enumType,
  float,
  int,
  mixin,
  number,
  object,
  partialUpdateObj,
  strict,
  string,
  trimmed,
} from 'schemas-lib';

// Most used types
trimmed;
boolean;
int;

// generic string and number
string;
number;
float;

// objects
object;
strict;
partialUpdateObj;

array;
enumType;
mixin;

datetimeUTC;

// prebuilt
id;
intString;
url;
nameField;
email;
date;

datetimeUTC

The datetimeUTC schema validates a utc date string or a object Date, and keep the date in string without the miliseconds

import { datetimeUTC } from 'schemas-lib';

datetimeUTC.parse('2023-07-20T21:19:25.711Z'); // pass and removes .711
datetimeUTC.parse('2020-1-1'); // fail
datetimeUTC.parse('2020-01-32'); // fail

distinct and literal

A literal schema is a schema that only accepts a single value. It is useful with distinct

A distinct schema is a schema that differs two other object schemas, based with the distinct key

Is similar to Discriminated unions from Zod

It is useful for things like WebSocket messages, where the server sends a message with a type field that determines the structure of the rest of the message

import { distinct, literal } from 'schemas-lib';

const object_with_name = object({
  type: literal(1),
  name: nameField,
});

const object_with_email = object({
  type: literal(2),
  email: email,
});

const _distinct = distinct('type', [obj1, obj2]);

Versão 3.0.0

A versão 3 vai adotar algumas diferenças da 2, sendo que todos os Schemas serão criados com uma função

Exemplo:

import { string, int } from 'schemas-lib';

// Atualmente
const schema = string.min(1).max(10);

// Versão 3
const schema = string().min(1).max(10);

Essa mudança é para dar mais consistencia e melhorar o Three shaking da lib, pois no momento atual, o Three shaking não funciona muito bem por modificar o prototype dos Schemas

Changelog

View the changelog at CHANGELOG.md