A library for creating and managing validation guards.
Go to file
2024-04-14 17:39:13 +02:00
.vscode BREAKING CHANGE(core): updated to esm 2022-03-21 21:53:46 +01:00
test BREAKING CHANGE(core): updated to esm 2022-03-21 21:53:46 +01:00
ts BREAKING CHANGE(core): updated to esm 2022-03-21 21:53:46 +01:00
.gitignore BREAKING CHANGE(core): updated to esm 2022-03-21 21:53:46 +01:00
.gitlab-ci.yml BREAKING CHANGE(core): updated to esm 2022-03-21 21:53:46 +01:00
license fix(core): update 2019-06-18 14:51:13 +02:00
npmextra.json update tsconfig 2024-04-14 17:39:13 +02:00
package-lock.json 2.0.1 2022-03-22 00:20:28 +01:00
package.json update tsconfig 2024-04-14 17:39:13 +02:00
pnpm-lock.yaml switch to new org scheme 2023-07-11 00:45:43 +02:00
readme.hints.md update tsconfig 2024-04-14 17:39:13 +02:00
readme.md update tsconfig 2024-04-14 17:39:13 +02:00
tsconfig.json update npmextra.json: githost 2024-04-01 21:35:15 +02:00

@push.rocks/smartguard

smart guards for validations

Install

To install @push.rocks/smartguard, run the following command in your terminal:

npm install @push.rocks/smartguard --save

This will add @push.rocks/smartguard to your project's dependencies.

Usage

@push.rocks/smartguard provides a sturdy and easy way to validate data by using guards. Guards are functions that return a Boolean value indicating whether the data meets certain criteria. This package is highly beneficial for input validation, security checks, or any scenario where data needs to conform to specific rules or patterns.

Basics

At the core of @push.rocks/smartguard are two main classes: Guard and GuardSet. A Guard represents a single rule or validation step, while a GuardSet allows you to combine multiple Guard instances and evaluate them together.

Creating a Guard

A Guard is an object that encapsulates a validation rule. You define a guard by providing a function that takes an input and returns a Promise, resolving to a Boolean value indicating if the input meets the criteria.

import { Guard } from '@push.rocks/smartguard';

const isStringGuard = new Guard<string>(async (data) => {
  return typeof data === 'string';
});

In the example above, we define a simple guard that checks if the input is a string.

Using GuardSets for Composite Validations

When you have multiple validation rules, you can combine them using GuardSet. This allows you to evaluate all guards on a piece of data and only pass if all guards return true.

import { Guard, GuardSet } from '@push.rocks/smartguard';

const isStringGuard = new Guard<string>(async (data) => {
  return typeof data === 'string';
});

const isNotEmptyGuard = new Guard<string>(async (data) => {
  return data.length > 0;
});

const stringValidationSet = new GuardSet<string>([isStringGuard, isNotEmptyGuard]);

// Now you can use stringValidationSet.executeGuardsWithData(data) to validate your data

Executing Guards

To execute a guard or a set of guards against data, you use the executeGuardWithData method for a single guard, or executeGuardsWithData method for a GuardSet.

const isValidString = await isStringGuard.executeGuardWithData('Hello World!');
console.log(isValidString); // true

const areValidStrings = await stringValidationSet.executeGuardsWithData('Hello World!');
console.log(areValidStrings.every(result => result)); // true if all validations passed

Advanced Usage: Custom Guard Functions

Guards can perform any asynchronous operation inside their validation function, making them incredibly versatile. For instance, you could call an API to validate an address, check if a username already exists in a database, or even integrate with third-party validation services.

import { Guard } from '@push.rocks/smartguard';
import { someApiRequestFunction } from './myApiFunctions';

const isValidAddressGuard = new Guard<string>(async (address) => {
  const response = await someApiRequestFunction(address);
  return response.isValid;
});

Integrating with Express Middleware

@push.rocks/smartguard can easily integrate with frameworks like Express by utilizing guards within middleware functions. This allows you to perform validations before a request reaches your route handlers.

import * as express from 'express';
import { Guard } from '@push.rocks/smartguard';

const app = express();
const isAuthorizedUserGuard = new Guard<express.Request>(async (req) => {
  // your logic here, return true if authorized
  return req.headers.authorization === 'Bearer some-token';
});

app.use(async (req, res, next) => {
  const isAuthorized = await isAuthorizedUserGuard.executeGuardWithData(req);
  if(!isAuthorized) {
    res.status(403).send('Unauthorized');
    return;
  }
  next();
});

app.listen(3000, () => console.log('Server running on port 3000'));

In the example above, we use a guard to check if a request has a valid authorization header. This demonstrates how @push.rocks/smartguard can be seamlessly integrated into existing server applications to enforce security or input validations.

Conclusion

@push.rocks/smartguard offers a robust, flexible way to perform validations across your application. Whether you're validating simple data types, complex objects, or making asynchronous validation calls, smartguard simplifies the process and makes your code cleaner and more maintainable.

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

Company Information

Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.