UNPKG

@4players/odin-common

Version:

A collection of commonly used type definitions and utility functions across ODIN web projects

29 lines (28 loc) 988 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toBytes = toBytes; exports.fromBytes = fromBytes; const result_1 = require("./result"); function toBytes(value) { try { (0, result_1.assert)(value !== undefined, 'undefined cannot be converted to byte array'); (0, result_1.assert)(value !== null, 'null cannot be converted to byte array'); const json = JSON.stringify(value); const decoder = new TextEncoder(); return (0, result_1.success)(decoder.encode(json)); } catch (error) { return (0, result_1.failure)(String(error)); } } function fromBytes(bytes) { try { (0, result_1.assert)(bytes.length > 0, 'empty byte array cannot be converted to value'); const json = new TextDecoder().decode(bytes); const text = JSON.parse(json); return (0, result_1.success)(text); } catch (error) { return (0, result_1.failure)(String(error)); } }