@huncyrus/simple-validated-dto
v1.0.2
Published
Simple Validated DTO class for JavaScript projects, using Zod for schema validation and deep-freezing data to ensure immutability.
Downloads
19
Maintainers
Readme
Simple Validated DTO
A self-closing (immutable via freeze), self-building (pass the input, no need to design the class), self-validating (via zod) Data Transfer Object implementation for JavaScript projects.
Reasons
- There are (older) projects where
TypeScriptcan not be used, where validation schemas already exists, the project evolving rapidly (large team) or there are shared schemas across services/modules/functions already. - The nature of JavaScript itself (the lack of private and protected functions)
- Validation requirements (data immutability, guarantee of data structure, etc...)
Features
- Minimal dependency (
zod,vitest) - Easy to use
- JavaScript support without overhead
- Support both
requireandimport(ESM/CommonJs)
Requirements
- Node.js v20+
- Basic
Zodschema knowledge
Usage
Import the dependencies:
npm install @huncyrus/simple-validated-dtoSee the example file.
Import the SimpleValidatedDto:
import { z } from 'zod';
import { SimpleValidatedDto } from '../src/SimpleValidatedDto.js';
// Alias can be used also
// import { SimpleValidatedDto as dto } from '../src/SimpleValidatedDto.js';Create a schema, based on an input or data structure, example:
const myDataInput = {
id: 42,
title: 'Ministry of Silly Walks',
other: '',
};
// schema example
const exampleSchema = z.object({
id: z.number(),
title: z.string().min(1),
other: z.union([z.string(), z.number()]),
});Then pass the data and schema:
const dto = new SimpleValidatedDto(exampleInput, exampleSchema);Retrieve data from DTO
console.log('Data from DTO: ', dto.data);Note: alternatively, use the input fields as
dto.<field-name>to retrieve its value
Mutate via build
The DTO provides a method to mutate the data, which shall create a new object instead of mutation:
const newDto = SimplevalidatedDto.build(newInput, schema);Tests
The DTO uses vitest for unit tests:
npm run testTest Coverage
Test coverate via Vitest:
npm run test:coverageTests via docker
Build the container:
docker build -t simple-validated-dto-tests .
# or rebuild
# docker build --no-cache -t simple-validated-dto-tests .Then run the container:
docker run --rm simple-validated-dto-testsAuthor
Author: Györk Bakonyi
