carlosmbolanos
carlosmbolanos

Reputation: 28

CouchDB returning HTTP 403 on required field validation

I've been working for the last couple of weeks on a small Couch/NodeJS project where I need some field validation (required, type...). I solved this by adding validate_doc_update to the design doc.

After doing some test I realized that I was receiving 403 forbidden HTTP code instead of 400 bad request, which I think is more appropriate in this use case.

CouchDB Documentation says that I can just throw one of these error objects:

Throws: forbidden error to gracefully prevent document storing. (403)

Throws: unauthorized error to prevent storage and allow the user to re-auth. (401)

Any ideas on what's the best approach to manage this kind of validation issues?

Update:

content of validate_doc_update:

function (newDoc, oldDoc, userCtx){

    function require(field, message){
        message = message || "Block must have a " + field;
        if (!newDoc[field]) throw({forbidden : message});
    };

    if(newDoc.type == "block"){
      require("name")
    }
}

I know that throw({forbidden: message}) will give 403... Is there any way to change that behaviour on CouchDB or should Ibuild my own validation middleware on express?

Upvotes: 1

Views: 939

Answers (1)

smathy
smathy

Reputation: 27971

Yeah, this is an ugly corner of CouchDB actually. I'm surprised there's still not a provision to respond with a 422 (which is much more appropriate for an invalid document than a 403), but yes - what we did was add our own middleware to do the right thing.

Upvotes: 1

Related Questions