save.js 1.97 KB
Newer Older
jutatip's avatar
jutatip committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
var extend = require('lodash.assign')

module.exports = function (name, opts) {

  var engine
    , defaults =
      { idProperty: '_id'
      , logger: { info: console.info, verbose: console.info }
      , engine: undefined
      , debug: true
      }
    , options = extend({}, defaults, opts)

  if (typeof name !== 'string') {
    throw new Error('A string must be provided for \'name\'')
  }

  // If no engine is passed then default to the memory engine.
  engine = options.engine || require('./memory-engine')(
    { idProperty: options.idProperty })

  // Only log in debug mode
  if (options.debug) {

    engine.on('create', function (object) {
      options.logger.info('Creating \'' + name + '\'', JSON.stringify(object))
    })

    engine.on('update', function (object, overwrite) {
      options.logger.info('Updating \'' + name + '\'', JSON.stringify(object)
        , ' with overwrite ', overwrite)
    })

    engine.on('updateMany', function (query) {
      options.logger.info('Updating many \'' + name + '\'', JSON.stringify(query))
    })

    engine.on('delete', function (id) {
      options.logger.info('Deleting \'' + name + '\'', id)
    })

    engine.on('deleteMany', function (query) {
      options.logger.info('Deleting many \'' + name + '\'', JSON.stringify(query))
    })

    engine.on('read', function (id) {
      options.logger.info('Reading \'' + name + '\'', id)
    })

    engine.on('find', function (query, queryOptions) {
      options.logger.info('Finding \'' + name + '\'', JSON.stringify(query) , JSON.stringify(queryOptions))
    })

    engine.on('findOne', function (query, queryOptions) {
      options.logger.info('Finding One \'' + name + '\'', JSON.stringify(query) , JSON.stringify(queryOptions))
    })

    engine.on('count', function (query) {
      options.logger.info('Count \'' + name + '\'', JSON.stringify(query))
    })

    engine.on('error', function (error) {
      options.logger.error('Error with \'' + name + '\'', error)
    })
  }

  return engine
}