Skip to content
This repository has been archived by the owner on Jul 5, 2024. It is now read-only.

Commit

Permalink
serialization works
Browse files Browse the repository at this point in the history
  • Loading branch information
KATT committed Oct 5, 2023
1 parent 18833c1 commit 9b2d833
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 3 deletions.
70 changes: 68 additions & 2 deletions src/async/serializeAsync.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { expect, test } from "vitest";

import { tsonAsyncIterator, tsonPromise } from "../index.js";
import { createAsyncTsonSerialize } from "./serializeAsync.js";
import { tsonAsyncIterator, tsonBigint, tsonPromise } from "../index.js";
import {
createAsyncTsonSerialize,
createAsyncTsonStringify,
} from "./serializeAsync.js";

test("serialize promise", async () => {
const serialize = createAsyncTsonSerialize({
Expand Down Expand Up @@ -152,3 +155,66 @@ test("serialize async iterable", async () => {
]
`);
});

test("stringify async iterable + promise", async () => {
const stringify = createAsyncTsonStringify({
nonce: () => "__tson",
types: [tsonAsyncIterator, tsonPromise, tsonBigint],
});

async function* iterable() {
await new Promise((resolve) => setTimeout(resolve, 1));
yield 1n;
yield 2n;
}

const obj = {
foo: "bar",
iterable: iterable(),
promise: Promise.resolve(42),
};
const buffer: string[] = [];
for await (const value of stringify(obj, 2)) {
buffer.push(value.trimEnd());
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const head: any = JSON.parse(buffer[1]!);

expect(buffer).toMatchInlineSnapshot(`
[
"[",
" {\\"json\\":{\\"foo\\":\\"bar\\",\\"iterable\\":[\\"AsyncIterator\\",0,\\"__tson\\"],\\"promise\\":[\\"Promise\\",1,\\"__tson\\"]},\\"nonce\\":\\"__tson\\"}",
" ,",
" [",
" [1,[0,42]]",
" ,[0,[0,[\\"bigint\\",\\"1\\",\\"__tson\\"]]]",
" ,[0,[0,[\\"bigint\\",\\"2\\",\\"__tson\\"]]]",
" ,[0,[2]]",
" ]",
"]",
]
`);

expect(head).toMatchInlineSnapshot(`
{
"json": {
"foo": "bar",
"iterable": [
"AsyncIterator",
0,
"__tson",
],
"promise": [
"Promise",
1,
"__tson",
],
},
"nonce": "__tson",
}
`);

expect(head.json.iterable[0]).toBe("AsyncIterator");
expect(head.json.promise[0]).toBe("Promise");
});
2 changes: 1 addition & 1 deletion src/async/serializeAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ function walkerFactory(nonce: TsonNonce, types: TsonAsyncOptions["types"]) {
);
}

const valueTuple: TsonAsyncValueTuple = [idx, result.value];
const valueTuple: TsonAsyncValueTuple = [idx, walk(result.value)];
yield valueTuple;
} while (iterators.size > 0);
},
Expand Down

0 comments on commit 9b2d833

Please sign in to comment.