All files / routes/pro/company-profile helpers.ts

100% Statements 13/13
100% Branches 8/8
100% Functions 4/4
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83                      54x                     48x 11x             37x                     28x 28x 8x             20x                       24x     24x 11x               13x 13x              
// Company Profile Route Helpers
import type { Context } from "hono";
import type { ContentfulStatusCode } from "hono/utils/http-status";
import { error } from "../../../lib/response";
import { AppError } from "../../../lib/errors";
import { logger } from "../../../lib/logger";
 
/**
 * Check if the user has owner or manager role
 */
export function hasManagerAccess(proRole: string): boolean {
	return ["owner", "manager"].includes(proRole);
}
 
/**
 * Return forbidden error if user doesn't have manager access
 */
export function requireManagerRole(
	c: Context,
	proRole: string,
	action: string,
): Response | null {
	if (!hasManagerAccess(proRole)) {
		return error(
			c,
			"FORBIDDEN",
			`Only owners and managers can ${action}`,
			403,
		) as unknown as Response;
	}
	return null;
}
 
/**
 * Parse numeric ID from route param
 */
export function parseNumericId(
	c: Context,
	paramName: string,
	idType: string,
): number | Response {
	const id = parseInt(c.req.param(paramName) ?? "", 10);
	if (Number.isNaN(id)) {
		return error(
			c,
			"INVALID_ID",
			`Invalid ${idType} ID`,
			400,
		) as unknown as Response;
	}
	return id;
}
 
/**
 * Handle common service errors for CRUD operations
 */
export function handleServiceError(
	c: Context,
	err: unknown,
	operation: "create" | "update" | "delete" | "fetch",
	entityName: string,
): Response {
	logger.error(`[COMPANY_PROFILE] Error ${operation}ing ${entityName}:`, err);
 
	// Typed errors from services — use their status code and error code directly
	if (err instanceof AppError) {
		return error(
			c,
			err.code,
			err.message,
			err.statusCode as ContentfulStatusCode,
		) as unknown as Response;
	}
 
	const errorCode = `${operation.toUpperCase()}_ERROR`;
	return error(
		c,
		errorCode,
		`Failed to ${operation} ${entityName}`,
		500,
	) as unknown as Response;
}