Last active
February 6, 2020 20:19
-
-
Save js-ms/73c95a499b61aa1154ebeed547ed9156 to your computer and use it in GitHub Desktop.
Provider created for making the uuid stored as Binary(16) readable as a string (Adonisjs)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
** You only need to put this file inside your Traits | |
** Feel free to contribute | |
** to call it in your models just put this.addTrait('Uuid'); | |
** if you want to create the trait with options, | |
** just pass the uuid properties array: this.addTrait('Uuid', ['field']); | |
** each position in the array refers to a key with uuid format inside your model | |
** another way is creating a get function, e.g: get uuidFields() { return ['field1', 'field 2']; } | |
**/ | |
const uuidv4 = require('uuid/v4'); | |
class readableUuid { | |
constructor() { | |
this.fields = []; | |
} | |
register(Model, options) { | |
this.fields = (options.length > 0 ? options : null) || Model.prototype.uuidFields || []; | |
Model.addHook('beforeCreate', this._beforeCreate.bind(this)); | |
Model.addHook('afterSave', this._afterSave.bind(this)); | |
Model.addHook('afterFind', this._afterFind.bind(this)); | |
Model.addHook('afterFetch', this._afterFetch.bind(this)); | |
Model.addHook('afterPaginate', this._afterFetch.bind(this)); | |
} | |
_beforeCreate(instance) { | |
const uuid = uuidv4().replace(/-/g, ''); | |
const binaryUUID = Buffer.from(uuid, 'hex'); | |
instance.id = binaryUUID; | |
} | |
_afterSave(instance) { | |
this.fields.map((field) => { | |
if (instance[field] && Buffer.isBuffer(instance[field])) { | |
instance[field] = Buffer.from(instance[field], 'hex').toString('hex'); | |
} | |
}); | |
} | |
_afterFind(instance) { | |
this.fields.map((field) => { | |
if (instance[field] && Buffer.isBuffer(instance[field])) { | |
instance[field] = Buffer.from(instance[field], 'hex').toString('hex'); | |
} | |
}); | |
} | |
_afterFetch(instances) { | |
instances.map((instance) => { | |
this.fields.map((field) => { | |
if (instance[field] && Buffer.isBuffer(instance[field])) { | |
instance[field] = Buffer.from(instance[field], 'hex').toString('hex'); | |
} | |
}); | |
}); | |
} | |
_afterPaginate(data, meta = null) { | |
data.map((instance) => { | |
this.fields.map((field) => { | |
if (instance[field] && Buffer.isBuffer(instance[field])) { | |
instance[field] = Buffer.from(instance[field], 'hex').toString('hex'); | |
} | |
}); | |
}); | |
} | |
} | |
module.exports = readableUuid; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment