| import Promise from 'pouchdb-promise'; |
| import { binaryMd5 } from 'pouchdb-md5'; |
| import { btoa } from 'pouchdb-binary-utils'; |
| |
| function sortObjectPropertiesByKey(queryParams) { |
| return Object.keys(queryParams).sort().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() : ''; |
| 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 Promise.all([src.id(), target.id()]).then(function (res) { |
| var queryData = res[0] + res[1] + filterFun + filterViewName + |
| queryParams + docIds; |
| if (process.env.POUCHDB_LITE) { |
| // do a simple btoa algorithm, not a full md5sum |
| return Promise.resolve('_local/' + btoa(queryData)); |
| } else { |
| return new Promise(function (resolve) { |
| binaryMd5(queryData, resolve); |
| }).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; |
| }); |
| } |
| }); |
| } |
| |
| export default generateReplicationId; |