Optimized date + boolean deserialization code

- we have to deserialize the values from the DB to turn them into moment + boolean values
- the use of lodash adds unnecessary overhead to the function, and writing it in native JS
  is a low faster
- also fixes the naming of the functions to make it clearer in flamegraphs
This commit is contained in:
Daniel Lockyer 2024-10-10 09:02:52 +01:00 committed by Daniel Lockyer
parent a2afc0af75
commit df76883378

View File

@ -26,7 +26,7 @@ module.exports = function (Bookshelf) {
* before we insert dates into the database, we have to normalize
* date format is now in each db the same
*/
fixDatesWhenSave: function fixDates(attrs) {
fixDatesWhenSave: function fixDatesWhenSave(attrs) {
const self = this;
_.each(attrs, function each(value, key) {
@ -49,15 +49,12 @@ module.exports = function (Bookshelf) {
* mysql:
* - knex wraps the UTC value into a local JS Date
*/
fixDatesWhenFetch: function fixDates(attrs) {
const self = this;
let dateMoment;
fixDatesWhenFetch: function fixDatesWhenFetch(attrs) {
const tableDef = schema.tables[this.tableName];
_.each(attrs, function each(value, key) {
if (value !== null
&& Object.prototype.hasOwnProperty.call(schema.tables[self.tableName], key)
&& schema.tables[self.tableName][key].type === 'dateTime') {
dateMoment = moment(value);
Object.keys(attrs).forEach((key) => {
if (attrs[key] && tableDef?.[key]?.type === 'dateTime') {
const dateMoment = moment(attrs[key]);
// CASE: You are somehow able to store e.g. 0000-00-00 00:00:00
// Protect the code base and return the current date time.
@ -74,12 +71,11 @@ module.exports = function (Bookshelf) {
// Convert integers to real booleans
fixBools: function fixBools(attrs) {
const self = this;
_.each(attrs, function each(value, key) {
const tableDef = schema.tables[self.tableName];
const columnDef = tableDef ? tableDef[key] : null;
if (columnDef?.type === 'boolean') {
attrs[key] = value ? true : false;
const tableDef = schema.tables[this.tableName];
Object.keys(attrs).forEach((key) => {
if (tableDef?.[key]?.type === 'boolean') {
attrs[key] = !!attrs[key];
}
});