Use Cases Overview
Health Check
Server status monitoring DB, memory, uptime
Utilities
Hash, encryption, UUID String processing
External API
Weather, maps, payments API proxy
Statistics/Aggregation
Dashboard data Multi-table aggregation
1. Health Check & Monitoring
Basic Health Check
// health.frame.ts
import { BaseFrameClass, api } from "sonamu";
class HealthFrame extends BaseFrameClass {
frameName = "Health";
@api({ httpMethod: "GET" })
async check(): Promise<{
status: "ok" | "error";
timestamp: Date;
uptime: number;
}> {
return {
status: "ok",
timestamp: new Date(),
uptime: process.uptime(),
};
}
@api({ httpMethod: "GET" })
async ping(): Promise<{ pong: string }> {
return { pong: "pong" };
}
}
export const HealthFrameInstance = new HealthFrame();
# Kubernetes liveness probe
curl http://api.example.com/api/health/ping
# Monitoring system
curl http://api.example.com/api/health/check
Detailed Health Check
interface HealthDetailResponse {
status: "healthy" | "degraded" | "unhealthy";
timestamp: Date;
uptime: number;
system: {
memory: {
total: number;
used: number;
free: number;
percentage: number;
};
cpu: {
model: string;
cores: number;
loadAverage: number[];
};
};
services: {
database: {
status: "connected" | "disconnected";
responseTime?: number;
};
redis?: {
status: "connected" | "disconnected";
responseTime?: number;
};
};
}
class HealthFrame extends BaseFrameClass {
frameName = "Health";
// Exposes OS, memory, and DB status, so restrict it to admins
@api({ httpMethod: "GET", guards: ["admin"] })
async detail(): Promise<HealthDetailResponse> {
const startTime = Date.now();
// DB connection check
let dbStatus: "connected" | "disconnected" = "disconnected";
let dbResponseTime: number | undefined;
try {
const rdb = this.getPuri("r");
const dbStart = Date.now();
await rdb.raw("SELECT 1");
dbResponseTime = Date.now() - dbStart;
dbStatus = "connected";
} catch (error) {
console.error("Database health check failed:", error);
}
// Memory info
const memoryUsage = process.memoryUsage();
const totalMemory = memoryUsage.heapTotal;
const usedMemory = memoryUsage.heapUsed;
const freeMemory = totalMemory - usedMemory;
// CPU info
const os = require("os");
const cpus = os.cpus();
// Determine overall status
let overallStatus: "healthy" | "degraded" | "unhealthy";
if (dbStatus === "disconnected") {
overallStatus = "unhealthy";
} else if (usedMemory / totalMemory > 0.9) {
overallStatus = "degraded";
} else {
overallStatus = "healthy";
}
return {
status: overallStatus,
timestamp: new Date(),
uptime: process.uptime(),
system: {
memory: {
total: totalMemory,
used: usedMemory,
free: freeMemory,
percentage: (usedMemory / totalMemory) * 100,
},
cpu: {
model: cpus[0]?.model || "unknown",
cores: cpus.length,
loadAverage: os.loadavg(),
},
},
services: {
database: {
status: dbStatus,
responseTime: dbResponseTime,
},
},
};
}
}
2. Encryption & Security Utilities
Hash & Encryption
// crypto.frame.ts
import { BadRequestException, BaseFrameClass, api } from "sonamu";
import crypto from "crypto";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
// The server, not the client, decides the bcrypt cost. Each extra cost point doubles the work,
// and bcrypt runs on the libuv thread pool (4 threads by default), so a few high-cost requests
// also stall file, compression, and DNS work that shares the pool.
const BCRYPT_COST = 12;
// Keep the encryption key and JWT secret on the server; never accept them from the request.
function getEncryptionKey(): Buffer {
const key = Buffer.from(process.env.ENCRYPTION_KEY ?? "", "base64");
if (key.length !== 32) {
throw new Error("ENCRYPTION_KEY must be a base64-encoded 32-byte key");
}
return key;
}
interface HashParams {
text: string;
algorithm: "md5" | "sha256" | "sha512" | "bcrypt";
}
class CryptoFrame extends BaseFrameClass {
frameName = "Crypto";
// Hash generation
@api({ httpMethod: "POST", guards: ["user"] })
async hash(params: HashParams): Promise<{ hash: string }> {
if (params.algorithm === "bcrypt") {
const hash = await bcrypt.hash(params.text, BCRYPT_COST);
return { hash };
}
const hash = crypto.createHash(params.algorithm).update(params.text).digest("hex");
return { hash };
}
// bcrypt verification
@api({ httpMethod: "POST", guards: ["user"] })
async verifyHash(params: { text: string; hash: string }): Promise<{ valid: boolean }> {
// bcrypt.compare uses the cost written in the hash, so reject hashes above the server cap before hashing
const match = /^\$2[aby]\$(\d{2})\$[./A-Za-z0-9]{53}$/.exec(params.hash);
if (!match || Number(match[1]) > BCRYPT_COST) {
throw new BadRequestException("Unsupported hash");
}
const valid = await bcrypt.compare(params.text, params.hash);
return { valid };
}
// AES-256-GCM encryption (with integrity check)
// The user guard only checks sign-in; in production, limit these APIs to data the caller owns
@api({ httpMethod: "POST", guards: ["user"] })
async encrypt(params: { plaintext: string }): Promise<{
ciphertext: string;
iv: string;
tag: string;
}> {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", getEncryptionKey(), iv);
const ciphertext = Buffer.concat([cipher.update(params.plaintext, "utf8"), cipher.final()]);
return {
ciphertext: ciphertext.toString("base64"),
iv: iv.toString("base64"),
tag: cipher.getAuthTag().toString("base64"),
};
}
// AES-256-GCM decryption
@api({ httpMethod: "POST", guards: ["user"] })
async decrypt(params: { ciphertext: string; iv: string; tag: string }): Promise<{
plaintext: string;
}> {
const key = getEncryptionKey();
try {
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(params.iv, "base64"), {
authTagLength: 16,
});
decipher.setAuthTag(Buffer.from(params.tag, "base64"));
const plaintext = Buffer.concat([
decipher.update(Buffer.from(params.ciphertext, "base64")),
decipher.final(),
]);
return { plaintext: plaintext.toString("utf8") };
} catch {
// Return the same error whatever failed (tag mismatch, bad length, ...)
throw new BadRequestException("Unable to decrypt");
}
}
// JWT token verification (simple version)
@api({ httpMethod: "POST", guards: ["user"] })
async verifyToken(params: { token: string }): Promise<{
valid: boolean;
payload?: any;
error?: string;
}> {
try {
// Verify only with the server secret and the allowed algorithm
const payload = jwt.verify(params.token, process.env.JWT_SECRET ?? "", {
algorithms: ["HS256"],
});
return {
valid: true,
payload,
};
} catch (error) {
return {
valid: false,
error: error instanceof Error ? error.message : "Unknown error",
};
}
}
// UUID generation
@api({ httpMethod: "POST" })
async uuid(): Promise<{ uuid: string }> {
return { uuid: crypto.randomUUID() };
}
// Random string generation
@api({ httpMethod: "POST" })
async randomString(params: {
length: number;
charset?: "alphanumeric" | "hex" | "base64";
}): Promise<{ random: string }> {
const length = Math.min(params.length, 1024);
const charset = params.charset || "alphanumeric";
let random: string;
switch (charset) {
case "hex":
random = crypto
.randomBytes(Math.ceil(length / 2))
.toString("hex")
.slice(0, length);
break;
case "base64":
random = crypto
.randomBytes(Math.ceil((length * 3) / 4))
.toString("base64")
.slice(0, length);
break;
case "alphanumeric":
default:
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
random = Array.from(crypto.randomBytes(length))
.map((byte) => chars[byte % chars.length])
.join("");
break;
}
return { random };
}
}
export const CryptoFrameInstance = new CryptoFrame();
3. External API Proxy
Weather API
// weather.frame.ts
import { BaseFrameClass, api } from "sonamu";
import axios from "axios";
class WeatherFrame extends BaseFrameClass {
frameName = "Weather";
private apiKey = process.env.OPENWEATHER_API_KEY || "";
private baseUrl = "https://api.openweathermap.org/data/2.5";
@api({ httpMethod: "GET" })
async current(params: {
city: string;
country?: string;
units?: "metric" | "imperial";
}): Promise<{
city: string;
country: string;
temperature: number;
feelsLike: number;
condition: string;
description: string;
humidity: number;
windSpeed: number;
pressure: number;
visibility: number;
timestamp: Date;
}> {
const query = params.country ? `${params.city},${params.country}` : params.city;
try {
const response = await axios.get(`${this.baseUrl}/weather`, {
params: {
q: query,
appid: this.apiKey,
units: params.units || "metric",
},
timeout: 5000,
});
const data = response.data;
return {
city: data.name,
country: data.sys.country,
temperature: data.main.temp,
feelsLike: data.main.feels_like,
condition: data.weather[0].main,
description: data.weather[0].description,
humidity: data.main.humidity,
windSpeed: data.wind.speed,
pressure: data.main.pressure,
visibility: data.visibility,
timestamp: new Date(),
};
} catch (error) {
if (axios.isAxiosError(error)) {
throw new Error(`Weather API error: ${error.message}`);
}
throw new Error("Failed to fetch weather data");
}
}
@api({ httpMethod: "GET" })
async forecast(params: { city: string; country?: string; days?: number }): Promise<{
city: string;
forecast: Array<{
date: string;
temperature: {
min: number;
max: number;
avg: number;
};
condition: string;
humidity: number;
windSpeed: number;
}>;
}> {
const query = params.country ? `${params.city},${params.country}` : params.city;
const days = Math.min(params.days || 5, 7);
try {
const response = await axios.get(`${this.baseUrl}/forecast`, {
params: {
q: query,
appid: this.apiKey,
units: "metric",
cnt: days * 8, // 3-hour interval data
},
timeout: 5000,
});
const data = response.data;
// Group by day
const dailyData = new Map<string, any[]>();
data.list.forEach((item: any) => {
const date = item.dt_txt.split(" ")[0];
if (!dailyData.has(date)) {
dailyData.set(date, []);
}
dailyData.get(date)!.push(item);
});
const forecast = Array.from(dailyData.entries()).map(([date, items]) => {
const temps = items.map((i) => i.main.temp);
const conditions = items.map((i) => i.weather[0].main);
return {
date,
temperature: {
min: Math.min(...temps),
max: Math.max(...temps),
avg: temps.reduce((a, b) => a + b, 0) / temps.length,
},
condition: conditions[0], // Use first condition
humidity: items[0].main.humidity,
windSpeed: items[0].wind.speed,
};
});
return {
city: data.city.name,
forecast,
};
} catch (error) {
throw new Error("Failed to fetch forecast data");
}
}
}
export const WeatherFrameInstance = new WeatherFrame();
Payment Gateway Proxy
// payment.frame.ts
import { BadRequestException, BaseFrameClass, NotFoundException, Sonamu, api } from "sonamu";
import axios from "axios";
class PaymentFrame extends BaseFrameClass {
frameName = "Payment";
private stripeApiKey = process.env.STRIPE_SECRET_KEY || "";
private stripeBaseUrl = "https://api.stripe.com/v1";
@api({ httpMethod: "POST", guards: ["user"] })
async createPaymentIntent(params: { orderId: number }): Promise<{
clientSecret: string;
paymentIntentId: string;
}> {
const { user } = Sonamu.getContext();
// The server sets the amount and currency from the signed-in user's order, not from client input
const order = await this.getPuri("r")
.table("orders")
.where("id", params.orderId)
.where("user_id", user!.id)
.select({ amount: "amount", currency: "currency" })
.first();
if (!order) {
throw new NotFoundException("Order not found");
}
try {
const response = await axios.post(
`${this.stripeBaseUrl}/payment_intents`,
new URLSearchParams({
amount: String(order.amount), // in cents
currency: order.currency,
}),
{
headers: {
Authorization: `Bearer ${this.stripeApiKey}`,
"Content-Type": "application/x-www-form-urlencoded",
},
},
);
return {
clientSecret: response.data.client_secret,
paymentIntentId: response.data.id,
};
} catch (error) {
throw new Error("Failed to create payment intent");
}
}
@api({ httpMethod: "POST", guards: ["user"] })
async verifyPayment(params: { paymentIntentId: string }): Promise<{
status: string;
amount: number;
currency: string;
paid: boolean;
}> {
// A format check does not prove ownership; in production, confirm the intent is linked to the signed-in user's order stored on the server
// The ID goes into a path called with the server secret key, so allow only the Stripe ID format (blocks path manipulation)
if (!/^pi_[A-Za-z0-9]+$/.test(params.paymentIntentId)) {
throw new BadRequestException("Invalid payment ID");
}
try {
const response = await axios.get(
`${this.stripeBaseUrl}/payment_intents/${encodeURIComponent(params.paymentIntentId)}`,
{
headers: {
Authorization: `Bearer ${this.stripeApiKey}`,
},
},
);
return {
status: response.data.status,
amount: response.data.amount,
currency: response.data.currency,
paid: response.data.status === "succeeded",
};
} catch (error) {
throw new Error("Failed to verify payment");
}
}
}
export const PaymentFrameInstance = new PaymentFrame();
4. Statistics & Dashboard
Admin Dashboard
// admin-stats.frame.ts
import { BaseFrameClass, api } from "sonamu";
interface DashboardStats {
users: {
total: number;
active: number;
newToday: number;
newThisWeek: number;
newThisMonth: number;
byRole: {
admin: number;
manager: number;
normal: number;
};
};
content: {
totalPosts: number;
totalComments: number;
postsToday: number;
commentsToday: number;
};
engagement: {
averagePostsPerUser: number;
averageCommentsPerPost: number;
mostActiveUsers: Array<{
userId: number;
username: string;
postCount: number;
}>;
};
system: {
databaseSize: number;
cacheHitRate: number;
averageResponseTime: number;
};
}
class AdminStatsFrame extends BaseFrameClass {
frameName = "AdminStats";
@api({ httpMethod: "GET", guards: ["admin"] })
async dashboard(): Promise<DashboardStats> {
const rdb = this.getPuri("r");
// Date calculations
const today = new Date();
today.setHours(0, 0, 0, 0);
const weekAgo = new Date(today);
weekAgo.setDate(weekAgo.getDate() - 7);
const monthAgo = new Date(today);
monthAgo.setMonth(monthAgo.getMonth() - 1);
// User statistics
const { totalUsers } = await rdb
.table("users")
.select({ totalUsers: Puri.count() })
.first();
const { activeUsers } = await rdb
.table("users")
.where("is_active", true)
.select({ activeUsers: Puri.count() })
.first();
const { newToday } = await rdb
.table("users")
.where("created_at", ">=", today)
.select({ newToday: Puri.count() })
.first();
const { newThisWeek } = await rdb
.table("users")
.where("created_at", ">=", weekAgo)
.select({ newThisWeek: Puri.count() })
.first();
const { newThisMonth } = await rdb
.table("users")
.where("created_at", ">=", monthAgo)
.select({ newThisMonth: Puri.count() })
.first();
// Statistics by role
const roleStats = await rdb
.table("users")
.select({ role: "role", count: Puri.count() })
.groupBy("role");
const byRole = {
admin: roleStats.find((s) => s.role === "admin")?.count || 0,
manager: roleStats.find((s) => s.role === "manager")?.count || 0,
normal: roleStats.find((s) => s.role === "normal")?.count || 0,
};
// Content statistics
const { totalPosts } = await rdb
.table("posts")
.select({ totalPosts: Puri.count() })
.first();
const { totalComments } = await rdb
.table("comments")
.select({ totalComments: Puri.count() })
.first();
const { postsToday } = await rdb
.table("posts")
.where("created_at", ">=", today)
.select({ postsToday: Puri.count() })
.first();
const { commentsToday } = await rdb
.table("comments")
.where("created_at", ">=", today)
.select({ commentsToday: Puri.count() })
.first();
// Engagement statistics
const averagePostsPerUser = totalUsers > 0 ? totalPosts / totalUsers : 0;
const averageCommentsPerPost = totalPosts > 0 ? totalComments / totalPosts : 0;
// Most active users
const mostActiveUsers = await rdb
.table("posts")
.join("users", "posts.user_id", "users.id")
.select({
userId: "posts.user_id",
username: "users.username",
postCount: Puri.count(),
})
.groupBy("posts.user_id", "users.username")
.orderBy("postCount", "desc")
.limit(5);
return {
users: {
total: totalUsers,
active: activeUsers,
newToday,
newThisWeek,
newThisMonth,
byRole,
},
content: {
totalPosts,
totalComments,
postsToday,
commentsToday,
},
engagement: {
averagePostsPerUser,
averageCommentsPerPost,
mostActiveUsers,
},
system: {
databaseSize: 0, // TODO: implement
cacheHitRate: 0, // TODO: implement
averageResponseTime: 0, // TODO: implement
},
};
}
}
export const AdminStatsFrameInstance = new AdminStatsFrame();
5. Validation & Validity Check
// validation.frame.ts
import { BaseFrameClass, api } from "sonamu";
import axios from "axios";
import dns from "dns";
import http from "http";
import https from "https";
import net from "net";
// IPv4 ranges that are not publicly routable (private, loopback, link-local/cloud metadata, CGNAT, multicast, ...)
const NON_PUBLIC_IPV4 = new net.BlockList();
for (const [address, prefix] of [
["0.0.0.0", 8],
["10.0.0.0", 8],
["100.64.0.0", 10],
["127.0.0.0", 8],
["169.254.0.0", 16],
["172.16.0.0", 12],
["192.0.0.0", 24],
["192.0.2.0", 24],
["192.168.0.0", 16],
["198.18.0.0", 15],
["198.51.100.0", 24],
["203.0.113.0", 24],
["224.0.0.0", 3],
] as const) {
NON_PUBLIC_IPV4.addSubnet(address, prefix, "ipv4");
}
// For IPv6, allow only global unicast (2000::/3) minus its documentation and 6to4 ranges
// (::1, fc00::/7, fe80::/10, IPv4-mapped ::ffff:0:0/96, and so on are all rejected)
const GLOBAL_IPV6 = new net.BlockList();
GLOBAL_IPV6.addSubnet("2000::", 3, "ipv6");
const NON_PUBLIC_IPV6 = new net.BlockList();
NON_PUBLIC_IPV6.addSubnet("2001:db8::", 32, "ipv6");
NON_PUBLIC_IPV6.addSubnet("2002::", 16, "ipv6");
function isPublicAddress(address: string): boolean {
if (net.isIPv4(address)) {
return !NON_PUBLIC_IPV4.check(address, "ipv4");
}
if (net.isIPv6(address)) {
return GLOBAL_IPV6.check(address, "ipv6") && !NON_PUBLIC_IPV6.check(address, "ipv6");
}
return false;
}
// Check the DNS result right before the socket opens. The connection uses the checked address,
// so DNS rebinding (changing the answer after the check) does not work either.
const publicOnlyLookup: net.LookupFunction = (hostname, options, callback) => {
dns.lookup(hostname, { ...options, all: true }, (error, addresses) => {
if (error) {
callback(error, "");
return;
}
if (addresses.length === 0 || !addresses.every((a) => isPublicAddress(a.address))) {
callback(new Error(`Host resolves to an internal address: ${hostname}`), "");
return;
}
if (options.all) {
callback(null, addresses);
} else {
callback(null, addresses[0].address, addresses[0].family);
}
});
};
// axios instance used only for user-supplied URLs
const publicOnlyHttp = axios.create({
httpAgent: new http.Agent({ lookup: publicOnlyLookup }),
httpsAgent: new https.Agent({ lookup: publicOnlyLookup }),
proxy: false, // A proxy would make the lookup check apply only to the proxy address
maxRedirects: 0, // Redirect targets (including IP literals) cannot be re-checked, so do not follow them
maxContentLength: 1024 * 1024, // Cap the response body at 1 MiB
timeout: 5000,
});
class ValidationFrame extends BaseFrameClass {
frameName = "Validation";
// Email validation
@api({ httpMethod: "POST", guards: ["user"] })
async validateEmail(params: { email: string; checkDns?: boolean }): Promise<{
valid: boolean;
format: boolean;
domain: boolean;
message?: string;
}> {
// Format validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const formatValid = emailRegex.test(params.email);
if (!formatValid) {
return {
valid: false,
format: false,
domain: false,
message: "Invalid email format",
};
}
// Domain validation
let domainValid = true;
const domain = params.email.split("@")[1];
if (params.checkDns) {
try {
await dns.promises.resolveMx(domain);
} catch (error) {
domainValid = false;
}
}
return {
valid: formatValid && domainValid,
format: formatValid,
domain: domainValid,
message: !domainValid ? "Domain does not exist or has no MX records" : undefined,
};
}
// URL validation
@api({ httpMethod: "POST", guards: ["user"] })
async validateUrl(params: { url: string; checkReachable?: boolean }): Promise<{
valid: boolean;
format: boolean;
reachable?: boolean;
statusCode?: number;
message?: string;
}> {
// Format validation
let urlObj: URL;
try {
urlObj = new URL(params.url);
} catch (error) {
return {
valid: false,
format: false,
message: "Invalid URL format",
};
}
// Only allow HTTP/HTTPS
if (!["http:", "https:"].includes(urlObj.protocol)) {
return {
valid: false,
format: false,
message: "Only HTTP/HTTPS protocols are supported",
};
}
// Hosts written as IP addresses skip the DNS lookup, so check them here
const host = urlObj.hostname.replace(/^\[(.*)\]$/, "$1");
if (net.isIP(host) !== 0 && !isPublicAddress(host)) {
return {
valid: false,
format: true,
message: "Internal addresses are not allowed",
};
}
// Check reachability
let reachable: boolean | undefined;
let statusCode: number | undefined;
if (params.checkReachable) {
try {
const response = await publicOnlyHttp.head(urlObj.href, {
validateStatus: () => true, // Allow all status codes
});
statusCode = response.status;
reachable = statusCode >= 200 && statusCode < 400;
} catch (error) {
reachable = false;
}
}
return {
valid: true && reachable !== false,
format: true,
reachable,
statusCode,
};
}
// Phone number validation (Korea)
@api({ httpMethod: "POST" })
async validatePhoneKR(params: { phone: string }): Promise<{
valid: boolean;
formatted: string;
type: "mobile" | "landline" | "unknown";
message?: string;
}> {
// Extract digits only
const digits = params.phone.replace(/\D/g, "");
// Length check (10-11 digits)
if (digits.length < 10 || digits.length > 11) {
return {
valid: false,
formatted: params.phone,
type: "unknown",
message: "Phone number must be 10-11 digits",
};
}
// Determine type
let type: "mobile" | "landline" | "unknown" = "unknown";
let formatted: string;
if (digits.startsWith("010") && digits.length === 11) {
// Mobile
type = "mobile";
formatted = `${digits.slice(0, 3)}-${digits.slice(3, 7)}-${digits.slice(7)}`;
} else if (digits.length === 10) {
// Area code
type = "landline";
formatted = `${digits.slice(0, 2)}-${digits.slice(2, 6)}-${digits.slice(6)}`;
} else {
formatted = params.phone;
}
return {
valid: type !== "unknown",
formatted,
type,
};
}
}
export const ValidationFrameInstance = new ValidationFrame();
Usage Patterns Summary
Next Steps
Creating Frames
BaseFrameClass usage
What are Frames?
Understanding Frame concept
@api Decorator
API basic usage
Model
Entity-based API