Complete the code to define an ambassador service that proxies requests to the main service.
class AmbassadorService { constructor(targetService) { this.targetService = targetService; } handleRequest(request) { return this.targetService.[1](request); } }
The ambassador service forwards the request by calling handleRequest on the target service.
Complete the code to add logging in the ambassador before forwarding the request.
class AmbassadorService { handleRequest(request) { console.log('Forwarding request:', [1]); return this.targetService.handleRequest(request); } }
this instead of the request.request.data.Logging the entire request object helps track what is being forwarded.
Fix the error in the ambassador's retry logic to handle failed requests.
async handleRequest(request) {
let attempts = 0;
while (attempts < [1]) {
try {
return await this.targetService.handleRequest(request);
} catch (error) {
attempts++;
}
}
throw new Error('Max retries reached');
}The retry limit should be a number literal like 3 to control the loop correctly.
Fill both blanks to implement a timeout mechanism in the ambassador pattern.
async handleRequest(request) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.[1](), [2]);
try {
return await this.targetService.handleRequest({ ...request, signal: controller.signal });
} finally {
clearTimeout(timeoutId);
}
}cancel().The AbortController uses the abort() method to cancel requests after a timeout of 5000 milliseconds.
Fill all three blanks to create a caching layer in the ambassador to reduce load on the main service.
class AmbassadorService { constructor(targetService) { this.targetService = targetService; this.cache = new Map(); } async handleRequest(request) { const key = JSON.stringify([1]); if (this.cache.has(key)) { return this.cache.get(key); } const response = await this.targetService.handleRequest([2]); this.cache.set(key, [3]); return response; } }
The cache key is created from the request. The request is forwarded as is, and the response is cached for future use.