fix(core): update

This commit is contained in:
Philipp Kunz 2024-05-30 22:09:37 +02:00
parent d53fe44766
commit e0eb81f8d1
6 changed files with 108 additions and 39 deletions

View File

@ -10,9 +10,9 @@
"license": "MIT",
"projectDomain": "push.rocks",
"keywords": [
"typescript",
"validation",
"guards",
"typescript",
"async",
"nodejs",
"express",
@ -25,7 +25,9 @@
"composite validation",
"form validation",
"server-side validation",
"backend validation"
"backend validation",
"smartrequest",
"typedserver"
]
}
},

View File

@ -41,9 +41,9 @@
"last 1 chrome versions"
],
"keywords": [
"typescript",
"validation",
"guards",
"typescript",
"async",
"nodejs",
"express",
@ -56,11 +56,13 @@
"composite validation",
"form validation",
"server-side validation",
"backend validation"
"backend validation",
"smartrequest",
"typedserver"
],
"homepage": "https://code.foss.global/push.rocks/smartguard",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartguard.git"
}
}
}

View File

@ -55,10 +55,10 @@ const stringValidationSet = new GuardSet<string>([isStringGuard, isNotEmptyGuard
### 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`.
To execute a guard or a set of guards against data, you use the `execGuardWithData` method for a single guard, or `execGuardsWithData` method for a `GuardSet`.
```typescript
const isValidString = await isStringGuard.executeGuardWithData('Hello World!');
const isValidString = await isStringGuard.execGuardWithData('Hello World!');
console.log(isValidString); // true
const areValidStrings = await stringValidationSet.executeGuardsWithData('Hello World!');
@ -84,7 +84,7 @@ const isValidAddressGuard = new Guard<string>(async (address) => {
`@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 express from 'express';
import { Guard } from '@push.rocks/smartguard';
const app = express();
@ -94,7 +94,7 @@ const isAuthorizedUserGuard = new Guard<express.Request>(async (req) => {
});
app.use(async (req, res, next) => {
const isAuthorized = await isAuthorizedUserGuard.executeGuardWithData(req);
const isAuthorized = await isAuthorizedUserGuard.execGuardWithData(req);
if (!isAuthorized) {
res.status(403).send('Unauthorized');
return;
@ -145,7 +145,7 @@ const validApiResponseGuard = new Guard(async (url: string) => {
return response.status === 200;
});
const isValidResponse = await validApiResponseGuard.executeGuardWithData('https://example.com/api/data');
const isValidResponse = await validApiResponseGuard.execGuardWithData('https://example.com/api/data');
console.log(isValidResponse); // true if the API response status is 200
```
@ -172,9 +172,9 @@ const isPasswordStrong = new Guard<string>(async (password) => {
// 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))
new Guard(async (data) => isUsernameValid.execGuardWithData(data.username)),
new Guard(async (data) => isEmailValid.execGuardWithData(data.email)),
new Guard(async (data) => isPasswordStrong.execGuardWithData(data.password))
]);
// Form data to validate
@ -218,9 +218,9 @@ const isPostalCodeValid = new Guard<string>(async (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);
const streetValid = await isStreetValid.execGuardWithData(address.street);
const cityValid = await isCityValid.execGuardWithData(address.city);
const postalCodeValid = await isPostalCodeValid.execGuardWithData(address.postalCode);
return streetValid && cityValid && postalCodeValid;
});
@ -234,9 +234,9 @@ const isEmailValid = new Guard<string>(async (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))
new Guard(async (data) => isUsernameValid.execGuardWithData(data.username)),
new Guard(async (data) => isEmailValid.execGuardWithData(data.email)),
new Guard(async (data) => isAddressValid.execGuardWithData(data.address))
]);
const userProfile = {
@ -296,7 +296,7 @@ const isStringGuard = new Guard<string>(async (data) => {
});
const isNonEmptyStringGuard = new Guard<string>(async (data) => {
return await isStringGuard.executeGuardWithData(data) && data.trim().length > 0;
return await isStringGuard.execGuardWithData(data) && data.trim().length > 0;
});
const isStringArrayGuard = new Guard<string[]>(async (data) => {
@ -309,14 +309,14 @@ const isEmailGuard = new Guard<string>(async (data) => {
});
const isAuthorGuardSet = new GuardSet<BlogPost['author']>([
new Guard(async (data) => await isNonEmptyStringGuard.executeGuardWithData(data.name)),
new Guard(async (data) => await isEmailGuard.executeGuardWithData(data.email))
new Guard(async (data) => await isNonEmptyStringGuard.execGuardWithData(data.name)),
new Guard(async (data) => await isEmailGuard.execGuardWithData(data.email))
]);
const isBlogPostGuardSet = new GuardSet<BlogPost>([
new Guard(async (data) => await isNonEmptyStringGuard.executeGuardWithData(data.title)),
new Guard(async (data) => await isNonEmptyStringGuard.executeGuardWithData(data.content)),
new Guard(async (data) => await isStringArrayGuard.executeGuardWithData(data.tags)),
new Guard(async (data) => await isNonEmptyStringGuard.execGuardWithData(data.title)),
new Guard(async (data) => await isNonEmptyStringGuard.execGuardWithData(data.content)),
new Guard(async (data) => await isStringArrayGuard.execGuardWithData(data.tags)),
new Guard(async (data) => await isAuthorGuardSet.executeGuardsWithData(data.author).then(results => results.every(result => result)))
]);
@ -350,7 +350,7 @@ const isApiKeyValidGuard = new Guard<string>(async (apiKey) => {
});
const apiKey = 'some-api-key';
const isApiKeyValid = await isApiKeyValidGuard.executeGuardWithData(apiKey);
const isApiKeyValid = await isApiKeyValidGuard.execGuardWithData(apiKey);
console.log(isApiKeyValid); // true if the API key is valid
```
@ -399,18 +399,31 @@ class MinLengthGuard extends Guard<string> {
const minLengthGuard = new MinLengthGuard(10);
const isLongEnough = await minLengthGuard.executeGuardWithData('Hello, world!');
const isLongEnough = await minLengthGuard.execGuardWithData('Hello, world!');
console.log(isLongEnough); // true because the length of 'Hello, world!' is more than 10
```
In this example, we create a `MinLengthGuard` class that extends `Guard` and validates a string based on its minimum length.
### Conclusion
`@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.
## 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
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.
## 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.

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartguard',
version: '3.0.1',
version: '3.0.2',
description: 'A TypeScript library for creating and managing validation guards, aiding in data validation and security checks.'
}

View File

@ -2,10 +2,17 @@ import * as plugins from './smartguard.plugins.js';
export type TGuardFunction<T> = (dataArg: T) => Promise<boolean>;
export interface IGuardOptions {
name?: string;
failedHint?: string;
}
export class Guard<T> {
private guardFunction: TGuardFunction<T>;
constructor(guardFunctionArg: TGuardFunction<T>) {
public guardoOptions: IGuardOptions;
constructor(guardFunctionArg: TGuardFunction<T>, optionsArg?: IGuardOptions) {
this.guardFunction = guardFunctionArg;
this.guardoOptions = optionsArg;
}
/**
@ -16,4 +23,13 @@ export class Guard<T> {
const result = await this.guardFunction(dataArg);
return result;
}
public async getFailedHint(dataArg: T) {
const result = await this.exec(dataArg);
if (!result) {
return this.guardoOptions.failedHint;
} else {
return null;
}
}
}

View File

@ -1,6 +1,11 @@
import * as plugins from './smartguard.plugins.js';
import { Guard, type TGuardFunction } from './smartguard.classes.guard.js';
export interface IExecOptions {
mode?: 'parallel' | 'serial';
stopOnFail?: boolean;
}
/**
* Extended GuardSet that inherits from Guard
* and provides additional functionalities.
@ -19,12 +24,23 @@ export class GuardSet<T> extends Guard<T> {
* executes all guards in all guardSets against a data argument
* @param dataArg
*/
public async execAllWithData(dataArg: T) {
public async execAllWithData(dataArg: T, optionsArg: IExecOptions = {
mode: 'parallel',
stopOnFail: false
}): Promise<boolean[]> {
const resultPromises: Array<Promise<boolean>> = [];
for (const guard of this.guards) {
const guardResultPromise = guard.exec(dataArg);
if (optionsArg.mode === 'serial') {
await guardResultPromise;
}
resultPromises.push(guardResultPromise);
if (optionsArg.stopOnFail) {
if (!await guardResultPromise) {
return await Promise.all(resultPromises);
}
}
}
const results = await Promise.all(resultPromises);
@ -35,8 +51,11 @@ export class GuardSet<T> extends Guard<T> {
* checks if all guards pass
* @param dataArg
*/
public async allGuardsPass(dataArg: T): Promise<boolean> {
const results = await this.execAllWithData(dataArg);
public async allGuardsPass(dataArg: T, optionsArg: IExecOptions = {
mode: 'parallel',
stopOnFail: false
}): Promise<boolean> {
const results = await this.execAllWithData(dataArg, optionsArg);
return results.every(result => result);
}
@ -45,7 +64,24 @@ export class GuardSet<T> extends Guard<T> {
* @param dataArg
*/
public async anyGuardsPass(dataArg: T): Promise<boolean> {
const results = await this.execAllWithData(dataArg);
const results = await this.execAllWithData(dataArg, {
mode: 'parallel',
stopOnFail: false
});
return results.some(result => result);
}
/**
* returns the first reason for why something fails
* @param dataArg
* @returns
*/
public getFailedHint (dataArg: T): Promise<string> {
for (const guard of this.guards) {
const failedHint = guard.getFailedHint(dataArg);
if (failedHint) {
return failedHint;
}
}
}
}