@everytravel/shared
Version:
A comprehensive shared package for Everytravel containing Mongoose models and CRUD operations for hotel booking, user management, and transaction handling. Updated with improved model syntax and enhanced error handling.
38 lines (31 loc) • 2.15 kB
JavaScript
import mongoose from 'mongoose';
// Primitive validators
export const isNonEmptyString = (value) => typeof value === 'string' && value.trim().length > 0;
export const isEmail = (value) =>
typeof value === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
export const isCurrencyCode = (value) => typeof value === 'string' && /^[A-Z]{3}$/.test(value);
export const isFourDigitString = (value) => typeof value === 'string' && /^\d{4}$/.test(value);
export const isMMYY = (value) => typeof value === 'string' && /^(0[1-9]|1[0-2])\/(\d{2})$/.test(value);
export const isLat = (value) => typeof value === 'number' && value >= -90 && value <= 90;
export const isLng = (value) => typeof value === 'number' && value >= -180 && value <= 180;
export const isNonNegativeNumber = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
export const isInteger = (value) => Number.isInteger(value);
export const isNonNegativeInteger = (value) => Number.isInteger(value) && value >= 0;
export const isPositiveInteger = (value) => Number.isInteger(value) && value > 0;
export const isObjectId = (value) => mongoose.Types.ObjectId.isValid(String(value));
// Sanitizers / setters
export const trimIfString = (value) => (typeof value === 'string' ? value.trim() : value);
export const uppercaseIfString = (value) => (typeof value === 'string' ? value.toUpperCase() : value);
export const arrayOfStringsSanitizer = (arr) =>
Array.isArray(arr) ? arr.map((s) => (typeof s === 'string' ? s.trim() : s)).filter((s) => typeof s === 'string' && s.length > 0) : arr;
// Cross-field helpers
export const validateGreaterThan = (otherPath) => function comparator(value) {
const other = this.get(otherPath);
if (value === undefined || value === null || other === undefined || other === null) return true;
return value > other;
};
export const validateGreaterOrEqualThan = (otherPath) => function comparator(value) {
const other = this.get(otherPath);
if (value === undefined || value === null || other === undefined || other === null) return true;
return value >= other;
};