vitalets/websocket-as-promised

How to use CBOR to pack/unpack messages?

fferri opened this issue · 1 comments

I would like to use CBOR to pack/unpack messages in a plain HTML/JS application.

I use spaceify/cbor-js (a fork of paroga/cbor-js)

<script src="https://cdn.jsdelivr.net/gh/spaceify/cbor-js@master/cbor.js"></script>

then in my JS code:

this.websocket = new WebSocketAsPromised(
    `ws://${this.host}:${this.port}`,
    {
        packMessage: data => CBOR.encode(data),
        unpackMessage: data => CBOR.decode(data),
        // attach requestId to message as `id` field
        attachRequestId: (data, requestId) => Object.assign({id: requestId}, data),
        // read requestId from message `id` field
        extractRequestId: data => data && data.id,
    }
);

but I have an error (TypeError: First argument to DataView constructor must be an ArrayBuffer) because unpackMessage calls CBOR.decode(data) with data being an object of type Blob.

I tried to change unpackMessage to use Blob.arrayBuffer():

unpackMessage: data => CBOR.encode(data.arrayBuffer())

but data.arrayBuffer() returns a Promise, however this:

unpackMessage: data => CBOR.encode(await data.arrayBuffer())

is a syntax error (Uncaught SyntaxError: missing ) after argument list).

Any idea how to fix this?

Solved:

unpackMessage = async data => CBOR.decode(await data.arrayBuffer());