mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
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:
+3
-3
@@ -6,8 +6,8 @@ NEXT_PUBLIC_APP_URL="http://localhost:1209"
|
||||
|
||||
# BASE_URL_API = https://his.nutech-integrasi.com/presence-api/api/v1
|
||||
# BASE_URL_IMG = https://his.nutech-integrasi.com/presence-api/
|
||||
BASE_URL_API = https://36.66.3.44/presence-api/api/v1
|
||||
BASE_URL_IMG = https://36.66.3.44/presence-api/
|
||||
BASE_URL_API = https://api-hats.hisnutech.my.id/api/v1
|
||||
BASE_URL_IMG = https://api-hats.hisnutech.my.id/
|
||||
|
||||
NEXTAUTH_URL = http://localhost:1209
|
||||
# NEXTAUTH_URL = http://localhost:7090/super-apps/api/auth
|
||||
@@ -19,4 +19,4 @@ FIREBASE_APP_ID = "1:422528660020:web:db16e1cba4d357e32f1061"
|
||||
DEVICE_CODE = "40001"
|
||||
NEXT_PUBLIC_HATS_SUPPORT_NAME = "Amalia"
|
||||
NEXT_PUBLIC_HATS_SUPPORT_PHONE = "6285214074002"
|
||||
NEXT_PUBLIC_APP_VERSION = "v1.1.0"
|
||||
NEXT_PUBLIC_APP_VERSION = "v1.1.1"
|
||||
@@ -94,6 +94,11 @@ const ChangeAvatar: FC<Props> = ({ nik, existAvatar }) => {
|
||||
setIsFullLoading(false)
|
||||
})
|
||||
} else {
|
||||
if (file.size > 5000000) {
|
||||
toast.error('Failed upload photo', { description: 'File size too large, maximum 5MB' })
|
||||
return
|
||||
}
|
||||
|
||||
let imageDataUrl = await readFile(file)
|
||||
|
||||
// apply rotation if needed
|
||||
|
||||
@@ -15,6 +15,18 @@ interface ReleaseNote {
|
||||
}
|
||||
|
||||
const releaseNotes: ReleaseNote[] = [
|
||||
{
|
||||
version: "v1.1.1",
|
||||
date: "09 February 2026",
|
||||
type: "minor",
|
||||
changes: [
|
||||
{ category: "feature", description: "Added application logging for backend API requests" },
|
||||
{ category: "feature", description: "Implemented server actions for backend API requests" },
|
||||
{ category: "bugfix", description: "Fixed donut chart click behavior on the employee homepage in mobile view" },
|
||||
{ category: "bugfix", description: "Fixed session persistence issues for HATS Team and Release Notes pages" },
|
||||
{ category: "improvement", description: "Limit file upload size for avatar" },
|
||||
]
|
||||
},
|
||||
{
|
||||
version: "v1.1.0",
|
||||
date: "28 January 2026",
|
||||
@@ -27,8 +39,8 @@ const releaseNotes: ReleaseNote[] = [
|
||||
{ category: "improvement", description: "Replaced native img tags with LazyLoad Image component and added lazy loading for avatars" },
|
||||
{ category: "bugfix", description: "Fixed spamming \"Failed to fetch geolocation\" alerts when presence using mobile devices" },
|
||||
{ category: "feature", description: "Added progress bar indicator when route change in employee routes" },
|
||||
{ category: 'feature', description: <div>Added <Link href="/hats-team" className="underline text-blue-500">hats team</Link> page</div> },
|
||||
{ category: 'feature', description: <div>Added <Link href="/release-notes" className="underline text-blue-500">release notes</Link> page</div> },
|
||||
{ category: 'feature', description: <div>Added <Link href="/hats-team" className="underline text-blue-500">HATs Team</Link> page</div> },
|
||||
{ category: 'feature', description: <div>Added <Link href="/release-notes" className="underline text-blue-500">Release Notes</Link> page</div> },
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+16
-17
@@ -1,33 +1,32 @@
|
||||
"use server"
|
||||
|
||||
import axios from "@/lib/axios";
|
||||
import { serverApiCall } from "@/lib/server-api";
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
export const editProfileData = async (payload: any) => {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${session?.user?.access_token}`;
|
||||
export async function updateProfileAction(payload: any) {
|
||||
const result = await serverApiCall('PUT', '/user/profile/update', payload);
|
||||
|
||||
await axios.put('/user/profile/update', payload)
|
||||
revalidatePath('profile-data')
|
||||
} catch (error: any) {
|
||||
console.log("ERROR EDIT PROFILE:", error.response?.data?.code, error.response?.data?.message)
|
||||
throw new Error(error as any)
|
||||
if (result.success) {
|
||||
revalidatePath('/profile');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export const changeAvatar = async (payload: any) => {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${session?.user?.access_token}`;
|
||||
export async function changeAvatarAction(nik: string, base64Image: string) {
|
||||
const cleanBase64 = base64Image ? base64Image.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '') : '';
|
||||
|
||||
await axios.post('/user/profile/change-avatar', payload)
|
||||
revalidatePath('/profile')
|
||||
} catch (error) {
|
||||
throw new Error(error as any)
|
||||
const payload = { nik, avatar: cleanBase64 };
|
||||
const result = await serverApiCall('POST', '/user/change-avatar', payload);
|
||||
|
||||
if (result.success) {
|
||||
revalidatePath('/profile'); // Refresh data
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export const changePassword = async (payload: any) => {
|
||||
|
||||
@@ -44,7 +44,7 @@ async function getData() {
|
||||
export default async function UserPage() {
|
||||
const data = await getData()
|
||||
|
||||
// console.log("DATA USER LENGTH :", data?.user?.length)
|
||||
console.log("DATA USER LENGTH :", data?.user)
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ import ProgressBarProviders from '@/providers/ProgressBarProvider';
|
||||
const jakarta = Plus_Jakarta_Sans({ subsets: ['latin'] })
|
||||
|
||||
export const metadata: Metadata = {
|
||||
metadataBase: new URL(process.env.NEXT_PUBLIC_APP_URL || 'https://his.nutech-integrasi.com'),
|
||||
metadataBase: new URL(process.env.NEXT_PUBLIC_APP_URL || 'https://hats.hisnutech.my.id'),
|
||||
title: 'HIS Attendance Task System (H.A.T.s)',
|
||||
description: 'H.A.T.s HIS Attendance Task System (smart absence, task management, work permit and leave mangement, etc).',
|
||||
applicationName: 'HIS Attendance Task System (H.A.T.s)',
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 553 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 553 KiB |
@@ -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;
|
||||
};
|
||||
};
|
||||
@@ -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",
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user