restatedev / sdk-typescript

Restate SDK for JavaScript/Typescript
MIT License
46 stars 8 forks source link

[client] Add 'raw' opt/sendOpt to skip JSON serde #404

Closed igalshilman closed 2 months ago

igalshilman commented 2 months ago

This PR adds a raw optional property to the client To allow skipping JSON serde. This will pass the raw input buffer to the underlying fetch

Given the following object def:

const counter = restate.object({
  name: "counter",
  handlers: {
    /**
     * Handlers (shared or exclusive) can be configured to bypass JSON serialization,
     * by specifying the input (accept) and output (contentType) content types.
     *
     * to call that handler with binary data, you can use the following curl command:
     * curl -X POST -H "Content-Type: application/octet-stream" --data-binary 'hello' ${RESTATE_INGRESS_URL}/counter/mykey/binary
     */
    binary: restate.handlers.object.exclusive(
      {
        accept: "application/octet-stream",
        contentType: "application/octet-stream",
      },
      async (ctx: restate.ObjectContext, data: Uint8Array) => {
        // console.log("Received binary data", data);
        return data;
      }
    ),
  },
});

Now it is possible to invoke this handler from the client like this:

const client = restate.connect({ url: "http://localhost:8080" });

const counter = client.objectClient(Counter, "counter1");

const buffer: Uint8Array = new TextEncoder().encode("hello!");

const outBuffer: Uint8Array = await counter.binary(
    buffer,
    restate.Opts.from({
      raw: true, // <-- tell the client to avoid JSON encoding/decoding
      headers: { "content-type": "application/octet-stream" },
    })
 );

 const str = new TextDecoder().decode(outBuffer);

console.log(`We got a buffer for ${name} : ${str}`);