syv-webapp-commons
v1.0.1
Published
Common utilities, messages, and helpers for web applications
Downloads
5
Maintainers
Readme
webapp-commons
A comprehensive utility package containing common functions, messages, validators, and helpers for web applications. Includes special support for Lao language features.
Installation
npm install syv-webapp-commonsFeatures
- Messages: Pre-defined validation, success, error, and UI messages
- Validators: Common validation functions for forms and data
- Formatters: Format dates, numbers, currency, phone numbers, etc.
- HTTP Utilities: Request helpers, status checkers, URL builders
- Date Utilities: Date manipulation with Lao date format support
- String Utilities: Text processing with Lao language support
Usage
const {
messages,
validators,
formatters,
httpUtils,
dateUtils,
stringUtils
} = require('webapp-commons');Messages
// Validation messages
console.log(messages.VALIDATION_MESSAGES.REQUIRED); // "This field is required"
console.log(messages.VALIDATION_MESSAGES.MIN_LENGTH(8)); // "Must be at least 8 characters long"
// Success messages
console.log(messages.SUCCESS_MESSAGES.SAVE_SUCCESS); // "Successfully saved!"
// Error messages
console.log(messages.ERROR_MESSAGES.NETWORK_ERROR); // "Network error. Please check your connection."
// UI messages
console.log(messages.UI_MESSAGES.LOADING); // "Loading..."
console.log(messages.UI_MESSAGES.ITEM_SELECTED(3)); // "3 items selected"
// Common labels
console.log(messages.COMMON_LABELS.EMAIL); // "Email"Validators
// Basic validation
validators.isRequired('hello'); // true
validators.isValidEmail('[email protected]'); // true
validators.isValidPassword('Password123'); // true
// Form validation
const formData = {
email: '[email protected]',
password: '123'
};
const rules = {
email: [
{ required: true },
{ email: true }
],
password: [
{ required: true },
{ minLength: 8 }
]
};
const result = validators.validateForm(formData, rules);
console.log(result.isValid); // false
console.log(result.errors); // { password: "Must be at least 8 characters" }Formatters
// Currency
formatters.formatCurrency(1234.56); // "$1,234.56"
formatters.formatCurrency(1234.56, 'EUR', 'de-DE'); // "1.234,56 €"
// Dates
formatters.formatDate(new Date(), 'medium'); // "Jan 15, 2024"
formatters.formatTimeAgo(new Date(Date.now() - 3600000)); // "1 hour ago"
// File size
formatters.formatFileSize(1048576); // "1 MB"
// Phone numbers
formatters.formatPhoneNumber('1234567890'); // "(123) 456-7890"
// Names
formatters.formatName('john doe'); // "John Doe"
formatters.formatInitials('John Doe'); // "JD"HTTP Utilities
// Status checking
httpUtils.isSuccessStatus(200); // true
httpUtils.isClientError(404); // true
// URL building
const url = httpUtils.buildUrl('https://api.example.com', '/users', {
page: 1,
limit: 10
}); // "https://api.example.com/users?page=1&limit=10"
// Query string handling
const params = httpUtils.parseQueryString('?name=John&age=30');
console.log(params); // { name: 'John', age: '30' }
// HTTP requests with retry
const data = await httpUtils.withRetry(() =>
httpUtils.get('https://api.example.com/data')
);
// Simple HTTP methods
const userData = await httpUtils.get('/api/users/1');
const newUser = await httpUtils.post('/api/users', { name: 'John' });
await httpUtils.put('/api/users/1', { name: 'Jane' });
await httpUtils.delete('/api/users/1');Date Utilities
// Date manipulation
const tomorrow = dateUtils.addDays(new Date(), 1);
const nextMonth = dateUtils.addMonths(new Date(), 1);
// Date checking
dateUtils.isToday(new Date()); // true
dateUtils.isYesterday(new Date(Date.now() - 86400000)); // true
// Lao date formatting
dateUtils.toLaoDateFormat(new Date()); // "15/01/2024"
dateUtils.toLaoFullDateFormat(new Date()); // "ວັນອາທິດ, 15 ມັງກອນ 2024"
dateUtils.getCurrentLaoDate(); // "15/01/2024"
// Buddhist Era conversion
dateUtils.gregorianToBuddhist(2024); // 2567
dateUtils.buddhistToGregorian(2567); // 2024
// Lao date with Buddhist Era
dateUtils.toLaoDateWithBE(new Date()); // "15/01/2567"
// Date validation
dateUtils.isValidLaoDateFormat('15/01/2024'); // trueString Utilities
// Case conversion
stringUtils.capitalize('hello world'); // "Hello world"
stringUtils.toTitleCase('hello world'); // "Hello World"
stringUtils.toCamelCase('hello world'); // "helloWorld"
stringUtils.toKebabCase('Hello World'); // "hello-world"
stringUtils.toSnakeCase('Hello World'); // "hello_world"
// Text processing
stringUtils.slugify('Hello World!'); // "hello-world"
stringUtils.truncateWords('This is a long sentence', 3); // "This is a..."
stringUtils.countWords('Hello world'); // 2
stringUtils.getReadingTime('Lorem ipsum...'); // "2 minutes"
// Validation
stringUtils.isNumeric('12345'); // true
stringUtils.isAlpha('hello'); // true
stringUtils.isAlphanumeric('hello123'); // true
// Lao language support
stringUtils.toLaoNumerals('123'); // "໑໒໓"
stringUtils.fromLaoNumerals('໑໒໓'); // "123"
stringUtils.containsLaoText('Hello ສະບາຍດີ'); // true
// Data extraction
stringUtils.extractEmails('Contact us at [email protected] or [email protected]');
// ["[email protected]", "[email protected]"]
stringUtils.extractUrls('Visit https://example.com or https://test.com');
// ["https://example.com", "https://test.com"]API Reference
Messages Module
VALIDATION_MESSAGES: Form validation messagesSUCCESS_MESSAGES: Success operation messagesERROR_MESSAGES: Error messagesUI_MESSAGES: User interface messagesHTTP_STATUS_MESSAGES: HTTP status code messagesCOMMON_LABELS: Common form labels
Validators Module
isRequired(value): Check if value is not emptyisValidEmail(email): Validate email formatisValidPassword(password, minLength): Validate password strengthisValidPhone(phone): Validate phone numberisValidUrl(url): Validate URL formatvalidateForm(data, rules): Comprehensive form validation
Formatters Module
formatCurrency(amount, currency, locale): Format currencyformatDate(date, format, locale): Format datesformatTimeAgo(date): Relative time formattingformatFileSize(bytes): Format file sizesformatPhoneNumber(phone, format): Format phone numbers
HTTP Utils Module
get(url, params, options): GET requestpost(url, data, options): POST requestput(url, data, options): PUT requestdelete(url, options): DELETE requestbuildUrl(baseUrl, path, params): Build URLs with query parameterswithRetry(requestFn, maxRetries, delay): Retry failed requests
Date Utils Module
addDays(date, days): Add days to datetoLaoDateFormat(date): Convert to Lao date format (dd/mm/yyyy)toLaoFullDateFormat(date): Format with Lao month/day namesgregorianToBuddhist(year): Convert to Buddhist Era yearisValidLaoDateFormat(dateString): Validate Lao date format
String Utils Module
capitalize(str): Capitalize first lettertoTitleCase(str): Convert to title caseslugify(str): Create URL-friendly slugtoLaoNumerals(str): Convert Arabic to Lao numeralscontainsLaoText(str): Check for Lao charactersextractEmails(str): Extract email addresses from text
Special Features for Lao Language
This package includes special support for Lao language applications:
- Lao Date Formatting: Convert dates to Lao format (dd/mm/yyyy)
- Buddhist Era Support: Convert between Gregorian and Buddhist Era years
- Lao Numerals: Convert between Arabic (0-9) and Lao (໐-໙) numerals
- Lao Text Detection: Check if text contains Lao characters
- Lao Month/Day Names: Full month and day names in Lao language
Testing
npm testContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see the LICENSE file for details.
Support
For support, please create an issue on the GitHub repository or contact the maintainers.
