A formatter
is a CommonJS module that exports two functions: load
, used
to load the configuration when the configfile
option is passed to mb start
,
and save
, used to save the configuration for mb save
. The formatter
gives you total control over how the test data is stored, allowing you to improve readability
(which suffers by default from JSON's single line requirement for strings) or to convert between
formats of other service virtualization tools.
The default formatter that ships with mountebank is described above ("Default config file parsing"). The example below shows a simple (and silly) formatter that encodes all data as Base64.
'use strict';
function encode (obj) {
return Buffer.from(JSON.stringify(obj)).toString('base64');
}
function decode (text) {
return Buffer.from(text, 'base64').toString('utf8');
}
function load (options) {
const fs = require('fs'),
contents = fs.readFileSync(options.configfile, { encoding: 'utf8' });
return JSON.parse(decode(contents));
}
function save (options, imposters) {
const fs = require('fs');
if (options.customName && imposters.imposters.length > 0) {
imposters.imposters[0].name = options.customName;
}
fs.writeFileSync(options.savefile, encode(imposters));
}
module.exports = { load, save };
Assuming the module is saved as 'customFormatter.js', the following commands will use it for saving and loading:
mb save --savefile mb.json --formatter customFormatter
mb restart --configfile mb.json --formatter customFormatter