Files
klz-cables.com/lib/directus.ts
2026-02-01 02:02:03 +01:00

94 lines
3.1 KiB
TypeScript

import { createDirectus, rest, authentication, readItems, readItem } from '@directus/sdk';
const DIRECTUS_URL = process.env.DIRECTUS_URL || 'http://localhost:8055';
const DIRECTUS_EMAIL = process.env.DIRECTUS_ADMIN_EMAIL;
const DIRECTUS_PASSWORD = process.env.DIRECTUS_ADMIN_PASSWORD;
const DIRECTUS_TOKEN = process.env.DIRECTUS_API_TOKEN;
const client = createDirectus(DIRECTUS_URL)
.with(rest())
.with(authentication());
export async function ensureAuthenticated() {
if (DIRECTUS_TOKEN) {
client.setToken(DIRECTUS_TOKEN);
return;
}
if (DIRECTUS_EMAIL && DIRECTUS_PASSWORD) {
try {
await client.login(DIRECTUS_EMAIL, DIRECTUS_PASSWORD);
} catch (e) {
console.error("Failed to authenticate with Directus:", e);
}
}
}
/**
* Maps the new translation-based schema back to the application's Product interface
*/
function mapDirectusProduct(item: any, locale: string): any {
const langCode = locale === 'en' ? 'en-US' : 'de-DE';
const translation = item.translations?.find((t: any) => t.languages_code === langCode) || item.translations?.[0] || {};
return {
id: item.id,
sku: item.sku,
title: translation.name || '',
description: translation.description || '',
content: translation.content || '',
technicalData: {
technicalItems: translation.technical_items || [],
voltageTables: translation.voltage_tables || []
},
locale: locale,
data_sheet_url: item.data_sheet ? `${DIRECTUS_URL}/assets/${item.data_sheet}` : null,
categories: (item.categories_link || []).map((c: any) => c.categories_id?.translations?.[0]?.name).filter(Boolean)
};
}
export async function getProducts(locale: string = 'de') {
await ensureAuthenticated();
try {
const items = await client.request(readItems('products', {
fields: [
'*',
'translations.*',
'categories_link.categories_id.translations.name'
]
}));
return items.map(item => mapDirectusProduct(item, locale));
} catch (error) {
console.error('Error fetching products:', error);
return [];
}
}
export async function getProductBySlug(slug: string, locale: string = 'de') {
await ensureAuthenticated();
const langCode = locale === 'en' ? 'en-US' : 'de-DE';
try {
const items = await client.request(readItems('products', {
filter: {
translations: {
slug: { _eq: slug },
languages_code: { _eq: langCode }
}
},
fields: [
'*',
'translations.*',
'categories_link.categories_id.translations.name'
],
limit: 1
}));
if (!items || items.length === 0) return null;
return mapDirectusProduct(items[0], locale);
} catch (error) {
console.error(`Error fetching product ${slug}:`, error);
return null;
}
}
export default client;