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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cargolift-cdi/lib-payload

v0.1.42

Published

Lib de tratamento e validação de payloads para serviços do middleware da Cargolift CDI

Downloads

4,014

Readme

@cargolift-cdi/lib-payload · PayloadValidation

Biblioteca utilizada pelos serviços do middleware para validar payloads antes de publicá-los ou processá-los. O PayloadValidation aplica regras declarativas, suporta objetos ou strings JSON e retorna um relatório padronizado com todos os erros encontrados.

Instalação

npm install @cargolift-cdi/lib-payload

Uso rápido

import { PayloadValidation, Schema } from "@cargolift-cdi/lib-payload";

const schema: Schema = {
  validations: [
    { field: "order/id", required: true, type: "string", length: { min: 3, max: 36 } },
    { field: "items", type: "array", minItems: 1 },
    { field: "items/qty", type: "number", range: { min: 1 }, message: "Quantidade mínima por item é 1" },
  ],
};

const validator = new PayloadValidation();
const result = await validator.run(payloadOuJson, schema);

if (!result.success) {
  console.error(result.errorsList);
}

Campos disponíveis no schema

| Propriedade | Uso | | --- | --- | | field | Caminho do campo. Use / para navegar entre níveis (ex.: address/city). Arrays são percorridos automaticamente: items/qty valida cada qty dentro de items. | | required | Garante presença do campo. | | allowNull | Quando false, recusa valores null mesmo que o campo exista. | | type | Valida o tipo do conteúdo. Tipos suportados: string, number, boolean, date, dateISO, object, array, email. | | length | Restrições para strings (min, max). | | range | Faixas para números (min, max). | | minItems / maxItems | Controle de tamanho de arrays. | | allowedValues | Lista de valores aceitos. Combina com ignoreCase para strings. | | ignoreCase | Quando true, compara allowedValues sem diferenciar maiúsculas/minúsculas. | | pattern | Expressão regular aplicada ao valor (somente strings). | | message | Mensagem personalizada exibida quando a regra falhar. |

Como os caminhos são avaliados

  • customer/name acessa propriedades aninhadas.
  • contacts/type aplica a regra a cada item da coleção contacts.
  • Valores inexistentes retornam undefined, permitindo diferenciar campos ausentes de campos nulos (allowNull).

Tipos especiais

  • date: aceita objetos Date ou strings DD/MM/YYYY, DD-MM-YYYY e formatos reconhecidos por Date.parse.
  • dateISO: exige ISO 8601 (2025-11-05T14:48:00.000Z).
  • email: aplica regex simples user@domain.

Exemplos práticos

1. Validando um payload bruto (string JSON)

const rawPayload = '{"order":{"id":"ORD-9","value":0},"items":[]}';

const schema: Schema = {
  validations: [
    { field: "order/id", required: true, type: "string" },
    { field: "order/value", type: "number", range: { min: 1 }, message: "Valor mínimo do pedido é 1" },
    { field: "items", type: "array", minItems: 1 },
  ],
};

const validation = new PayloadValidation();
const result = await validation.run(rawPayload, schema);

/* result.errors => [
  { field: 'order/value', value: 0, error: 'Valor mínimo do pedido é 1' },
  { field: 'items', value: [], error: "Campo 'items' deve conter ao menos 1 itens" }
] */

2. AllowedValues com ignoreCase e campos opcionais

const payload = {
  status: "APPROVED",
  channel: null,
};

const schema: Schema = {
  validations: [
    {
      field: "status",
      type: "string",
      allowedValues: ["pending", "approved", "rejected"],
      ignoreCase: true,
    },
    {
      field: "channel",
      allowNull: false,
      required: false,
      type: "string",
      message: "Canal precisa ser informado quando enviado",
    },
  ],
};

const { success, errors } = await new PayloadValidation().run(payload, schema);
// success === false porque allowNull=false e channel veio como null

Estrutura do resultado

PayloadValidation.run() retorna ValidationResult:

{
  success: boolean;
  errors: Array<{
    field: string;
    value: any;       // valor que falhou
    error: string;    // mensagem final
    rule?: SchemaValidation; // regra original (útil para auditorias)
  }>;
  errorsList: string[]; // mensagens simples
}
  • Em caso de payload malformado (JSON inválido), o erro é registrado com field = "_schema" e value contém o conteúdo bruto.
  • Nenhuma exceção é propagada para regras inválidas; a execução continua e todos os erros são agregados.

Tratamento do payload

  • Aceita objetos JavaScript ou strings JSON.
  • Caso receba string, a biblioteca detecta o formato e tenta fazer JSON.parse (XML pode ser suportado futuramente, ver detectType).
  • Falhas de parsing disparam BusinessError com código INVALID_PAYLOAD, permitindo padronizar a resposta HTTP ou o nack de mensagens.

Testes

A suíte usa Vitest e cobre cenários básicos de schema, tipos e parsing.

npm test

Execute os testes antes de publicar (npm prepublishOnly) para garantir que regressões sejam detectadas.