1

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?

SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42
  • It seems that your function is avoiding the creation of any doc that has an attribute "type" with value "post", it is not related with the HTTP method used PUT/POST in the API invocation. It is not clear what you need to do. – Juanjo Rodriguez Sep 12 '19 at 10:16
  • @JuanjoRodriguez do you know how I get access to the current invoked HTTP method? – SomeDutchGuy Sep 12 '19 at 10:28

1 Answers1

1

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
SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42