Search code examples
javascriptevalmarklogic

passing variables to xdmp.eval()


I am trying to pass a variable into the MarkLogic 8.0.4 xdmp.eval() like this:

var spo = 'spo-role';
var spoRoleRes = xdmp.eval("var sec = require('/MarkLogic/security.xqy'); sec.createRole(role)",(role, spo),{"database" : xdmp.securityDatabase()}) 

But I have no clue how to pass the variable to the script I want to run in the securty database. The documentation seems to reflect the XQY docs, see xdmp.eval-docs

Under variables, the doc talks about map:map() objects which are not js but xqy concepts. Same for QName

I tried a sequence, a JSON object, several versions of clark notation but no clue what namespace I should use here?

Question: How to pass a variable to a xdmp.eval()?


Solution

  • In most places where you would use a map in xQuery, you can use an object in javascript. Although the options documentation is silly in that it talks in terms of XDMP, the actual API parameter definition shows that it expects an object.

    When passing an object as the second parameter to xdmp.eval, it expands this and creates local variables in your evaluated code for every object property.

    I have provided a simple proof of concept to help you understand what happens:

    var data = {
      "foo": "bar",
      "baz": "buz"
    }
    
    xdmp.eval(
      "declareUpdate();   xdmp.documentInsert('/foo/' + baz + '.json', {'a':'aaa'} )",
      data
    )
    

    Result is a document in the current database called /foo/buz.json

    Why?

    • Because I passed in the object called data.
    • This object has two properties (foo and baz)
    • These were turned into two variables
      1. foo = bar
      2. baz = buz
    • Therefore, "/foo/" + baz + ".json" = /foo/buz.json