I'm using couchrest_model to interact with CouchDB from ruby. I have a bunch of documents in a database, each of which I've added a key "updated_by" to, which I want to keep information about the user who made the changes that generated that revision.

Is this the right way to do things?

If this is the right way, how should I use couchrest_model so that I can make requests of user data as well as my main database?

Thanks!

有帮助吗?

解决方案

The only way is to force updated_by field by equal userCtx.name value thought validate_doc_update function:

function(newdoc, olddoc, userctx, secobj){
   if (newdoc.updated_by != userctx.name)
       throw({"forbidden": "`updated_by` field should match real updater user name"})
}

This function will control content for all documents (except design ones), requiring them to have data in the way you expected.

You may stop at this point, but he has one flaw: all your clients will have to set this field manually. That's awkward and not let them to "relax". To solve this problem CouchDB provides update functions, that allows to setup some part of business logic on server side removing this knowledge from client realizations. So your update function may looks like:

function(doc, req){
   if (!doc){ // new doc
     doc = JSON.parse(req.body);
   }
   doc.updated_by = req.userCtx.name;
   return [doc, {"json": {"status": "ok"}}
}

And he let you setup updated_by field in right way. More over, you may extend this function by adding more and more meta fields (e.g. userCtx.peer hold client IP address) and if your clients will use it they wouldn't require any updates on you metadata changes.

But note that you need to provide some exceptions for service users or you'll get broken replications between CouchDB nodes since validate function will reject all documents which has different from user name updated_by value.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top