Deepan Chelliah
Deepan Chelliah

Reputation: 81

How to create a custom javascript function and call it anywhere in marklogic?

I want to create a javascript function and load it into my own modules database and I want to call that function.

Initially, I was trying it with xquery function. I loaded the xquery function into my own modules database(like top-songs-mods). When I try to call that function I'm getting the following exception.

XDMP-MODNOTFOUND: (err:XQST0059)

I've also added the execute, update, read permissions to the document.

After that, when I loaded the same xquery function to the MODULES database(which is there by default) i can able to call that function.

I was referring to this document https://docs.marklogic.com/guide/app-dev/import_modules#id_26329

In my app-server, root is set to '/' and modules is set to 'top-songs-mods'.

Can anyone explain, how to load a module into our own modules database and import it from library module or main module and call that function anywhere?

Upvotes: 1

Views: 392

Answers (1)

Mads Hansen
Mads Hansen

Reputation: 66783

This page explains how to create a simple SJS module: https://developer.marklogic.com/learn/sjs/javascript-modules

I created a local file called test.sjs with the following content:

module.exports= {
  myFunction: test
};

function test() {
 return "test";
}

Using a similar curl command to what you posted, I PUT the test.sjs file into the example-modules database:

curl --anyauth --user admin:admin -X PUT -T test.sjs "localhost:8123/v1/documents?uri=/test.sjs&database=example-modules"

And then executing the following code in Query Console against that app server that has example-modules as the modules database:

const test = require("/test.sjs");
test.myFunction();

It executes successfully and returns: test

Upvotes: 2

Related Questions