Helper Functions
Utility functions available throughout your MiniWork application.
HTML Helpers
escapeHtml
escapeHtml(text: string): stringEscape HTML special characters to prevent XSS.
Parameters
| Name | Type | Description |
|---|---|---|
text |
string |
Text to escape |
Returns:
string
- Escaped HTML-safe string
Example
import { escapeHtml } from '@miniwork/core';
const userInput = '<script>alert("xss")</script>';
const safe = escapeHtml(userInput);
// <script>alert("xss")</script>
htmlResponse
htmlResponse(html: string, status?: number): ResponseCreate an HTML Response with proper Content-Type header.
Parameters
| Name | Type | Description |
|---|---|---|
html |
string |
HTML content |
status optional |
number |
HTTP status code Default: 200 |
Returns:
Response
- Fetch API Response object
Example
return htmlResponse('<h1>Hello</h1>');
return htmlResponse('<h1>Not Found</h1>', 404);
Validation Helpers
validate
validate<T>(data: unknown, schema: Schema): ValidationResult<T>Validate data against a schema.
Parameters
| Name | Type | Description |
|---|---|---|
data |
unknown |
Data to validate |
schema |
Schema |
Validation schema |
Returns:
ValidationResult<T>
- Result with valid flag, data, and errors
Example
import { validate } from '@miniwork/core';
const result = validate(body, {
email: { type: 'email', required: true },
password: { type: 'string', minLength: 8 },
age: { type: 'number', min: 18 },
});
if (!result.valid) {
return { errors: result.errors };
}
const { email, password, age } = result.data;
Date Helpers
formatDate
formatDate(date: string | Date, format?: string): stringFormat a date for display.
Parameters
| Name | Type | Description |
|---|---|---|
date |
string | Date |
Date to format |
format optional |
string |
Format string Default: MM/DD/YYYY |
Returns:
string
- Formatted date string
Example
formatDate(user.createdAt); // "1/15/2024"
formatDate(post.publishedAt, 'MMMM D, YYYY'); // "January 15, 2024"
timeAgo
timeAgo(date: string | Date): stringGet relative time string (e.g., '5 minutes ago').
Parameters
| Name | Type | Description |
|---|---|---|
date |
string | Date |
Date to compare |
Returns:
string
- Relative time string
Example
timeAgo(comment.createdAt); // "5 minutes ago"
timeAgo(post.publishedAt); // "2 days ago"