fadh
fadh

Reputation: 43

CouchDb - Access replication filters in view

is it possible to use the replication filter feature of couchdb (http://wiki.apache.org/couchdb/Replication#Filtered_Replication) by requesting a view, f.e.:

.../_view/candidates?filter=hrtool/myfilter

This would be nice to filter the documents based on the usersession or userrole

Thanks in advance

fadh

Upvotes: 2

Views: 385

Answers (1)

JasonSmith
JasonSmith

Reputation: 73752

That is possible with a _list function.

List functions are Javascript code which pre-process the view output before sending it to the client. You can modify the view output in any way, such as by filtering some rows.

function(head, req) {
  // lists.filtered: filter view output by using a replication filter.

  var ddoc = this; // A common trick to explicitly identify the design document.
  function error(reason) {
    start({"code":400, "headers":{"content-type":"application/json"}});
    send(JSON.stringify({"error":reason}));
  }

  var filter_name = req.query.filter;
  if(!filter_name)
    return error("Need filter_name parameter");

  var filter_src = ddoc.filters[filter_name];
  if(!filter_src)
    return error("Invalid filter_name: " + filter_name);

  // Not 100% sure on this, you could also use new Function(args, src);
  // In the worst-case, the couchapp tool has the !code tool to copy code.
  var filter = eval(filter_src); // Not 100% sure on this
  var row;

  start({"headers":{"content-type":"application/json"}});
  send('{"rows":[\r\n');

  var first = true;
  while(row = getRow()) {
    if(filter(row)) { // Or perhaps use include_docs=true and filter(row.doc)
      if(! first)
        send(",\r\n");
      first = false;
      send(JSON.stringify(row));
    }
  }
  send("]}\r\n");
}

Use this list "filter" like any filter function:

GET /db/_design/example/_list/filtered/candidates?filter=myfilter&include_docs=true

Upvotes: 1

Related Questions