Skip to content

JavaScript Views

Jens Alfke edited this page Aug 6, 2015 · 7 revisions

It is now possible to write map/reduce functions in JavaScript. This page explains how … after first trying to talk you out of it.

Pros:

  • You can reuse them between iOS and Android versions of a mobile app.
  • Syntax is slightly simpler than Objective-C.
  • The functions can be stored in a 'canned' database packaged with the app, and can be updated without having to recompile the app's main code.
  • The functions can be stored in a design document in a server-side database and replicated down to clients (but see the corresponding 'Con' point below!)

Cons:

  • Significantly slower to run, and use more memory, than native functions.
  • On iOS, replicating a map/reduce function from a server is a violation of Apple's App Store Review Guidelines, section 2.7: "Apps that download code in any way or form will be rejected", and Apple can reject your app or pull it from the App Store at any time. It is legal to store canned JS functions in your app package and run them, since they're installed along with the app and not downloaded by it.

How To Do It

The functionality is available as a plug-in CBLViewCompiler that you register with Couchbase Lite at launch time. Once registered, it will take care of compiling functions from design documents, converting them into native CBLMapBlock or CBLReduceBlock blocks that call the function via JavaScriptCore.

  1. Copy libCBLJSViewCompiler.a and CBLRegisterJSViewCompiler.h from the Extras folder of the Couchbase Lite binary distribution into your project's source tree.
  2. Add these files to your Xcode project.
  3. Add the built-in JavaScriptCore.framework to your target's linked libraries.
  4. In your app's Couchbase Lite initialization code, call the function CBLRegisterJSViewCompiler(), declared in CBLRegisterJSViewCompiler.h.

That's it. Couchbase Lite will now recognize JavaScript map/reduce functions stored in design documents.