Skip to content

Commit

Permalink
cleanNodeDecoding
Browse files Browse the repository at this point in the history
  • Loading branch information
guillemcordoba committed Oct 12, 2023
1 parent e10fe02 commit b4df105
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@holochain-open-dev/utils",
"version": "0.15.1",
"version": "0.15.2",
"description": "Common utilities to build Holochain web applications",
"author": "[email protected]",
"main": "dist/index.js",
Expand All @@ -12,7 +12,8 @@
"url": "git+https://github.com/holochain-open-dev/common.git"
},
"exports": {
".": "./dist/index.js"
".": "./dist/index.js",
"./dist/*": "./dist/*"
},
"scripts": {
"build": "npm run lint && tsc --incremental",
Expand Down
39 changes: 39 additions & 0 deletions packages/utils/src/clean-node-decoding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Deeply convert nulls into undefineds, and buffers into Uint8Array
*
* When msgpack is used to decode() in nodejs, it returns hashes as buffers
* and nulls instead of undefineds.
* This is mostly fine, except in tryorama tests when using deepEqual. This function
* is useful in that case, to allow objects constructed in the tests to deeply equal
* the return of calls to @holochain/client
*/
export function cleanNodeDecoding(object: any): any {
return deepMap(object, (value) => {
if (Buffer.isBuffer(value)) return new Uint8Array(value);
if (value === null) return undefined;
return value;
});
}

function mapObject(obj, fn) {
return Object.keys(obj).reduce((res, key) => {
res[key] = fn(obj[key]);
return res;
}, {});
}

function deepMap(obj, fn) {
const deepMapper = (val) =>
typeof val === "object" && !Buffer.isBuffer(val)
? deepMap(val, fn)
: fn(val);
if (Array.isArray(obj)) {
return obj.map(deepMapper);
}
if (obj === null) {
return fn(obj);
} else if (typeof obj === "object") {
return mapObject(obj, deepMapper);
}
return obj;
}
14 changes: 14 additions & 0 deletions packages/utils/tests/clean-node-decoding.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { encodeHashToBase64 } from "@holochain/client";
import { test, assert } from "vitest";
import { cleanNodeDecoding } from "../src/clean-node-decoding.js";

test("test clean", async () => {
const hi = {
hi: null,
bu: Buffer.from(new Uint8Array([1, 1, 1])),
};
assert.deepEqual(cleanNodeDecoding(hi), {
hi: undefined,
bu: new Uint8Array([1, 1, 1]),
});
});

0 comments on commit b4df105

Please sign in to comment.