Question

I have a javascript file, that needs to be shared between server side and client side.

Background:

The file contains validation code, I would like to use it for client side and server side validation (so both stay in sync), I also need libraries on client side to do in browser unit tests.

I am using couchapp.

Summary:

How can I serve a server side javascript file to the client?

Was it helpful?

Solution

add

{ 
  "include_design": "true" 
}

to options.json in root of couchapp.

Then views can include the design documents, you will have to edit existing views to make them not emit design docs.

Then add views/design/map.js of

function(doc) {  
    if (typeof String.prototype.startsWith != 'function') {
        String.prototype.startsWith = function (sub){
            var self=this;
            return self.substring(0, sub.length) === sub;
        }
    };

    var id = doc._id;

    if (id.startsWith( "_design/")){
        emit(null, null); // use query `include_docs=true`
    }
}

You can then write a list something like

function  (head, req) {
    var ddoc = this;

    var dir=req.query["~dir"];
    var name=req.query["~name"];

    var Result="";

    function process(row){
        if (row.doc) {
            Result = row.doc[dir][name]; 
        } 
    }

    function mainLoop(){
        while (row = getRow() ) {
            process(row);
        }
    }

    mainLoop();

    send( Result);
}

And a rewrite of

{ 
    "from": "server_lib/:~name",
    "to": "_list/sub/design",
    "query": {
        "~dir": "lib",
        "include_docs": "true"
    }
}

Note: I tried to make the query of "~path": [ "lib", ":~name" ], "include… ,but there appears to be an inconsistency (https://issues.apache.org/jira/browse/COUCHDB-2204) in couchdb, lists only work for key queries (these is code in the couchdb to treat keys different).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top