@4players/odin-common
Version:
A collection of commonly used type definitions and utility functions across ODIN web projects
25 lines (24 loc) • 784 B
JavaScript
import { assert, failure, success } from './result';
export function toBytes(value) {
try {
assert(value !== undefined, 'undefined cannot be converted to byte array');
assert(value !== null, 'null cannot be converted to byte array');
const json = JSON.stringify(value);
const decoder = new TextEncoder();
return success(decoder.encode(json));
}
catch (error) {
return failure(String(error));
}
}
export function fromBytes(bytes) {
try {
assert(bytes.length > 0, 'empty byte array cannot be converted to value');
const json = new TextDecoder().decode(bytes);
const text = JSON.parse(json);
return success(text);
}
catch (error) {
return failure(String(error));
}
}