From 22aebdcee686824eef21f3a7313dc818d5d2bc32 Mon Sep 17 00:00:00 2001 From: schmoove Date: Mon, 12 Apr 2021 09:24:05 +1200 Subject: [PATCH] Add "useBinary" option to convert to/from binary format for DB storage --- index.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/index.js b/index.js index d23aaa7..12d9b39 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,26 @@ const uuid = require('uuid/v4'); +const fromBinaryUUID = function(buf) { + return [ + buf.toString("hex", 4, 8), + buf.toString("hex", 2, 4), + buf.toString("hex", 0, 2), + buf.toString("hex", 8, 10), + buf.toString("hex", 10, 16), + ].join("-"); +}; + +const toBinaryUUID = function(uuid) { + const buf = Buffer.from(uuid.replace(/-/g, ""), "hex"); + return Buffer.concat([ + buf.slice(6, 8), + buf.slice(4, 6), + buf.slice(0, 4), + buf.slice(8, 16), + ]); +}; + /** * Export `guid`. */ @@ -14,6 +34,7 @@ module.exports = options => { options = Object.assign( { field: 'id', + useBinary: false, generateGuid: () => uuid() }, options @@ -21,6 +42,23 @@ module.exports = options => { return Model => { return class extends Model { + + /** + * After find. + */ + + $afterFind(context) { + const parent = super.$afterFind(context); + + return Promise.resolve(parent) + .then(() => { + if ( options.useBinary ) { + this[options.field] = fromBinaryUUID(this[options.field]); + } + }); + + } + /** * Before insert. */ @@ -34,6 +72,10 @@ module.exports = options => { this[options.field] || options.generateGuid.call(this, context) ) .then(guid => { + if ( options.useBinary ) { + guid = toBinaryUUID(guid) + } + this[options.field] = guid; }); }