RepoConnection

node~ RepoConnection

(private) new RepoConnection() → {*}

Creates a new repo-connection.

Returns:

native Native repo-connection object.

Type
*

Methods

commit(…keys, messageopt) → {object}

This function commits the active version of nodes.

Parameters:
Name Type Attributes Description
keys string | Array.<string> <repeatable>

Node keys to commit. Each argument could be an id, a path or an array of the two. Prefer the usage of ID rather than paths.

message string <optional>

Commit message.

Returns:

Commit object.

Type
object
Examples
// Commits a node.
var result1 = repo.commit({keys: 'nodeId'});

log.info('Commit created with id ' + result1._id);
// Commit created.
var expected1 = {
    "id": "aa1f76bf-4bb9-41be-b166-03561c1555b2",
    "message": "",
    "committer": "user:system:anonymous",
    "timestamp": "2019-01-24T15:16:36.260799Z"
};
// Commits nodes.
var result2 = repo.commit({
    keys: ['nodeId', 'nodeId2'],
    message: 'Commit message'
});

log.info('Commit created with id ' + result2._id);
// Commit created.
var expected2 = {
    "id": "aa1f76bf-4bb9-41be-b166-03561c1555b2",
    "message": "Commit message",
    "committer": "user:system:anonymous",
    "timestamp": "2019-01-24T15:16:36.260799Z"
};

create(params) → {object}

This function creates a node.

To create a content where the name is not important and there could be multiple instances under the same parent content, skip the name parameter and specify a displayName.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Description
_name string <optional>

Name of content.

_parentPath string <optional>

Path to place content under.

_indexConfig object <optional>

How the document should be indexed. A default value "byType" will be set if no value specified.

_permissions object <optional>

The access control list for the node. By default the creator will have full access

_inheritsPermissions boolean <optional>

true if the permissions should be inherited from the node parent. Default is false.

_manualOrderValue number <optional>

Value used to order document when ordering by parent and child-order is set to manual

_childOrder string <optional>

Default ordering of children when doing getChildren if no order is given in query

Returns:

Node created as JSON.

Type
object
Examples
var nodeLib = require('/lib/xp/node');

// Connect to repo
var repo = nodeLib.connect({
    repoId: "com.enonic.cms.default",
    branch: "master"
});

// Create node.
var result1 = repo.create({
    likes: "plywood",
    numberOfUselessGadgets: 123
});

log.info('Node created with id ' + result1._id);
// Node created.
var expected = {
    "_id": "a-random-node-id",
    "_childOrder": "_ts DESC",
    "_indexConfig": {
        "default": {
            "decideByType": true,
            "enabled": true,
            "nGram": false,
            "fulltext": false,
            "includeInAllText": false,
            "path": false,
            "indexValueProcessors": [],
            "languages": []
        },
        "configs": []
    },
    "_inheritsPermissions": false,
    "_permissions": [
        {
            "principal": "role:system.admin",
            "allow": [
                "READ",
                "CREATE",
                "MODIFY",
                "DELETE",
                "PUBLISH",
                "READ_PERMISSIONS",
                "WRITE_PERMISSIONS"
            ],
            "deny": []
        }
    ],
    "_state": "DEFAULT",
    "_nodeType": "default",
    "likes": "plywood",
    "numberOfUselessGadgets": 123
};
var nodeLib = require('/lib/xp/node');
var valueLib = require('/lib/xp/value');

// Connect to repo
var repo = nodeLib.connect({
    repoId: "com.enonic.cms.default",
    branch: "master"
});

// Create node.
var result1 = repo.create({
    _name: "myName",
    displayName: "This is brand new node",
    myExtraPath: "/this/is/a/path",
    someData: {
        cars: [
            "skoda", "tesla model X"
        ],
        likes: "plywood",
        numberOfUselessGadgets: 123,
        myGeoPoint: valueLib.geoPoint(80, -80),
        myGeoPoint2: valueLib.geoPointString("80,-30"),
        myInstant: valueLib.instant("2016-08-01T11:22:00Z"),
        myReference: valueLib.reference("1234"),
        myLocalDateTime: valueLib.localDateTime("2016-01-08T10:00:00.000"),
        myLocalDate: valueLib.localDate("2016-01-08"),
        myLocalTime: valueLib.localTime("10:00:00.000"),
        myBinaryReference: valueLib.binary('myFile', byteSource1),
        myBinaryReference2: valueLib.binary('myFile2', byteSource2)
    },
    _indexConfig: {
        default: "byType",
        configs: [
            {
                path: "displayName",
                config: "fulltext"
            },
            {
                path: "someData.cars",
                config: "minimal"
            },
            {
                path: "myExtraPath",
                config: "path"
            }]
    },
    _permissions: [
        {
            "principal": "role:admin",
            "allow": [
                "READ",
                "CREATE",
                "MODIFY",
                "DELETE",
                "PUBLISH",
                "READ_PERMISSIONS",
                "WRITE_PERMISSIONS"
            ],
            "deny": []
        }
    ]
});

log.info('Node created with id ' + result1._id);
// Node created.
var expected = {
        "_id": "nodeId",
        "_name": "my-name",
        "_path": "/my-name",
        "_childOrder": "_ts DESC",
        "_indexConfig": {
            "default": {
                "decideByType": false,
                "enabled": true,
                "nGram": false,
                "fulltext": false,
                "includeInAllText": false,
                "path": false,
                "indexValueProcessors": [],
                "languages": []
            },
            "configs": [
                {
                    "path": "displayName",
                    "config": {
                        "decideByType": false,
                        "enabled": true,
                        "nGram": true,
                        "fulltext": true,
                        "includeInAllText": true,
                        "path": false,
                        "indexValueProcessors": [],
                        "languages": []
                    }
                }
            ]
        },
        "_inheritsPermissions": false,
        "_permissions": [
            {
                "principal": "role:admin",
                "allow": [
                    "READ",
                    "CREATE",
                    "MODIFY",
                    "DELETE",
                    "PUBLISH",
                    "READ_PERMISSIONS",
                    "WRITE_PERMISSIONS"
                ],
                "deny": []
            }
        ],
        "_state": "DEFAULT",
        "_nodeType": "default",
        "_versionKey": "versionKey",
        "_ts": "2010-10-10T10:10:10.100Z",
        "displayName": "This is brand new node",
        "someData": {
            "cars": [
                "skoda",
                "tesla model x"
            ],
            "likes": "plywood",
            "numberOfUselessGadgets": 123
        }
    }
    ;

delete(…keys) → {boolean}

This function deletes a node or nodes.

Parameters:
Name Type Attributes Description
keys string | Array.<string> <repeatable>

Keys to delete. Each argument could be an id, a path or an array of the two.

Returns:

True if deleted, false otherwise.

Type
boolean
Examples
// Deletes a node.
var result1 = repo.delete('nodeId');

log.info(result1.length + ' nodes deleted.');
// Deletes nodes.
var result2 = repo.delete('nodeId', '/node2-path', 'anotherNodeId');

log.info(result2.length + ' nodes deleted.');
// Deletes nodes.
var nodeIds = ['nodeId', '/node2-path'];
var result3 = repo.delete(nodeIds);

log.info(result3.length + ' nodes deleted.');

diff(params) → {object}

This function resolves the differences for node between current and given branch

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Default Description
key string

Path or id to resolve diff for

target string

Branch to diff against.

includeChildren boolean <optional>
false

also resolve dependencies for children

Returns:

DiffNodesResult

Type
object
Examples
// Diff the given node in the current branch and the targetBranch
var result = repo.diff({
    key: ['a'],
    target: 'otherBranch',
    includeChildren: true
});
// Node created.
var expected = {
    "diff": [
        {
            "id": "a",
            "status": "NEW"
        },
        {
            "id": "b",
            "status": "MOVED"
        },
        {
            "id": "c",
            "status": "OLDER"
        }
    ]
};

findChildren(params) → {object}

Get children for given node.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Default Description
parentKey number

path or id of parent to get children of

start number <optional>
0

Start index (used for paging).

count number <optional>
10

Number of contents to fetch.

childOrder string <optional>

How to order the children (defaults to value stored on parent)

countOnly boolean <optional>
false

Optimize for count children only ( no children returned )

recursive boolean <optional>
false

Do recursive fetching of all children of children

Returns:

Result of getChildren.

Type
object
Examples
// Query content using aggregations.
var repo = nodeLib.connect({
    repoId: "com.enonic.cms.default",
    branch: "master"
});

var result = repo.findChildren({
    start: 0,
    count: 2,
    parentKey: "abc"
});

log.info('Found ' + result.total + ' number of contents');

for (var i = 0; i < result.hits.length; i++) {
    var node = result.hits[i];
    log.info('Node ' + node.id + ' found');
}
// Result set returned.
var expected = {
    "total": 12902,
    "count": 2,
    "hits": [
        {
            "id": "b186d24f-ac38-42ca-a6db-1c1bda6c6c26"
        },
        {
            "id": "350ba4a6-589c-498b-8af0-f183850e1120"
        }
    ]
};

findVersions(params) → {Array.<object>}

This function returns node versions.

Parameters:
Name Type Description
params object

JSON parameters.

Properties
Name Type Attributes Default Description
key string

Path or ID of the node.

start number <optional>
0

Start index (used for paging).

count number <optional>
10

Number of node versions to fetch.

Returns:

Node versions.

Type
Array.<object>

get(…keys) → {object}

This function fetches nodes.

Parameters:
Name Type Attributes Description
keys string | Array.<string> <repeatable>

to fetch. Each argument could be an id, a path or an array of the two.

Returns:

The node or node array (as JSON) fetched from the repository.

Type
object
Examples
// Fetches a node.
var result1 = repo.get('nodeId');

if (result1) {
    log.info('Node "' + result1._id + '" found');
} else {
    log.info('Node not found.');
}
// Fetches nodes.
var result2 = repo.get('nodeId', '/node2-path', 'node3Id');
log.info(result2.length + ' nodes found.');
// Node fetched.
var expected = {
    "_id": "nodeId",
    "_name": "my-name",
    "_path": "/my-name",
    "_childOrder": "_ts DESC",
    "_indexConfig": {
        "default": {
            "decideByType": false,
            "enabled": true,
            "nGram": false,
            "fulltext": false,
            "includeInAllText": false,
            "path": false,
            "indexValueProcessors": [],
            "languages": []
        },
        "configs": [
            {
                "path": "displayName",
                "config": {
                    "decideByType": false,
                    "enabled": true,
                    "nGram": true,
                    "fulltext": true,
                    "includeInAllText": true,
                    "path": false,
                    "indexValueProcessors": [],
                    "languages": []
                }
            }
        ]
    },
    "_inheritsPermissions": false,
    "_permissions": [
        {
            "principal": "role:admin",
            "allow": [
                "READ",
                "CREATE",
                "MODIFY",
                "DELETE",
                "PUBLISH",
                "READ_PERMISSIONS",
                "WRITE_PERMISSIONS"
            ],
            "deny": []
        }
    ],
    "_state": "DEFAULT",
    "_nodeType": "default",
    "_versionKey": "versionKey",
    "_ts": "2010-10-10T10:10:10.100Z",
    "displayName": "This is brand new node",
    "someData": {
        "cars": [
            "skoda",
            "tesla model x"
        ],
        "likes": "plywood",
        "numberOfUselessGadgets": 123
    }
};
// Fetches a node from an array of keys.

var result3 = repo.get('node1', 'node2');

log.info(result3.length + ' nodes found.');
// Fetches a node from an array of keys.

var nodeKeys = ['node1', 'node2', 'node3'];
var result1 = repo.get(nodeKeys);

log.info(result1.length + ' nodes found.');
// Fetches a node from an array of keys.

var nodeKeys1 = ['node1', 'node2', 'node3'];
var nodeKeys2 = ['node4', 'node5', 'node6'];
var result2 = repo.get(nodeKeys1, nodeKeys2);

log.info(result2.length + ' nodes found.');

getActiveVersion(params) → {object}

This function returns the active version of a node.

Parameters:
Name Type Description
params object

JSON parameters.

Properties
Name Type Description
key string

Path or ID of the node.

Returns:

Active content versions per branch.

Type
object

getBinary(params) → {*}

This function returns a binary stream.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Description
key string

Path or id to the node.

binaryReference string

to the binary.

Returns:

Stream of the binary.

Type
*
Example
// Fetches a node.
var myRepo = nodeLib.connect({
    repoId: 'my-repo',
    branch: 'master'
});

var binaryStream = myRepo.getBinary({
    key: "/myNode",
    binaryReference: "myBinaryReference"
});

modify(params) → {object}

This function modifies a node.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Description
key string

Path or id to the node.

editor function

Editor callback function.

Returns:

Modified node as JSON.

Type
object
Examples
var repo = nodeLib.connect({
    repoId: "com.enonic.cms.default",
    branch: "master"
});

// Editor to call for node.
function editor(node) {

    node._childOrder = "updatedOrderField DESC";
    node._permissions = [
        {
            "principal": "user:system:newUser",
            "allow": [
                "CREATE"
            ],
            "deny": []
        },
        {
            "principal": "role:newRole",
            "allow": [
                "MODIFY"
            ],
            "deny": []
        }
    ];
    node._indexConfig = {
        default: "fulltext",
        configs: {
            path: "displayName",
            config: "none"
        }
    };

    node.myString = 'modified';
    node.mySet.myGeoPoint = valueLib.geoPoint(0, 0);
    node.myArray = ["modified1", "modified2", "modified3"];
    node.myBinaryReference = valueLib.binary('myFile', stream1);

    delete node.toBeRemoved;

    return node;
}

// Modify node by id
var result = repo.modify({
    key: 'abc',
    editor: editor
});

if (result) {
    log.info('Node modified');
} else {
    log.info('Node not found');
}
// Node modified.
var expected = {
    "_id": "abc",
    "_name": "myNode",
    "_path": "/myNode",
    "_childOrder": "updatedorderfield DESC",
    "_indexConfig": {
        "default": {
            "decideByType": false,
            "enabled": true,
            "nGram": true,
            "fulltext": true,
            "includeInAllText": true,
            "path": false,
            "indexValueProcessors": [],
            "languages": []
        },
        "configs": [
            {
                "path": "displayName",
                "config": {
                    "decideByType": false,
                    "enabled": false,
                    "nGram": false,
                    "fulltext": false,
                    "includeInAllText": false,
                    "path": false,
                    "indexValueProcessors": [],
                    "languages": []
                }
            }
        ]
    },
    "_inheritsPermissions": false,
    "_permissions": [
        {
            "principal": "role:newRole",
            "allow": [
                "MODIFY"
            ],
            "deny": []
        },
        {
            "principal": "user:system:newUser",
            "allow": [
                "CREATE"
            ],
            "deny": []
        }
    ],
    "_state": "DEFAULT",
    "_nodeType": "default",
    "notChanged": "originalValue",
    "myString": "modified",
    "mySet": {
        "myGeoPoint": "0.0,0.0"
    },
    "myArray": [
        "modified1",
        "modified2",
        "modified3"
    ],
    "myBinaryReference": "myFile"
};

move(params) → {boolean}

Rename a node or move it to a new path.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Description
source string

Path or id of the node to be moved or renamed.

target string

New path or name for the node. If the target ends in slash '/', it specifies the parent path where to be moved. Otherwise it means the new desired path or name for the node.

Returns:

True if the node was successfully moved or renamed, false otherwise.

Type
boolean
Examples
// Rename content by id. Keeps same parent.
var content1 = repo.move({
    source: 'nodeId',
    target: 'new-name'
});

log.info('New path: ' + content1._path); // '/new-name'
// Move content by path. New parent path, keeps same name.
var content2 = repo.move({
    source: '/my-name',
    target: '/content/my-site/folder/'
});

log.info('New path: ' + content2._path); // '/content/my-site/folder/my-name'
// Move and rename content by path.
var content3 = repo.move({
    source: '/my-name',
    target: '/content/my-site/folder/new-name'
});

log.info('New path: ' + content3._path); // '/content/my-site/folder/new-name'

push(params) → {object}

This function push a node to a given branch.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Default Description
key Array.<string>

Id or path to the nodes

keys Array.<string>

Array of ids or paths to the nodes

target string

Branch to push nodes to.

includeChildren boolean <optional>
false

Also push children of given nodes

resolve boolean <optional>
true

Resolve dependencies before pushing, meaning that references will also be pushed

exclude Array.<string> <optional>

Array of ids or paths to nodes not to be pushed (nodes needed to maintain data integrity (e.g parents must be present in target) will be pushed anyway)

Returns:

PushNodesResult

Type
object
Examples
// Push nodes from current branch
var result = repo.push({
    keys: ['a'],
    target: 'otherBranch',
    resolve: false
});
// Node created.
var expected = {
    "success": [
        "a"
    ],
    "failed": [],
    "deleted": []
};
// Rename content by id. Keeps same parent.
var result = repo.push({
    keys: ['a'],
    target: 'otherBranch',
    resolve: true,
    includeChildren: true
});
// Node created.
var expected = {
    "success": [
        "a",
        "b",
        "c"
    ],
    "failed": [
        {
            "id": "d",
            "reason": "ACCESS_DENIED"
        }
    ],
    "deleted": []
};
// Rename content by id. Keeps same parent.
var result = repo.push({
    keys: ['/a'],
    target: 'otherBranch',
    resolve: true,
    includeChildren: true,
    exclude: ['/a/b', '/a/c']
});
// Node created.
var expected = {
    "success": [
        "a",
        "d"
    ],
    "failed": [],
    "deleted": []
};

query(params) → {object}

This command queries nodes.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Default Description
start number <optional>
0

Start index (used for paging).

count number <optional>
10

Number of contents to fetch.

query string

Query expression.

filters object <optional>

Query filters

sort string <optional>
'_score DESC'

Sorting expression.

aggregations string <optional>

Aggregations expression.

explain boolean <optional>
false

Return score calculation explanation.

Returns:

Result of query.

Type
object
Examples
// Query content using aggregations.
var result = repo.query({
    start: 0,
    count: 2,
    query: "startTime > instant('2016-10-11T14:38:54.454Z')",
    filters: {
        boolean: {
            must: [
                {
                    exists: {
                        field: "modifiedTime"
                    }
                },
                {
                    exists: {
                        field: "other"
                    }
                }
            ],
            mustNot: {
                hasValue: {
                    field: "myField",
                    values: [
                        "cheese",
                        "fish",
                        "onion"
                    ]
                }
            }
        },
        notExists: {
            field: "unwantedField"
        },
        ids: {
            values: ["id1", "id2"]
        }
    },
    sort: "duration DESC",
    aggregations: {
        urls: {
            terms: {
                field: "url",
                order: "_count desc",
                size: 2
            },
            aggregations: {
                duration: {
                    histogram: {
                        field: "duration",
                        interval: 100,
                        minDocCount: 1,
                        extendedBoundMin: 0,
                        extendedBoundMax: 10000,
                        order: "_key desc"
                    }
                },
                durationStats: {
                    stats: {
                        field: "duration"
                    }
                }
            }
        }
    }
});

log.info('Found ' + result.total + ' number of contents');

for (var i = 0; i < result.hits.length; i++) {
    var node = result.hits[i];
    log.info('Node ' + node.id + ' found');
}
// Result set returned.
var expected = {
    "total": 12902,
    "count": 2,
    "hits": [
        {
            "id": "b186d24f-ac38-42ca-a6db-1c1bda6c6c26",
            "score": 1.2300000190734863
        },
        {
            "id": "350ba4a6-589c-498b-8af0-f183850e1120",
            "score": 1.399999976158142
        }
    ],
    "aggregations": {
        "urls": {
            "buckets": [
                {
                    "key": "/site/draft/superhero/search",
                    "docCount": 6762,
                    "duration": {
                        "buckets": [
                            {
                                "key": "1600",
                                "docCount": 2
                            },
                            {
                                "key": "1400",
                                "docCount": 1
                            },
                            {
                                "key": "1300",
                                "docCount": 5
                            }
                        ]
                    }
                },
                {
                    "key": "/site/draft/superhero",
                    "docCount": 1245,
                    "duration": {
                        "buckets": [
                            {
                                "key": "1600",
                                "docCount": 2
                            },
                            {
                                "key": "1400",
                                "docCount": 1
                            },
                            {
                                "key": "1300",
                                "docCount": 5
                            }
                        ]
                    }
                }
            ]
        }
    }
};

refresh(modeopt)

Refresh the index for the current repoConnection

Parameters:
Name Type Attributes Description
mode string <optional>

Refresh all (ALL) data, or just the search-index (SEARCH) or the storage-index (STORAGE)

Examples
// Refresh repository indices
repo.refresh();
// Refresh repository search index
repo.refresh('SEARCH');

setActiveVersion(params) → {boolean}

This function sets the active version of a node.

Parameters:
Name Type Description
params object

JSON parameters.

Properties
Name Type Description
key string

Path or ID of the node.

versionId string

Version to set as active.

Returns:

True if deleted, false otherwise.

Type
boolean

setChildOrder(params) → {object}

Set node's children order

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Description
key string

node's path or id

childOrder string

children order

Returns:

updated node

Type
object

setRootPermissions(params) → {object}

Set the root node permissions and inherit.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Description
_permissions object

the permission json

_inheritsPermissions object <optional>

true if the permissions should be inherited to children

Returns:

Updated root-node as JSON.

Type
object
Example
var nodeLib = require('/lib/xp/node');

// Connect to repo
var repo = nodeLib.connect({
    repoId: "com.enonic.cms.default",
    branch: "master"
});


// Update root-permissions
var result1 = repo.setRootPermissions({
    _permissions: [
        {
            "principal": "role:system.admin",
            "allow": [
                "READ",
                "CREATE",
                "MODIFY",
                "DELETE",
                "PUBLISH",
                "READ_PERMISSIONS",
                "WRITE_PERMISSIONS"
            ],
            "deny": []
        }
    ],
    _inheritsPermissions: true
});

log.info("Modified root node with inheritsPermissions = [%s], permissions: %s", result1._inheritsPermissions,
    JSON.stringify(result1._permissions, null, 4));