pneutam
pneutam
CDCloudflare Developers
Created by pneutam on 11/18/2024 in #workers-help
How to return a plain object and not a stub from a Worker with RPC binding?
I'm working with a Cloudflare Worker that is called from a Cloudflare Pages project using Services Binding + RPC. I'd like to be able to configure or convert a plain object returned from a target instance to be serialized to an object and not be returned as a stub. As an example, consider the following projects: TYPE LIB: Standalone library with types I want to reference in other projects.
export type MyObject = {
name: string;
description: string;
}
export type MyObject = {
name: string;
description: string;
}
SHARED WORKER: Worker providing services via service bindings and RPC.
export default class extends WorkerEntrypoint {
async myStore(): Promise<myStore> {
return new MyStoreTarget();
}
);

class MyStoreTarget extends RpcTarget {
async findMyObject(name: string) : Promise<MyObject | null> { // references TYPE LIB
return { name: 'Test name', description: 'Test description' };
}
export default class extends WorkerEntrypoint {
async myStore(): Promise<myStore> {
return new MyStoreTarget();
}
);

class MyStoreTarget extends RpcTarget {
async findMyObject(name: string) : Promise<MyObject | null> { // references TYPE LIB
return { name: 'Test name', description: 'Test description' };
}
END APP: The calling code to the shared worker.
const worker = event.platform.env.STORE_WORKER; // references SHARED WORKER

const target = await worker.myStore();

const myobj : MyObject = await target.findMyObject('Test name'); // references TYPE LIB
const worker = event.platform.env.STORE_WORKER; // references SHARED WORKER

const target = await worker.myStore();

const myobj : MyObject = await target.findMyObject('Test name'); // references TYPE LIB
When I try the above, it appears to return myobj as a stub, and TypeScript in VSCode complains as the types don't match. Further, it would seem any reference to myobj properties would be executed as RPC calls which is inefficient. Is there a way to configure or convert myobj efficiently so that it is a plain object matching the MyObject type? Thanks in advance!
1 replies