PK
PK5mo ago

how to proxy a router

hey im building a chrome extension that has two adapters .. one is for communicating with the api server (lets call it an apiRouter) and another to communicate between the different parts(worlds) of the chrome extension (specifically the background script and a content script). since apiRouter is only available for the background script , but the extensionRouter is available for all the other parts I'd like the extensionRouter to proxy the apiRouter , in such a way that a query() from the api AppRouter would be available natively on the extensionRouter my naive implementation was create a new proxy method for the apiClient
export function createProxy<T>(api: any): T {
return new Proxy(api, {
get(target, propKey, receiver) {
if (propKey === 'useQuery') {
return function (...args) {
console.log(`Redirecting method useQuery to query with args:`, args);
return target.query(...args);
};
} else if (typeof target[propKey] === 'function') {
return function (...args) {
console.log(`Calling ${propKey.toString()} with args:`, args);
return Reflect.get(target, propKey, receiver).apply(target, args);
};
} else if (typeof target[propKey] === 'object' && target[propKey] !== null) {
console.log(`Creating proxy for ${propKey.toString()}`);
return createProxy(target[propKey]);
} else {
console.log(`Returning property ${propKey.toString()}`);
return target[propKey];
}
}
});
}
export function createProxy<T>(api: any): T {
return new Proxy(api, {
get(target, propKey, receiver) {
if (propKey === 'useQuery') {
return function (...args) {
console.log(`Redirecting method useQuery to query with args:`, args);
return target.query(...args);
};
} else if (typeof target[propKey] === 'function') {
return function (...args) {
console.log(`Calling ${propKey.toString()} with args:`, args);
return Reflect.get(target, propKey, receiver).apply(target, args);
};
} else if (typeof target[propKey] === 'object' && target[propKey] !== null) {
console.log(`Creating proxy for ${propKey.toString()}`);
return createProxy(target[propKey]);
} else {
console.log(`Returning property ${propKey.toString()}`);
return target[propKey];
}
}
});
}
const proxiedTrpcClient = createProxy<ApiRouter>(apiTrpcStandaloneClient);
const proxiedTrpcClient = createProxy<ApiRouter>(apiTrpcStandaloneClient);
then adding proxiedTrpcClient on the AppRouter but it looks like the proxy is being swaped by anoter implementation by tRPC. what am I missing , is there a better way to tackle this?
0 Replies
No replies yetBe the first to reply to this messageJoin