Tutorial: 020 - Schema - Converters

020 - Schema - Converters

The last tutorial covered customizing table names using the generator.ADD_TABLE event. There's also a generator.ADD_COLUMN event that allows developers to add custom mappings for columns names, and also to add column converters.

If you have not reviewed the Ad-Hoc Converters tutorial, you should do so now. Building on that example, here's how one can add a BooleanConverter to all BIT-type fields.

'use strict';

const MySQLDriver      = require('node-data-mapper-mysql').MySQLDriver;
const driver           = new MySQLDriver(require('../bikeShopConOpts.json'));
const util             = require('util');
// This converter converts from database bits to JavaScript booleans.
const booleanConverter = require('node-data-mapper').booleanConverter;

// Listen for ADD_COLUMN events and add converters as needed.
driver.generator.on('ADD_COLUMN', onAddColumn);

driver
  .initialize()
  .then(runQuery)
  .then(printResult)
  .catch(console.error)
  .finally(() => driver.end());

function runQuery(dataContext) {
  // Pull all staff members.
  return dataContext
    .from('staff s')
    .select('s.staffID', 's.firstName', 's.hasStoreKeys')
    .execute();
}

function printResult(result) {
  // Note that hasStoreKeys is converted from a Buffer to a boolean.
  console.log(util.inspect(result, {depth: null}));
}

/**
 * Add a converter to BIT columns that converts to boolean.
 */
function onAddColumn(col, table) {
  if (col.dataType === 'bit') {
    col.converter = booleanConverter;
  }
}
  

The example prints the following output ($ node example/schema/converters.js):

{ staff: 
   [ { staffID: 1, firstName: 'Randy', hasStoreKeys: false },
     { staffID: 2, firstName: 'John', hasStoreKeys: true },
     { staffID: 3, firstName: 'Tina', hasStoreKeys: false },
     { staffID: 4, firstName: 'Abe', hasStoreKeys: true },
     { staffID: 5, firstName: 'Sal', hasStoreKeys: true },
     { staffID: 6, firstName: 'Valerie', hasStoreKeys: true },
     { staffID: 7, firstName: 'Kimberly', hasStoreKeys: false },
     { staffID: 8, firstName: 'Michael', hasStoreKeys: false } ] }
  

Notice that the hasStoreKeys is converted to a boolean.