lib/xp/content

Functions to find and manipulate content.

Example
var contentLib = require('/lib/xp/content');

Methods

(static) create(params) → {object}

This function creates a content.

The parameter name is optional, but if it is not set then displayName must be specified. When name is not set, the system will auto-generate a name based on the displayName, by lower-casing and replacing certain characters. If there is already a content with the auto-generated name, a suffix will be added to the name in order to make it unique.

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 Default Description
name string <optional>

Name of content.

parentPath string

Path to place content under.

displayName string <optional>

Display name. Default is same as name.

requireValid boolean <optional>
true

The content has to be valid, according to the content type, to be created. If requireValid=true and the content is not strictly valid, an error will be thrown.

contentType string

Content type to use.

language string <optional>

The language tag representing the content’s locale.

branch string <optional>

Set by portal, depending on context, to either draft or master. May be overridden, but this is not recommended. Default is the current branch set in portal.

data object

Actual content data.

x object <optional>

eXtra data to use.

Returns:

Content created as JSON.

Type
object
Examples
// Creates a content.
var result1 = contentLib.create({
    name: 'mycontent',
    parentPath: '/a/b',
    displayName: 'My Content',
    branch: 'draft',
    contentType: 'test:myContentType',
    language: 'es',
    data: {
        a: 1,
        b: 2,
        c: ['1', '2'],
        d: {
            e: {
                f: 3.6,
                g: true
            }
        }
    },
    x: {
        "com-enonic-myapplication": {
            myschema: {
                a: 1
            }
        }
    },
    "attachments": {}
});

log.info('Content created with id ' + result1._id);
// Check if content already exists.
try {
    var result2 = contentLib.create({
        name: 'mycontent',
        parentPath: '/a/b',
        displayName: 'My Content',
        branch: 'draft',
        contentType: 'test:myContentType',
        data: {}
    });

    log.info('Content created with id ' + result2._id);

} catch (e) {
    if (e.code == 'contentAlreadyExists') {
        log.error('There is already a content with that name');
    } else {
        log.error('Unexpected error: ' + e.message);
    }
}
// Content created.
var expected = {
    "_id": "123456",
    "_name": "mycontent",
    "_path": "/a/b/mycontent",
    "creator": "user:system:anonymous",
    "createdTime": "1975-01-08T00:00:00Z",
    "type": "test:myContentType",
    "displayName": "My Content",
    "hasChildren": false,
    "language": "es",
    "valid": false,
    "data": {
        "a": 1,
        "b": 2,
        "c": [
            "1",
            "2"
        ],
        "d": {
            "e": {
                "f": 3.6,
                "g": true
            }
        }
    },
    "x": {
        "com-enonic-myapplication": {
            "myschema": {
                "a": 1
            }
        }
    },
    "page": {},
    "attachments": {}
};

(static) createMedia(params) → {object}

Creates a media content.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Default Description
name string <optional>

Name of content.

parentPath string <optional>
/

Path to place content under.

mimeType string <optional>

Mime-type of the data.

focalX number <optional>

Focal point for X axis (if it's an image).

focalY number <optional>

Focal point for Y axis (if it's an image).

branch string <optional>

Set by portal, depending on context, to either draft or master. May be overridden, but this is not recommended. Default is the current branch set in portal.

data

Data (as stream) to use.

Returns:

Returns the created media content.

Type
object
Examples
// Creates a media.
var result = contentLib.createMedia({
    name: 'mycontent',
    parentPath: '/a/b',
    mimeType: 'text/plain',
    branch: 'draft',
    data: stream
});
// Content created.
var expected = {
    "_id": "123456",
    "_name": "mycontent",
    "_path": "/a/b/mycontent",
    "creator": "user:system:anonymous",
    "createdTime": "1975-01-08T00:00:00Z",
    "type": "base:unstructured",
    "hasChildren": false,
    "valid": false,
    "data": {},
    "x": {},
    "page": {},
    "attachments": {}
};

(static) delete(params) → {boolean}

This function deletes a content.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Description
key string

Path or id to the content.

branch string <optional>

Set by portal, depending on context, to either draft or master. May be overridden, but this is not recommended. Default is the current branch set in portal.

Returns:

True if deleted, false otherwise.

Type
boolean
Example
// Deletes a content by path.
var result = contentLib.delete({
    key: '/features/js-libraries/mycontent',
    branch: 'draft'
});

if (result) {
    log.info('Content deleted');
} else {
    log.info('Content was not found');
}

(static) get(params) → {object}

This function fetches a content.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Description
key string

Path or id to the content.

branch string <optional>

Set by portal, depending on context, to either draft or master. May be overridden, but this is not recommended. Default is the current branch set in portal.

Returns:

The content (as JSON) fetched from the repository.

Type
object
Examples
// Gets a single content by path.
var result = contentLib.get({
    key: '/path/to/mycontent',
    branch: 'draft'
});

if (result) {
    log.info('Display Name = ' + result.displayName);
} else {
    log.info('Content was not found');
}
// Content as it is returned.
var expected = {
    "_id": "123456",
    "_name": "mycontent",
    "_path": "/path/to/mycontent",
    "creator": "user:system:admin",
    "modifier": "user:system:admin",
    "createdTime": "1970-01-01T00:00:00Z",
    "modifiedTime": "1970-01-01T00:00:00Z",
    "type": "base:unstructured",
    "displayName": "My Content",
    "hasChildren": false,
    "language": "en",
    "valid": true,
    "data": {
        "myfield": "Hello World"
    },
    "x": {},
    "page": {},
    "attachments": {
        "logo.png": {
            "name": "logo.png",
            "label": "small",
            "size": 6789,
            "mimeType": "image/png"
        },
        "document.pdf": {
            "name": "document.pdf",
            "size": 12345,
            "mimeType": "application/pdf"
        }
    }
};

(static) getAttachments(key) → {object}

This function returns a content attachments.

Parameters:
Name Type Description
key string

Path or id to the content.

Returns:

An object with all the attachments that belong to the content, where the key is the attachment name. Or null if the content cannot be found.

Type
object
Examples
// Gets all attachments for a content.
var result = contentLib.getAttachments('/features/js-libraries/mycontent');

if (!result) {
    log.info('Content was not found');
} else {
    log.info('Attachments as JSON %s', result);
}
// Attachments returned.
var expected = {
    "logo.png": {
        "name": "logo.png",
        "label": "small",
        "size": 6789,
        "mimeType": "image/png"
    },
    "document.pdf": {
        "name": "document.pdf",
        "size": 12345,
        "mimeType": "application/pdf"
    }
};

(static) getAttachmentStream(params) → {*}

This function returns a data-stream for the specified content attachment.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Description
key string

Path or id to the content.

name string

Attachment name.

Returns:

Stream of the attachment data.

Type
*
Example
// Get stream for attachment.
var stream = contentLib.getAttachmentStream({
    key: '/a/b/mycontent',
    name: 'document.pdf'
});

(static) getChildren(params) → {boolean}

This function fetches children of a content.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Default Description
key string

Path or id to the parent content.

start number <optional>
0

Start index (used for paging).

count number <optional>
10

Number of contents to fetch.

sort string <optional>

Sorting expression.

branch string <optional>

Set by portal, depending on context, to either draft or master. May be overridden, but this is not recommended. Default is the current branch set in portal.

Returns:

Result (of content) fetched from the repository.

Type
boolean
Examples
// Returns the children of specified path.
var result = contentLib.getChildren({
    key: '/path/to',
    start: 0,
    count: 2,
    sort: '_modifiedTime ASC',
    branch: 'draft'
});

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

for (var i = 0; i < result.hits.length; i++) {
    var content = result.hits[i];
    log.info('Content ' + content._name + ' loaded');
}
// Result set returned.
var expected = {
    "total": 20,
    "count": 2,
    "hits": [
        {
            "_id": "id1",
            "_name": "name1",
            "_path": "/a/b/name1",
            "creator": "user:system:admin",
            "modifier": "user:system:admin",
            "createdTime": "1970-01-01T00:00:00Z",
            "modifiedTime": "1970-01-01T00:00:00Z",
            "type": "base:unstructured",
            "displayName": "My Content 1",
            "hasChildren": false,
            "valid": false,
            "data": {},
            "x": {},
            "page": {},
            "attachments": {}
        },
        {
            "_id": "id2",
            "_name": "name2",
            "_path": "/a/b/name2",
            "creator": "user:system:admin",
            "modifier": "user:system:admin",
            "createdTime": "1970-01-01T00:00:00Z",
            "modifiedTime": "1970-01-01T00:00:00Z",
            "type": "base:unstructured",
            "displayName": "My Content 2",
            "hasChildren": false,
            "valid": false,
            "data": {},
            "x": {},
            "page": {},
            "attachments": {}
        }
    ]
};

(static) getPermissions(params) → {object}

Gets permissions on a content.

Parameters:
Name Type Description
params object

JSON parameters.

Properties
Name Type Description
key string

Path or id of the content.

Returns:

Content permissions.

Type
object
Examples
// Return permissions for content by path.
var result = contentLib.getPermissions({
    key: '/features/js-libraries/mycontent'
});

if (result) {
    log.info('Content inherits permissions: ' + result.inheritPermissions);
} else {
    log.info('Content not found');
}
// Permissions returned.
var expected = {
    "inheritsPermissions": false,
    "permissions": [
        {
            "principal": "user:system:anonymous",
            "allow": [
                "READ"
            ],
            "deny": []
        }
    ]
};

(static) getSite(params) → {object}

This function returns the parent site of a content.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Description
key string

Path or id to the content.

Returns:

The current site as JSON.

Type
object
Examples
var result = contentLib.getSite({
    key: '/path/to/mycontent'
});
log.info('Site name = %s', result._name);
// Site data returned.
var expected = {
    "_id": "100123",
    "_name": "my-content",
    "_path": "/my-content",
    "type": "base:unstructured",
    "hasChildren": false,
    "valid": false,
    "data": {
        "siteConfig": {
            "applicationKey": "myapplication",
            "config": {
                "Field": 42
            }
        }
    },
    "x": {},
    "page": {},
    "attachments": {}
};

(static) getSiteConfig(params) → {object}

This function returns the site configuration for this app in the parent site of a content.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Description
key string

Path or id to the content.

applicationKey string

Application key.

Returns:

The site configuration for current application as JSON.

Type
object
Examples
var result = contentLib.getSiteConfig({
    key: '/path/to/mycontent',
    applicationKey: app.name
});
log.info('Field value for the site config = %s', result.Field);
// Site config returned.
var expected = {
    "Field": 42
};

(static) modify(params) → {object}

This function modifies a content.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Default Description
key string

Path or id to the content.

editor function

Editor callback function.

branch string <optional>

Set by portal, depending on context, to either draft or master. May be overridden, but this is not recommended. Default is the current branch set in portal.

requireValid boolean <optional>
true

The content has to be valid, according to the content type, to be updated. If requireValid=true and the content is not strictly valid, an error will be thrown.

Returns:

Modified content as JSON.

Type
object
Examples
// Editor to call for content.
function editor(c) {
    c.displayName = 'Modified';
    c.language = 'en';
    c.data.myCheckbox = false;
    c.data["myTime"] = "11:00";
    return c;
}

// Modify content by path
var result = contentLib.modify({
    key: '/a/b/mycontent',
    editor: editor
});

if (result) {
    log.info('Content modified. New title is ' + result.displayName);
} else {
    log.info('Content not found');
}
// Content modified.
var expected = {
    "_id": "123456",
    "_name": "mycontent",
    "_path": "/path/to/mycontent",
    "creator": "user:system:admin",
    "modifier": "user:system:admin",
    "createdTime": "1970-01-01T00:00:00Z",
    "modifiedTime": "1970-01-01T00:00:00Z",
    "type": "base:unstructured",
    "displayName": "Modified",
    "hasChildren": false,
    "language": "en",
    "valid": true,
    "data": {
        "myfield": "Hello World",
        "myCheckbox": "false",
        "myTime": "11:00"
    },
    "x": {},
    "page": {},
    "attachments": {
        "logo.png": {
            "name": "logo.png",
            "label": "small",
            "size": 6789,
            "mimeType": "image/png"
        },
        "document.pdf": {
            "name": "document.pdf",
            "size": 12345,
            "mimeType": "application/pdf"
        }
    }
};

(static) move(params) → {boolean}

Rename a content or move it to a new path.

Parameters:
Name Type Description
params object

JSON with the parameters.

Properties
Name Type Attributes Description
source string

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

target string

New path or name for the content. 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 content.

branch string <optional>

Set by portal, depending on context, to either draft or master. May be overridden, but this is not recommended. Default is the current branch set in portal.

Returns:

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

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

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

log.info('New path: ' + content2._path); // '/my-site/folder/my-content-name'
// Move content by id to new path. New parent path, keeps same name.
var content3 = contentLib.move({
    source: '8d933461-ede7-4dd5-80da-cb7de0cd7bba',
    target: '/my-site/folder/'
});

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

log.info('New path: ' + content4._path); // '/my-site/folder/new-name'
// Handle error if target already exists.
try {
    var content5 = contentLib.move({
        source: '/my-site/my-content-name',
        target: '/my-site/folder/existing-content'
    });

} catch (e) {
    if (e.code == 'contentAlreadyExists') {
        log.error('There is already a content in the target specified');
    } else {
        log.error('Unexpected error: ' + e.message);
    }
}

(static) publish(params) → {object}

This function publishes content to a branch.

Parameters:
Name Type Description
params object

JSON with the parameters.

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

List of all content keys(path or id) that should be published.

sourceBranch string

The branch where the content to be published is stored.

targetBranch string

The branch to which the content should be published. Technically, publishing is just a move from one branch to another, and publishing user content from master to draft is therefore also valid usage of this function, which may be practical if user input to a web-page is stored on master.

includeChildren boolean <optional>
true

Whether all children should be included when publishing content.

includeDependencies boolean <optional>
true

Whether all related content should be included when publishing content.

Returns:

Status of the publish operation in JSON.

Type
object
Examples
// Publish content by path or key
var result = contentLib.publish({
    keys: ['/mysite/somepage', '79e21db0-5b43-45ce-b58c-6e1c420b22bd'],
    sourceBranch: 'draft',
    targetBranch: 'master',
    includeChildren: true,
    includeDependencies: false
});

if (result) {
    log.info('Pushed ' + result.pushedContents.length + " content.");
    log.info('Deleted ' + result.deletedContents.length + " content.");
    log.info('Content that failed operation: ' + result.failedContents.length);
} else {
    log.info('Operation failed.');
}
// Content published.
var expected = {
    "pushedContents": [
        "d7ad428b-eae2-4ff1-9427-e8e8a8a3ab23",
        "9f5b0db0-38f9-4e81-b92e-116f25476b1c",
        "e1f57280-d672-4cd8-b674-98e26e5b69ae"
    ],
    "deletedContents": [
        "45d67001-7f2b-4093-99ae-639be9fdd1f6"
    ],
    "failedContents": [
        "79e21db0-5b43-45ce-b58c-6e1c420b22bd"
    ]
};

(static) query(params) → {boolean}

This command queries content.

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.

sort string <optional>

Sorting expression.

aggregations string <optional>

Aggregations expression.

contentTypes Array.<string> <optional>

Content types to filter on.

branch string <optional>

Set by portal, depending on context, to either draft or master. May be overridden, but this is not recommended. Default is the current branch set in portal.

Returns:

Result of query.

Type
boolean
Examples
// Query content using aggregations.
var result = contentLib.query({
    start: 0,
    count: 2,
    sort: "modifiedTime DESC, geoDistance('data.location', '59.91,10.75')",
    query: "data.city = 'Oslo' AND fulltext('data.description', 'garden', 'AND') ",
    branch: "draft",
    contentTypes: [
        app.name + ":house",
        app.name + ":apartment"
    ],
    aggregations: {
        floors: {
            terms: {
                field: "data.number_floor",
                order: "_count asc"
            },
            aggregations: {
                prices: {
                    histogram: {
                        field: "data.price",
                        interval: 1000000,
                        extendedBoundMin: 1000000,
                        extendedBoundMax: 3000000,
                        minDocCount: 0,
                        order: "_key desc"
                    }
                }
            }
        },
        by_month: {
            dateHistogram: {
                field: "data.publish_date",
                interval: "1M",
                minDocCount: 0,
                format: "MM-yyyy"
            }
        },
        price_ranges: {
            range: {
                field: "data.price",
                ranges: [
                    {to: 2000000},
                    {from: 2000000, to: 3000000},
                    {from: 3000000}
                ]
            }
        },
        my_date_range: {
            dateRange: {
                field: "data.publish_date",
                format: "MM-yyyy",
                ranges: [
                    {to: "now-10M/M"},
                    {from: "now-10M/M"}
                ]
            }
        },
        price_stats: {
            stats: {
                field: "data.price"
            }
        }
    }
});

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

for (var i = 0; i < result.hits.length; i++) {
    var content = result.hits[i];
    log.info('Content ' + content._name + ' found');
}
// Result set returned.
var expected = {
    "total": 20,
    "count": 2,
    "hits": [
        {
            "_id": "id1",
            "_name": "name1",
            "_path": "/a/b/name1",
            "creator": "user:system:admin",
            "modifier": "user:system:admin",
            "createdTime": "1970-01-01T00:00:00Z",
            "modifiedTime": "1970-01-01T00:00:00Z",
            "type": "base:unstructured",
            "displayName": "My Content 1",
            "hasChildren": false,
            "valid": false,
            "data": {},
            "x": {},
            "page": {},
            "attachments": {}
        },
        {
            "_id": "id2",
            "_name": "name2",
            "_path": "/a/b/name2",
            "creator": "user:system:admin",
            "modifier": "user:system:admin",
            "createdTime": "1970-01-01T00:00:00Z",
            "modifiedTime": "1970-01-01T00:00:00Z",
            "type": "base:unstructured",
            "displayName": "My Content 2",
            "hasChildren": false,
            "valid": false,
            "data": {},
            "x": {},
            "page": {},
            "attachments": {}
        }
    ],
    "aggregations": {
        "genders": {
            "buckets": [
                {
                    "key": "male",
                    "docCount": 10
                },
                {
                    "key": "female",
                    "docCount": 12
                }
            ]
        },
        "by_month": {
            "buckets": [
                {
                    "key": "2014-01",
                    "docCount": 8
                },
                {
                    "key": "2014-02",
                    "docCount": 10
                },
                {
                    "key": "2014-03",
                    "docCount": 12
                }
            ]
        },
        "price_ranges": {
            "buckets": [
                {
                    "key": "a",
                    "docCount": 2,
                    "to": 50
                },
                {
                    "key": "b",
                    "docCount": 4,
                    "from": 50,
                    "to": 100
                },
                {
                    "key": "c",
                    "docCount": 4,
                    "from": 100
                }
            ]
        },
        "my_date_range": {
            "buckets": [
                {
                    "docCount": 2,
                    "from": "2014-09-01T00:00:00Z"
                },
                {
                    "docCount": 5,
                    "from": "2014-10-01T00:00:00Z",
                    "to": "2014-09-01T00:00:00Z"
                },
                {
                    "docCount": 7,
                    "to": "2014-11-01T00:00:00Z"
                }
            ]
        },
        "item_count": {
            "count": 5,
            "min": 1,
            "max": 5,
            "avg": 3,
            "sum": 15
        }
    }
};

(static) setPermissions(params) → {boolean}

Sets permissions on a content.

Parameters:
Name Type Description
params object

JSON parameters.

Properties
Name Type Attributes Description
key string

Path or id of the content.

inheritPermissions boolean <optional>

Set to true if the content must inherit permissions. Default to false.

overwriteChildPermissions boolean <optional>

Set to true to overwrite child permissions. Default to false.

permissions array <optional>

Array of permissions.

Properties
Name Type Description
principal string

Principal key.

allow array

Allowed permissions.

deny array

Denied permissions.

Returns:

True if successful, false otherwise.

Type
boolean
Example
// Set permissions for content by path.
var flag = contentLib.setPermissions({
    key: '/features/js-libraries/mycontent',
    inheritPermissions: false,
    overwriteChildPermissions: true,
    permissions: [{
        principal: 'user:system:anonymous',
        allow: ['READ'],
        deny: ['DELETE']
    }]
});

if (flag) {
    log.info('Permissions set');
} else {
    log.info('Content not found');
}