UNPKG

opaqueid

Version:

A basic opaque ID generator with support for types and metadata.

86 lines (85 loc) 2.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var InvalidIDError_1 = require("./error/InvalidIDError"); var InvalidIDTypeError_1 = require("./error/InvalidIDTypeError"); /** * Base64 encodes a string. * @param b The string to encode. */ function encode(str) { return Buffer.from(str).toString('base64'); } exports.encode = encode; /** * Base64 decodes a string * @param encoded The Base64 encoded string. */ function decode(encoded) { return Buffer.from(encoded, 'base64').toString('binary'); } exports.decode = decode; /** * Generates a base64 encoded opaque ID for an entity. * The default type is an empty string. * @param id The original ID. * @param type The type of the entity. */ function encodeId(id, type, metadata) { if (type === void 0) { type = ''; } var idData = type + "|" + id; if (metadata) idData += "|" + JSON.stringify(metadata); return encode(idData); } exports.encodeId = encodeId; /** * Decodes a base64 encoded ID for an entity. * @param encodedId The base64 encoded ID. * @param type The expected type of the entity. */ function decodeId(encodedId, type) { var decoded; try { decoded = decode(encodedId); // Throw an error if the ID does not contain delimeters if (!decoded.includes('|')) throw new Error('Missing delimeters'); } catch (_a) { throw new InvalidIDError_1.default(type); } // Split the decoded ID var split = decoded.split('|'); if (type !== undefined) { if (split[0] !== type) { throw new InvalidIDTypeError_1.default(type, split[0]); } } // Convert to a number if the ID is numeric return isNaN(split[1]) ? split[1] : split[1] * 1; } exports.decodeId = decodeId; /** * Returns the opaque ID's entity type. * @param encodedId The opaque ID to check. */ function getIdType(encodedId) { // Try to decode the base64 ID and get the type var type = decode(encodedId).split('|')[0]; return type === '' ? undefined : type; } exports.getIdType = getIdType; /** * Returns the opaque ID's metadata. * @param encodedId The base64 encoded ID. * @param type The expected type of the entity. */ function getIdMetadata(encodedId, type) { if (type === void 0) { type = ''; } var decoded = decode(encodedId).split('|'); if (decoded[0] !== type) { throw new InvalidIDTypeError_1.default(type, decoded[0]); } return decoded[2] ? JSON.parse(decoded[2]) : undefined; } exports.getIdMetadata = getIdMetadata;