Code coverage report for lib/replicate/generateReplicationId.js

Statements: 100% (22 / 22)      Branches: 100% (12 / 12)      Functions: 100% (6 / 6)      Lines: 100% (22 / 22)      Ignored: none     

All files » lib/replicate/ » generateReplicationId.js
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    2 2   1 23 25 25           1 1165 1165 1165 1165   1165 23     1165 6     1165 1140 1136   1136       1136 1136           2  
'use strict';
 
var md5 = require('../deps/md5');
var collate = require('pouchdb-collate').collate;
 
function sortObjectPropertiesByKey(queryParams) {
  return Object.keys(queryParams).sort(collate).reduce(function (result, key) {
    result[key] = queryParams[key];
    return result;
  }, {});
}
 
// Generate a unique id particular to this replication.
// Not guaranteed to align perfectly with CouchDB's rep ids.
function generateReplicationId(src, target, opts) {
  var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : '';
  var filterFun = opts.filter ? opts.filter.toString() : '';
  var queryParams = '';
  var filterViewName =  '';
 
  if (opts.filter && opts.query_params) {
    queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
  }
 
  if (opts.filter && opts.filter === '_view') {
    filterViewName = opts.view.toString();
  }
 
  return src.id().then(function (src_id) {
    return target.id().then(function (target_id) {
      var queryData = src_id + target_id + filterFun + filterViewName +
        queryParams + docIds;
      return md5(queryData).then(function (md5sum) {
        // can't use straight-up md5 alphabet, because
        // the char '/' is interpreted as being for attachments,
        // and + is also not url-safe
        md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
        return '_local/' + md5sum;
      });
    });
  });
}
 
module.exports = generateReplicationId;