Helper Functions

Utility functions available throughout your MiniWork application.

HTML Helpers

escapeHtml
escapeHtml(text: string): string

Escape HTML special characters to prevent XSS.

Parameters
NameTypeDescription
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);
// &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;
htmlResponse
htmlResponse(html: string, status?: number): Response

Create an HTML Response with proper Content-Type header.

Parameters
NameTypeDescription
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
NameTypeDescription
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): string

Format a date for display.

Parameters
NameTypeDescription
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): string

Get relative time string (e.g., '5 minutes ago').

Parameters
NameTypeDescription
date string | Date Date to compare
Returns: string - Relative time string
Example
timeAgo(comment.createdAt); // "5 minutes ago"
timeAgo(post.publishedAt);   // "2 days ago"