8.2. JavaScript

Note

While every design function has access to all JavaScript objects, the tablebelow describes appropriate usage cases. For example, you may useemit() in Map Functions, but getRow() is not permittedduring Map Functions.

JS Function Reasonable to use in design doc functions
emit() Map Functions
getRow() List Functions
JSON any
isArray() any
log() any
provides() Show Functions, List Functions
registerType() Show Functions, List Functions
require() any, except Reduce and Rereduce Functions
send() List Functions
start() List Functions
sum() any
toJSON() any

8.2.1. Design functions context

Each design function executes in a special context of predefined objects,modules and functions:

emit(key, value)

Emits a key-value pair for further processing by CouchDB after the mapfunction is done.

|Arguments:
|——-
|
- key – The view key
- value – The key’s associated value





  1. function(doc){
    emit(doc.id, doc._rev);
    }



getRow()

Extracts the next row from a related view result.

|Returns:
|——-
|View result row
|Return type:
|——-
|object





  1. function(head, req){
    send('[');
    row = getRow();
    if (row){
    send(toJSON(row));
    while(row = getRow()){
    send(',');
    send(toJSON(row));
    }
    }
    return ']';
    }



JSON

JSON2object.
isArray(_obj)

A helper function to check if the provided value is an Array.

|Arguments:
|——-
|
- obj – Any JavaScript value
|Returns:
|——-
|
true if obj is Array-typed, false otherwise

|Return type:
|——-
|
boolean


log(message)

Log a message to the CouchDB log (at the INFO level).

|Arguments:
|——-
|
- message – Message to be logged





  1. function(doc){
    log('Procesing doc ' + doc['id']);
    emit(doc['_id'], null);
    }




After the map function has run, the following line can be found in CouchDBlogs (e.g. at
/var/log/couchdb/couch.log):




  1. [Sat, 03 Nov 2012 17:38:02 GMT] [info] [<0.7543.0>] OS Process #Port<0.3289> Log :: Processing doc 8d300b86622d67953d102165dbe99467



provides(_key, func)

Registers callable handler for specified MIME key.

|Arguments:
|——-
|
- key – MIME key previously defined by registerType()
- func – MIME type handler

registerType(key, *mimes)

Registers list of MIME types by associated key.

|Arguments:
|——-
|
- key – MIME types
- mimes – MIME types enumeration


Predefined mappings (key-array):

- all: /
- text: text/plain; charset=utf-8, txt
- html: text/html; charset=utf-8
- xhtml: application/xhtml+xml, xhtml
- xml: application/xml, text/xml, application/x-xml
- js: text/javascript, application/javascript,application/x-javascript
- css: text/css
- ics: text/calendar
- csv: text/csv
- rss: application/rss+xml
- atom: application/atom+xml
- yaml: application/x-yaml, text/yaml
- multipart_form: multipart/form-data
- url_encoded_form: application/x-www-form-urlencoded
- json: application/json, text/x-json
require(path)

Loads CommonJS module by a specified path. The path should not start witha slash.

|Arguments:
|——-
|
- path – A CommonJS module path started from design document root
|Returns:
|——-
|
Exported statements


send(chunk)

Sends a single string chunk in response.

|Arguments:
|——-
|
- chunk – Text chunk





  1. function(head, req){
    send('Hello,');
    send(' ');
    send('Couch');
    return ;
    }



start(init_resp)

Initiates chunked response. As an option, a customresponse object may be sent at this point.For list-functions only!


Note

list functions may set the HTTP response code and headers by callingthis function. This function must be called before send(),getRow() or a return statement; otherwise, the query server willimplicitly call this function with the empty object ({}).





  1. function(head, req){
    start({
    "code": 302,
    "headers": {
    "Location": "http://couchdb.apache.org&#34;
    }
    });
    return "Relax!";
    }



sum(arr)

Sum arr’s items.

|Arguments:
|——-
|
- arr – Array of numbers
|Return type:
|——-
|
number


toJSON(obj)

Encodes obj to JSON string. This is an alias for the JSON.stringifymethod.

|Arguments:
|——-
|
- obj – JSON-encodable object
|Returns:
|——-
|
JSON string


8.2.2. CommonJS Modules

Support for CommonJS Modules(introduced in CouchDB 0.11.0) allows you to create modular design functionswithout the need for duplication of functionality.

Here’s a CommonJS module that checks user permissions:

  1. function user_context(userctx, secobj) {
  2. var is_admin = function() {
  3. return userctx.indexOf('_admin') != -1;
  4. }
  5. return {'is_admin': is_admin}
  6. }
  7.  
  8. exports['user'] = user_context

Each module has access to additional global variables:

  • module (object): Contains information about the stored module
    • id (string): The module id; a JSON path in ddoc context
    • current (code): Compiled module code object
    • parent (object): Parent frame
    • exports (object): Export statements
  • exports (object): Shortcut to the module.exports object
    The CommonJS module can be added to a design document, like so:
  1. {
  2. "views": {
  3. "lib": {
  4. "security": "function user_context(userctx, secobj) { ... }"
  5. }
  6. },
  7. "validate_doc_update": "function(newdoc, olddoc, userctx, secobj) {
  8. user = require('views/lib/security').user(userctx, secobj);
  9. return user.is_admin();
  10. }"
  11. "_id": "_design/test"
  12. }

Modules paths are relative to the design document’s views object, butmodules can only be loaded from the object referenced via lib. Thelib structure can still be used for view functions as well, by simplystoring view functions at e.g. views.lib.map, views.lib.reduce, etc.

原文: http://docs.couchdb.org/en/stable/query-server/javascript.html