// PhotoRoom Service Implementation - API Call Structure
// 1. Service Configuration
export class PhotoroomService {
private config: PhotoroomConfig;
constructor(config: PhotoroomConfig) {
this.config = {
baseUrl: ‘image-api.photoroom.com’,
…config,
};
}
// 2. Main API Call Method
async generateImage(params: GenerateImageParams): Promise {
try {
const editParams = this.buildEditParams(params);
const imageBuffer = await this.makeRequest(editParams, params.imageUrl);
return {
success: true,
imageBuffer,
};
} catch (error) {
console.error('Photoroom API error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
}
// 3. Parameters Builder - THIS IS THE KEY PART
private buildEditParams(params: GenerateImageParams): string {
const commonParams = {
outputSize: ‘1080x1350’,
padding: ‘15%’,
‘shadow.mode’: ‘ai.soft’,
‘lighting.mode’: ‘ai.auto’,
};
if (params.type === 'lifestyle') {
const lifestylePrompt = params.creativePromptLifestyle ||
'elegant lifestyle setting with natural lighting, professional advertising photography style, high-end commercial quality';
return new URLSearchParams({
...commonParams,
'background.prompt': lifestylePrompt,
'background.seed': (params.seed || 1372426027).toString(),
}).toString();
} else {
return new URLSearchParams({
...commonParams,
'background.color': 'F2F2F2FF',
}).toString();
}
}
// 4. Actual HTTP Request to PhotoRoom API
private async makeRequest(editParams: string, imageUrl: string): Promise {
return new Promise((resolve, reject) => {
const options = {
hostname: this.config.baseUrl,
port: 443,
path: /v2/edit?${editParams}&imageUrl=${encodeURIComponent(imageUrl)},
method: ‘GET’,
headers: {
‘x-api-key’: this.config.apiKey,
},
};
const req = https.request(options, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`Request failed with status code ${res.statusCode}`));
return;
}
const chunks: Buffer[] = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const buffer = Buffer.concat(chunks);
resolve(buffer);
});
});
req.on('error', (error) => {
reject(error);
});
req.end();
});
}
}
// 5. How we call it in practice
// Example from your router:
photoroomService.generateImage({
imageUrl: product.image_url,
type: ‘lifestyle’, // or ‘studio’
seed: Math.floor(Math.random() * 1000000000),
productDescription: product.description,
productTitle: product.title,
productCategory: product.category,
creativePromptLifestyle: creativePrompt,
})