CouchDB validation on CRUD events

79 Views Asked by At

I am trying to write a validation function for CouchDB that should only run if the used HTTP method is post (which resembles CREATE event in CRUD terms).

This is my code:

function(newDoc, oldDoc, userCtx) {
  if (newDoc.type == "post") {
    throw({forbidden : 'no way'});
  }
}

I am placing this inside a design document like so:

{
  "_id": "_design/delete",
  "_rev": "7-6bd645d2412fea53011a480d71590ff8",
  "validate_doc_update": "function(newDoc, oldDoc, userCtx) {if (newDoc.type == 'post') {throw({forbidden : 'no way'});}}"
}

I am expecting that it will refuse to create any new document I try to add to the database. But for some reason it seems like the function is never fired at all.

I am guessing my check for use of the post method is incorrect. Does anyone see what I am doing wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

For those coming here that need to check for CRUD events on documents stored in a CouchDB database. I did some experiments to define how I could check for each of the CRUD events in a CouchDB design document.

I came up with this solution (these can be used inside the condition of an if statement):

Create

newDoc !== null && oldDoc === null

Read

Implemented by adding users to a database.

For per user based restrictions on reads read this: CouchDB - prevent unauthorized reads

Update

newDoc !== null && oldDoc !== null

Delete

newDoc._deleted === true