smartguard/readme.md

282 lines
12 KiB
Markdown
Raw Normal View History

2024-04-14 15:39:13 +00:00
# @push.rocks/smartguard
2024-05-30 13:08:09 +00:00
A library for creating and managing validation guards.
2019-08-07 14:34:34 +00:00
2024-04-14 15:39:13 +00:00
## Install
To install `@push.rocks/smartguard`, run the following command in your terminal:
```bash
npm install @push.rocks/smartguard --save
```
This will add `@push.rocks/smartguard` to your project's dependencies.
2019-08-07 14:34:34 +00:00
## Usage
2024-05-30 13:08:09 +00:00
`@push.rocks/smartguard` provides a robust 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.
2024-04-14 15:39:13 +00:00
### 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
2024-05-30 13:08:09 +00:00
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.
2024-04-14 15:39:13 +00:00
```typescript
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.
```typescript
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`.
```typescript
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.
```typescript
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.
```typescript
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);
2024-05-30 13:08:09 +00:00
if (!isAuthorized) {
2024-04-14 15:39:13 +00:00
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.
2024-05-30 13:08:09 +00:00
### Combining Guards with `GuardSet`
2024-04-14 15:39:13 +00:00
2024-05-30 13:08:09 +00:00
One of the strengths of `@push.rocks/smartguard` is its ability to combine multiple guards into a `GuardSet`. This is particularly useful when you need to validate data against several criteria. For example, to validate a string that must be non-empty and start with a specific prefix:
2024-04-14 15:39:13 +00:00
2024-05-30 13:08:09 +00:00
```typescript
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 startsWithPrefixGuard = new Guard<string>(async (data) => {
return data.startsWith('prefix');
});
const combinedValidationSet = new GuardSet<string>([isStringGuard, isNotEmptyGuard, startsWithPrefixGuard]);
const validationResults = await combinedValidationSet.executeGuardsWithData('prefix: Valid String');
console.log(validationResults.every(result => result)); // true if all validations passed
```
### Integration with Other Libraries
To demonstrate the versatility and integration capabilities of `@push.rocks/smartguard`, let's integrate it with another popular library, `@push.rocks/smartrequest`, for validating API response data.
```typescript
import { Guard } from '@push.rocks/smartguard';
import { smartrequest } from '@push.rocks/smartrequest';
const validApiResponseGuard = new Guard(async (url: string) => {
const response = await smartrequest.request(url, { method: 'GET' });
return response.status === 200;
});
const isValidResponse = await validApiResponseGuard.executeGuardWithData('https://example.com/api/data');
console.log(isValidResponse); // true if the API response status is 200
```
### Real-World Example: Form Validation
Let's create a real-world example where we use `@push.rocks/smartguard` to validate form data in a Node.js application. Suppose we have a user registration form with fields for `username`, `email`, and `password`.
```typescript
import { Guard, GuardSet } from '@push.rocks/smartguard';
// Guards for individual fields
const isUsernameValid = new Guard<string>(async (username) => {
return typeof username === 'string' && username.length >= 3;
});
const isEmailValid = new Guard<string>(async (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return typeof email === 'string' && emailRegex.test(email);
});
const isPasswordStrong = new Guard<string>(async (password) => {
return typeof password === 'string' && password.length >= 8;
});
// Combining guards using GuardSet
const registrationValidationSet = new GuardSet<{ username: string, email: string, password: string }>([
new Guard(async (data) => isUsernameValid.executeGuardWithData(data.username)),
new Guard(async (data) => isEmailValid.executeGuardWithData(data.email)),
new Guard(async (data) => isPasswordStrong.executeGuardWithData(data.password))
]);
// Form data to validate
const formData = {
username: 'exampleUser',
email: 'user@example.com',
password: 'strongpassword123'
};
const formValidationResults = await registrationValidationSet.executeGuardsWithData(formData);
console.log(formValidationResults.every(result => result)); // true if all fields are valid
```
In this example, we used guards to validate each form field. We then combined these guards into a `GuardSet` to validate the entire form data object.
### Validating Nested Objects
`@push.rocks/smartguard` can also handle validation of nested objects. Suppose you need to validate a user profile that includes nested address information.
```typescript
interface UserProfile {
username: string;
email: string;
address: {
street: string;
city: string;
postalCode: string;
};
}
const isStreetValid = new Guard<string>(async (street) => {
return typeof street === 'string' && street.length > 0;
});
const isCityValid = new Guard<string>(async (city) => {
return typeof city === 'string' && city.length > 0;
});
const isPostalCodeValid = new Guard<string>(async (postalCode) => {
return typeof postalCode === 'string' && /^[0-9]{5}$/.test(postalCode);
});
const isAddressValid = new Guard<UserProfile['address']>(async (address) => {
const streetValid = await isStreetValid.executeGuardWithData(address.street);
const cityValid = await isCityValid.executeGuardWithData(address.city);
const postalCodeValid = await isPostalCodeValid.executeGuardWithData(address.postalCode);
return streetValid && cityValid && postalCodeValid;
});
const isUsernameValid = new Guard<string>(async (username) => {
return typeof username === 'string' && username.length >= 3;
});
const isEmailValid = new Guard<string>(async (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return typeof email === 'string' && emailRegex.test(email);
});
const userProfileValidationSet = new GuardSet<UserProfile>([
new Guard(async (data) => isUsernameValid.executeGuardWithData(data.username)),
new Guard(async (data) => isEmailValid.executeGuardWithData(data.email)),
new Guard(async (data) => isAddressValid.executeGuardWithData(data.address))
]);
const userProfile = {
username: 'exampleUser',
email: 'user@example.com',
address: {
street: '123 Main St',
city: 'Anytown',
postalCode: '12345'
}
};
const userProfileValidationResults = await userProfileValidationSet.executeGuardsWithData(userProfile);
console.log(userProfileValidationResults.every(result => result)); // true if user profile is valid
```
In this example, we created a nested guard structure to validate a user profile object that includes address information. Each nested object is validated individually using its specific guards.
### Summary
`@push.rocks/smartguard` provides a powerful framework for creating and managing validation guards in JavaScript and TypeScript applications. The library's flexibility allows it to handle simple boolean checks, asynchronous operations, integration with external APIs, and complex composite validations. Its use of `Guard` and `GuardSet` classes ensures that validations are both modular and reusable.
Whether you are validating form inputs, securing APIs, or ensuring data integrity in your backend services, `@push.rocks/smartguard` simplifies the process and makes your code cleaner and more maintainable.
2024-04-14 15:39:13 +00:00
## License and Legal Information
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](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
2022-03-21 20:53:46 +00:00
2024-04-14 15:39:13 +00:00
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.
2022-03-21 20:53:46 +00:00
2024-04-14 15:39:13 +00:00
### Company Information
2022-03-21 20:53:46 +00:00
2024-04-14 15:39:13 +00:00
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
2019-08-07 14:34:34 +00:00
2024-04-14 15:39:13 +00:00
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
2019-08-07 14:34:34 +00:00
2024-04-14 15:39:13 +00:00
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.