This guide explains how to dynamically fetch trader images from Payload CMS for the Kenya Forex Firm website.
The integration allows the website to display trader images stored in Payload CMS. The system handles both direct image URLs and Payload CMS image objects/IDs.
The src/lib/payload/image.ts file contains utility functions for handling Payload CMS images:
// Gets the URL for a trader's image from Payload CMS
export function getTraderImageUrl(image: PayloadImage | string): string {
if (typeof image === 'string') {
// If it's an ID (no slashes or dots), construct the media URL
if (!image.includes('/') && !image.includes('.')) {
return `${import.meta.env.PAYLOAD_API_URL || 'https://api.kenyaforexfirm.com'}/api/media/${image}`;
}
return getPayloadImageUrl(image);
}
return getPayloadImageUrl(image.url);
}
The src/lib/payload/mappers.ts file contains functions to normalize data from Payload CMS:
// Normalizes a trader object from Payload CMS
export function normalizeTrader(trader: PayloadTrader): PayloadTrader {
// Normalize journey challenges, trading style preferred pairs, etc.
}
The TraderProfile.astro component has been updated to handle both string URLs and image objects:
// Get the image URL from either a string or a Payload CMS image object
const imageUrl = getTraderImageUrl(image);
{
"name": "Ken Githaiga",
"specialization": "Technical Analysis",
"experience": "10+ Years",
"startYear": 2014,
"image": "6841dd8c2e5e72cf108d0a9a",
"journey": {
"challenges": [
{
"challenge": "Initially struggled with balancing trading and family life",
"id": "6841dbd9f606798b6b6cdf33"
}
]
},
"tradingAdvice": {
"tradingStyle": {
"preferredPairs": [
{
"pair": "EUR/USD",
"id": "6841dc49b388815272ea9046"
}
]
}
}
}
Fetch traders from Payload CMS:
const tradersResponse = await fetchFromPayload('/fxTraders?limit=100&depth=1');
const traders = tradersResponse.docs.map(trader => normalizeTrader(trader as PayloadTrader));
Display trader images:
<img src={getTraderImageUrl(trader.image)} alt={`${trader.name} - Forex Trader`} />
Make sure to set these environment variables:
PAYLOAD_API_URL=https://api.kenyaforexfirm.com
PAYLOAD_API_KEY=your_api_key_here