Skip to content

Commit f13f95d

Browse files
committed
Use prototype chain to memoize PathCallForwarder (and rename)
1 parent b8502ad commit f13f95d

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

packages/openapi-fetch/src/index.js

+30-5
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ export default function createClient(clientOptions) {
233233
};
234234
}
235235

236-
class UrlCallForwarder {
236+
class PathCallForwarder {
237237
constructor(client, url) {
238238
this.client = client;
239239
this.url = url;
@@ -265,17 +265,42 @@ class UrlCallForwarder {
265265
}
266266
}
267267

268-
const clientProxyHandler = {
268+
class PathClientProxyHandler {
269+
constructor() {
270+
this.client = null;
271+
}
272+
269273
// Assume the property is an URL.
270-
get: (coreClient, url) => new UrlCallForwarder(coreClient, url),
271-
};
274+
get(coreClient, url) {
275+
const forwarder = new PathCallForwarder(coreClient, url);
276+
this.client[url] = forwarder;
277+
return forwarder;
278+
}
279+
}
272280

273281
/**
274282
* Wrap openapi-fetch client to support a path based API.
275283
* @type {import("./index.js").wrapAsPathBasedClient}
276284
*/
277285
export function wrapAsPathBasedClient(coreClient) {
278-
return new Proxy(coreClient, clientProxyHandler);
286+
const handler = new PathClientProxyHandler();
287+
const proxy = new Proxy(coreClient, handler);
288+
289+
// Put the proxy on the prototype chain of the actual client.
290+
// This means if we do not have a memoized PathCallForwarder,
291+
// we fall back to the proxy to synthesize it.
292+
// However, the proxy itself is not on the hot-path (if we fetch the same
293+
// endpoint multiple times, only the first call will hit the proxy).
294+
function Client() {}
295+
Client.prototype = proxy;
296+
297+
const client = new Client();
298+
299+
// Feed the client back to the proxy handler so it can store the generated
300+
// PathCallForwarder.
301+
handler.client = client;
302+
303+
return client;
279304
}
280305

281306
/**

0 commit comments

Comments
 (0)