port-nimara-client-portal/server/api/get-berths.ts

64 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-06-03 17:57:08 +02:00
export default defineEventHandler(async (event) => {
const xTagHeader = getRequestHeader(event, "x-tag");
2025-06-09 23:33:20 +02:00
console.log('[get-berths] Request received with x-tag:', xTagHeader);
2025-06-03 17:57:08 +02:00
2025-06-09 23:33:20 +02:00
if (!xTagHeader || (xTagHeader !== "094ut234" && xTagHeader !== "pjnvü1230")) {
console.error('[get-berths] Authentication failed - invalid x-tag:', xTagHeader);
2025-06-03 17:57:08 +02:00
throw createError({ statusCode: 401, statusMessage: "unauthenticated" });
}
2025-06-09 23:33:20 +02:00
try {
const config = getNocoDbConfiguration();
const berthsTableId = "mczgos9hr3oa9qc";
console.log('[get-berths] Fetching berths...');
const berths = await $fetch<{ list: any[] }>(`${config.url}/api/v2/tables/${berthsTableId}/records`, {
headers: {
"xc-token": config.token,
},
params: {
limit: 1000,
},
});
console.log('[get-berths] Successfully fetched berths, count:', berths.list?.length || 0);
// Sort berths by letter zone and then by number
if (berths.list && Array.isArray(berths.list)) {
berths.list.sort((a, b) => {
const berthA = a['Berth Number'] || '';
const berthB = b['Berth Number'] || '';
// Extract letter and number parts
const matchA = berthA.match(/^([A-Za-z]+)(\d+)$/);
const matchB = berthB.match(/^([A-Za-z]+)(\d+)$/);
if (matchA && matchB) {
const [, letterA, numberA] = matchA;
const [, letterB, numberB] = matchB;
// First sort by letter zone
const letterCompare = letterA.localeCompare(letterB);
if (letterCompare !== 0) {
return letterCompare;
}
// Then sort by number within the same letter zone
return parseInt(numberA) - parseInt(numberB);
}
// Fallback to string comparison if pattern doesn't match
return berthA.localeCompare(berthB);
});
console.log('[get-berths] Berths sorted by zone and number');
}
2025-06-09 23:33:20 +02:00
return berths;
} catch (error) {
console.error('[get-berths] Error occurred:', error);
console.error('[get-berths] Error details:', error instanceof Error ? error.message : 'Unknown error');
throw error;
}
2025-06-03 17:57:08 +02:00
});