The library for elysia which allows you to work with MessagePack. To pack/unpack it, we use really fast msgpackr
bun install elysia-msgpack
// @filename: server.ts
import Elysia from "elysia"
import { msgpack } from "elysia-msgpack"
const app = new Elysia()
.use(msgpack())
.post("/", ({ body, msgpack }) => {
// body is unpacked MessagePack if content-type header contains application/x-msgpack
// also you can work with Packr instance via msgpack decorator
// if accept header contains application/x-msgpack
// this response will become a MessagePack,
// and if not, it will remain JSON
return {
some: "values",
and: true,
keys: 228,
}
})
.listen(3000);
export AppType = typeof app;
It works fine with End-to-End Type Safety too!
// @filename: client.ts
import { treaty } from "@elysiajs/eden";
import { pack, unpack } from "msgpackr";
import type { AppType } from "./server";
const app = treaty<AppType>("localhost:4888", {
onRequest: (path, { body }) => {
return {
headers: {
"content-type": "application/x-msgpack",
accept: "application/x-msgpack",
},
body: pack(body),
};
},
onResponse: async (response) => {
if (
response.headers
.get("Content-Type")
?.startsWith("application/x-msgpack")
)
return unpack(Buffer.from(await response.arrayBuffer()));
},
});
const { data, error } = await app.index.post({
some: 228,
});
console.log(data);
All options of msgpackr constructor (but we set useRecords to false
by default)
Key | Type | Default | Description |
---|---|---|---|
contentTypes? | string[] | ["application/x-msgpack"] | An array of content-types that need to be serialized/deserialized |
force? | boolean | false | Don't look at the accept header to serialize? |
as? | LifeCycleType | "scoped" | Option to specify type of hooks |
new Elysia()
.use(msgpack({
mimeType: "application/some-another-msgpack-type",
int64AsType: "string",
// and other msgpackr constructor options
}))
You can use Apidog to test the API with msgpack.