86 lines
1.7 KiB
TypeScript
86 lines
1.7 KiB
TypeScript
import axios from 'axios';
|
|
|
|
const STRAPI_URL = process.env.STRAPI_URL || 'http://localhost:1337';
|
|
const STRAPI_TOKEN = process.env.STRAPI_API_TOKEN;
|
|
|
|
const strapi = axios.create({
|
|
baseURL: `${STRAPI_URL}/api`,
|
|
headers: {
|
|
Authorization: `Bearer ${STRAPI_TOKEN}`,
|
|
},
|
|
});
|
|
|
|
export interface StrapiResponse<T> {
|
|
data: {
|
|
id: number;
|
|
attributes: T;
|
|
}[];
|
|
meta: {
|
|
pagination: {
|
|
page: number;
|
|
pageSize: number;
|
|
pageCount: number;
|
|
total: number;
|
|
};
|
|
};
|
|
}
|
|
|
|
export interface Product {
|
|
title: string;
|
|
sku: string;
|
|
description: string;
|
|
application: string;
|
|
content: string;
|
|
technicalData: any;
|
|
locale: string;
|
|
images?: {
|
|
data: {
|
|
attributes: {
|
|
url: string;
|
|
alternativeText: string;
|
|
};
|
|
}[];
|
|
};
|
|
}
|
|
|
|
export async function getProducts(locale: string = 'de') {
|
|
try {
|
|
const response = await strapi.get<StrapiResponse<Product>>('/products', {
|
|
params: {
|
|
locale,
|
|
populate: '*',
|
|
},
|
|
});
|
|
return response.data.data.map(item => ({
|
|
id: item.id,
|
|
...item.attributes,
|
|
}));
|
|
} catch (error) {
|
|
console.error('Error fetching products from Strapi:', error);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export async function getProductBySku(sku: string, locale: string = 'de') {
|
|
try {
|
|
const response = await strapi.get<StrapiResponse<Product>>('/products', {
|
|
params: {
|
|
filters: { sku: { $eq: sku } },
|
|
locale,
|
|
populate: '*',
|
|
},
|
|
});
|
|
if (response.data.data.length === 0) return null;
|
|
const item = response.data.data[0];
|
|
return {
|
|
id: item.id,
|
|
...item.attributes,
|
|
};
|
|
} catch (error) {
|
|
console.error(`Error fetching product ${sku} from Strapi:`, error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export default strapi;
|