UNPKG

@upv/ushi-shared

Version:

Shared DTOs, types, and utilities for the USHI platform (LMS, Trials, Social, Wallet).

133 lines (132 loc) 3.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IDataSource; (function (IDataSource) { IDataSource["body"] = "body"; IDataSource["params"] = "params"; IDataSource["queries"] = "queries"; IDataSource["payload"] = "payload"; })(IDataSource || (IDataSource = {})); class CheckRules { constructor() { this._values = {}; this._errors = []; this._finalValues = {}; } body(event) { this._values = event.body ? JSON.parse(event.body) : {}; this._dataSource = IDataSource.body; return this; } params(event) { this._values = event.pathParameters || {}; this._dataSource = IDataSource.params; return this; } queries(event) { this._values = event.queryStringParameters || {}; this._dataSource = IDataSource.queries; return this; } payload(payload) { this._values = payload || {}; this._dataSource = IDataSource.payload; return this; } data(data) { this._values = data || {}; this._dataSource = IDataSource.body; return this; } check(property) { this._property = property; this._label = property; this._value = this._values[property]; return this; } label(label) { this._label = label; return this; } and(func) { return func(this); } isRequired() { if (this._value === undefined || (Array.isArray(this._value) && this._value.length === 0) || this._value === '') { this._errors.push({ field: this._property, message: `${this._label} is required in ${this._dataSource}`, }); } return this; } isString() { if (typeof this._value !== 'string') { this._errors.push({ field: this._property, message: `${this._label} must be a string`, }); } else { this._finalValues[this._property] = this._value; } return this; } isEmail() { const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!regex.test(this._value)) { this._errors.push({ field: this._property, message: `${this._label} must be a valid email address`, }); } else { this._finalValues[this._property] = this._value; } return this; } matches(regex) { if (!regex.test(this._value)) { this._errors.push({ field: this._property, message: `${this._label} is in an invalid format`, }); } else { this._finalValues[this._property] = this._value; } return this; } toCamelCase() { if (typeof this._value === 'string') { this._value = this._value.replace(/[-_](\w)/g, (_, c) => c.toUpperCase()); this._finalValues[this._property] = this._value; } return this; } toLowerCase() { if (typeof this._value === 'string') { this._value = this._value.toLowerCase(); this._finalValues[this._property] = this._value; } return this; } validate() { return this._errors.length === 0; } get errors() { return this._errors; } get values() { return this._finalValues; } get errorSummary() { return this._errors.reduce((acc, { field, message }) => { acc[field] = message; return acc; }, {}); } } exports.default = CheckRules;