Add server API helper, logging & misc updates

Introduce a reusable serverApiCall helper and file-based logger (lib/server-api.ts, lib/logger.ts) to centralize backend requests, attach session auth, and capture request/response/error logs. Update server actions to use the new helper (updateProfileAction, changeAvatarAction) and ensure profile revalidation. Add client-side avatar upload size limit (5MB) and normalize avatar base64 payload. Add new OpenGraph/Twitter images, bump app version to v1.1.1, and add a v1.1.1 entry in release notes. Update default API/IMG env URLs and metadataBase fallback, fix minor release-notes link capitalization, and adjust a debug console.log in admin user page.
This commit is contained in:
Ichsan Kurniawan
2026-02-09 14:48:03 +07:00
parent c24838550a
commit 5cbded392a
10 changed files with 155 additions and 24 deletions
+50
View File
@@ -0,0 +1,50 @@
// lib/logger.ts
import fs from 'fs';
import path from 'path';
export const writeLog = (type: 'REQUEST' | 'RESPONSE' | 'ERROR', title: string, data: any) => {
const logProcess = async () => {
try {
const now = new Date();
const dateStr = now.toISOString().split('T')[0];
const fileName = `${dateStr}.log`;
const logDir = path.join(process.cwd(), 'logs');
// Check folder exists (async version is complex, sync check is tiny and runs once)
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const timestamp = now.toISOString();
// Safe stringify to prevent circular reference crashes
const dataString = JSON.stringify(data, getCircularReplacer(), 2);
const logEntry = `[${timestamp}] [${type}] ${title}\n${dataString}\n${'-'.repeat(50)}\n`;
// Async append - we don't wait for this result
fs.appendFile(path.join(logDir, fileName), logEntry, (err) => {
if (err) console.error('Writing log failed:', err);
});
} catch (error) {
console.error('Logger internal error:', error);
}
};
// Trigger execution immediately but don't return a promise to the caller
logProcess();
};
// Helper to handle circular references in JSON (common in Axios error objects)
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key: any, value: any) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
}
return value;
};
};
+65
View File
@@ -0,0 +1,65 @@
import { getServerSession } from "next-auth";
import { authOptions } from "@/pages/api/auth/[...nextauth]"; // Adjust path as needed
import axios from "@/lib/axios"; // Your axios instance
import { writeLog } from "./logger";
// 1. Define a standard response format for all your actions
export type ActionResponse<T = any> =
| { success: true; data?: T }
| { success: false; code: string | number; message: string; };
// 2. The Reusable Function
export async function serverApiCall<T>(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
url: string,
payload?: any
): Promise<ActionResponse<T>> {
try {
writeLog('REQUEST', `${method} ${url}`, payload || 'No Payload');
const session = await getServerSession(authOptions);
const config = {
headers: {
Authorization: `Bearer ${session?.user?.access_token}`,
},
};
let response;
switch (method) {
case 'POST':
response = await axios.post(url, payload, config);
break;
case 'PUT':
response = await axios.put(url, payload, config);
break;
case 'DELETE':
response = await axios.delete(url, config);
break;
default:
response = await axios.get(url, config);
break;
}
writeLog('RESPONSE', `${method} ${url} - SUCCESS`, response.data);
return { success: true, data: response.data };
} catch (error: any) {
// 3. Detailed Error Handling (The part you wanted!)
const errorDetails = {
code: error.response?.data?.code || error.response?.status || '-',
message: error.response?.data?.message || error.response?.statusText || error.message || "An unexpected error occurred",
backendData: error.response?.data
};
writeLog('ERROR', `${method} ${url}`, errorDetails);
console.error(`[Server Action Error] ${method} ${url}:`, error.response?.data || error.message);
return {
success: false,
code: error.response?.data?.code || error.response?.status || '-',
message: error.response?.data?.message || error.response?.statusText || error.message || "An unexpected error occurred",
};
}
}