Client SDKs

JavaScript Client

Updated: December 6, 2016 Page Information Edit on GitHub

Client Library for Nuxeo API

Jenkins npm version npm downloads Dependency Status devDependency Status

The Nuxeo JavaScript Client is a JavaScript client library for the Nuxeo Automation and REST API. The library can work in a browser, or in Node.js, using the same API.

This is an on-going project, supported by Nuxeo.

Nuxeo Platform Dependency

The JS Client is compliant with all Nuxeo versions as of LTS 2015.

Getting Started

Installation

Node.js Applications

After installing Node.js, use npm to install the nuxeo package:

$ npm install nuxeo
Node.js v6 LTS (Boron)
var Nuxeo = require('nuxeo');
var nuxeo = new Nuxeo({ ... });
Node.js v4 LTS (Argon)
var Nuxeo = require('nuxeo/es5');
var nuxeo = new Nuxeo({ ... });

Bower Powered Applications

The nuxeo client can be also installed through bower:

$ bower install nuxeo --save

When added to your page, Nuxeo is available as a global variable.

var nuxeo = new Nuxeo({ ... });

Angular Applications

After adding nuxeo through Bower, you can easily create a service that will return a client:

...
.service('nuxeo', function() {
  return new Nuxeo({
    baseURL: 'http://localhost:8080/nuxeo/',
    auth: {
      method: 'basic',
      username: 'Administrator',
      password: 'Administrator'
    }
  });
})
...

To notify Angular to update the UI when a Nuxeo promise has resolved, you can either wrap Nuxeo promises in $q.when() or, the preferred way, configure the Promise library class to be $q.

// wrap promises
...
$q.when(nuxeo.request('/path/').get()).then(function(res) {
  $scope.res = res;
});
// use $q as the Promise library class
...
.service('nuxeo', function($q) {
  Nuxeo.promiseLibrary($q);
  return new Nuxeo({
    baseURL: 'http://localhost:8080/nuxeo/',
    auth: {
      method: 'basic',
      username: 'Administrator',
      password: 'Administrator'
    }
  });
})
...

React Applications

After adding nuxeo through npm to your application, to make it sure that it will work on most browsers you must require nuxeo differently according to your build system.

If your build transpiles external libraries from ES6 to ES5:

var Nuxeo = require('nuxeo');

If your build does not (such as create-react-app):

var Nuxeo = require('nuxeo/es5');

Documentation

Check out the API documentation.

Quick Start

This quick start guide will show how to do basics operations using the client.

Authentication

The authentication method to be used is defined when creating a client:

var nuxeo = new Nuxeo({
  auth: {
    method: ...,
    ...
  }
});

The client supports different authentication methods matching the ones available on the Nuxeo Platform.

Basic Authentication

The simplest one allowing to authenticate with a username and password.

var nuxeo = new Nuxeo({
  auth: {
    method: 'basic',
    username: 'Administrator',
    password: 'Administrator'
  }
});

Portal Authenticaton

If the Portal Authentication is configured on the Nuxeo Platform, you can authenticate with the portal method.

var nuxeo = new Nuxeo({
  auth: {
    method: 'portal',
    username: 'joe',
    secret: 'shared-secret-from-server'
  }
});

Token Authentication

To authenticate through a token from the Nuxeo Server:

var nuxeo = new Nuxeo({
  auth: {
    method: 'token',
    token: 'a-token'
  }
});

There is a utility method Nuxeo#requestAuthenticationToken to retrieve a token from a Nuxeo Server using the configured authentication method. For instance, a typical flow would be:

var nuxeo = new Nuxeo({
  auth: {
    method: 'basic',
    username: 'Administrator',
    password: 'Administrator'
  }
});

nuxeo.requestAuthenticationToken('My App', deviceUID, deviceName, 'rw')
  .then(function(token) {
    nuxeo = new Nuxeo({
      auth: {
        method: 'token',
        token: token
      }
    });

    // do something with the new `nuxeo` client using token authentication
    // store the token, and next time you need to create a client, use it
  })
  .catch(function(err) {
    throw err;
  });

OAuth2 Authorization and Bearer Token Authentication

Since Nuxeo Platform 9.2, you can use OAuth2 authorization through the JS client.

For more information on OAuth2 server side, see Using OAuth2.

Assuming you already have an access token, you can configure the client:

var nuxeo = new Nuxeo({
  auth: {
    method: 'bearerToken',
    token: access_token,
    clientId: 'my-app' // optional OAuth2 client ID to refresh the access token
  }
});

The bearertoken method supports the token being a simple string (an access token) or a full token object such as:

{
  "access_token":"H8dXDdEW9U2jJnFDh6lJJ74AHRzCyG4D",
  "token_type":"bearer",
  "expires_in":3600,
  "refresh_token":"Amz8JlyglhGWDmYHMYS5EnTTFUFAwZLiHG4aqQDfkwUNunSMpTTSFUmvprX3WdSF"
}

If the token is a full token object (ie. with a refresh_token key) and a clientId is configured on the auth object, the client will try automatically to refresh the access token if it's expired.

OAuth2 Flow

A typical OAuth2 flow with the Nuxeo Platform would be:

Retrieving Authorization Code

Generate a "log in" link to be used in a browser, such as:

http://localhost:8080/nuxeo/oauth2/authorize?client_id=CLIENT_ID&response_type=code&redirect_uri=REDIRECT_URI

The user sees the login page then, after being logged in, the authorization prompt for the application.

If the user grants access, the Nuxeo Platform redirects the user back to the application:

http://localhost:8000/authorize?code=AUTH_CODE

Retrieving Access Token

The client exchanges the authorization code for an access token:

POST http://localhost:8080/nuxeo/oauth2/token
  grant_type=authorization_code
  code=AUTH_CODE
  redirect_uri=REDIRECT_URI
  client_id=CLIENT_ID

The Nuxeo Platform replies with an access token:

{
  "access_token":"H8dXDdEW9U2jJnFDh6lJJ74AHRzCyG4D",
  "token_type":"bearer",
  "expires_in":3600,
  "refresh_token":"Amz8JlyglhGWDmYHMYS5EnTTFUFAwZLiHG4aqQDfkwUNunSMpTTSFUmvprX3WdSF"
}

There are some utility methods on the client to help you with this flow:

Nuxeo.oauth2.getAuthorizationURL(baseURL, clientId[, params])

Returns the OAuth2 authorization URL for the given baseURL and clientId.

var authorizationURL = Nuxeo.oauth2.getAuthorizationURL('http://localhost:8080/nuxeo', 'my-app', {
  state: 'xyz',
  redirect_uri: 'http://localhost:8000/authorize',
});
console.log(authorizationURL); // http://localhost:8080/nuxeo/oauth2/authorize?client_id=my-app&response_type=code&state=xyz&redirect_uri=http://localhost:8000/authorize

Nuxeo.oauth2.fetchAccessToken(baseURL, clientId, code[, params])

Fetches an OAuth2 access token for the given baseURL, clientId and code.

var code = ...
Nuxeo.oauth2.fetchAccessToken('http://localhost:8080/nuxeo', 'my-app', code, {
  redirect_uri: 'http://localhost:8000/authorize',
}).then(function(token) {
  // do something with the access token
  var nuxeo = new Nuxeo({
    auth: {
      method: 'bearerToken',
      token: token
    }
  });
});

Nuxeo.oauth2.refreshAccessToken(baseURL, clientId, refreshToken[, params])

Manually refresh an access token for the given baseURL, clientId and refreshToken.

var refreshToken = ...
Nuxeo.oauth2.refreshAccessToken('http://localhost:8080/nuxeo', 'my-app', refreshToken)
  .then(function(token) {
    console.log(token); // refreshed access token
});

Creating a Client

var nuxeo = new Nuxeo({
  auth: {
    method: 'basic',
    username: 'Administrator',
    password: 'Administrator'
  }
});

To connect to a different Nuxeo Platform Instance, you can use the following:

var nuxeo = new Nuxeo({
  baseURL: 'http://demo.nuxeo.com/nuxeo/',
  auth: {
    method: 'basic',
    username: 'Administrator',
    password: 'Administrator'
  }
});

Promise Based Calls

All API calls made on the server return a Promise object.

nuxeo.operation('Document.GetChildren')
  .input('/')
  .execute()
  .then(function(docs) {
    // work with docs
  })
  .catch(function(error) {
    // something went wrong
    throw error;
  });

When something went wrong, the error is an Error object with a response field containing the whole response.

Connecting to a Nuxeo Server

After creating a Client, you can connect to a Nuxeo Server by using the connect method. This method returns a Promise which is resolved with the connected client.

var nuxeo = new Nuxeo({ ... });
nuxeo.connect()
  .then(function(client){
    // client.connected === true
    // client === nuxeo
    console.log('Connected OK!');
  })
  .catch(function(error) {
    // wrong credentials / auth method / ...
    throw error;
  });

Current User

The connect method fills the user property of the client. user is a full User object.

var nuxeo = new Nuxeo({ ... });
nuxeo.connect()
  .then(function(client){
    // client.user.id === 'Administrator'
    console.log(client.user);
  })
  .catch(function(error) {
    // wrong credentials / auth method / ...
    throw error;
  });

Nuxeo Server version

The connect method fills the nuxeoVersion property of the client.

var nuxeo = new Nuxeo({ ... });
nuxeo.connect()
  .then(function(client){
    // client.nuxeoVersion === '8.10'
    console.log(client.nuxeoVersion);
  })
  .catch(function(error) {
    // wrong credentials / auth method / ...
    throw error;
  });

Some constants are available in the Nuxeo object for supported LTS versions:

Nuxeo.VERSIONS.LTS_2015 === '7.10';
Nuxeo.VERSIONS.LTS_2016 === '8.10';

You can use them to easily make different calls according to the target version:

...
if (nuxeo.nuxeoVersion < Nuxeo.VERSIONS.LTS_2016) {
  // do something on versions before LTS 2016
} else {
  // do something else
}
...

Operation

Operation object allows you to execute an operation (or operation chain).

See the Operation documentation.

Samples

Call an operation to create a new folder in the Root document

nuxeo.operation('Document.Create')
  .params({
    type: 'Folder',
    name: 'My Folder',
    properties: 'dc:title=My Folder \ndc:description=A Simple Folder'
  })
  .input('/')
  .execute()
  .then(function(doc) {
    console.log('Created ' + doc.title + ' folder');
  })
  .catch(function(error) {
    throw error;
  });

Request

The Request object allows you to call the Nuxeo REST API.

See the Request documentation.

Samples

Fetch the Administrator user

nuxeo.request('user/Administrator')
  .get()
  .then(function(user) {
    console.log(user);
  })
  .catch(function(error) {
    throw error;
  });

Fetch the whole list of Natures

nuxeo.request('directory/nature')
  .get()
  .then(function(data) {
    console.log(JSON.stringify(data.entries, null, 2))
  })
  .catch(function(error) {
    throw error
  });

Repository

The Repository object allows you to work with document.

See the Repository documentation.

Samples

Create a Repository object

var defaultRepository = nuxeo.repository(); // 'default' repository
...
var testRepository = nuxeo.repository('test'); // 'test' repository
...

Fetch the Root document

nuxeo.repository().fetch('/')
  .then(function(doc) {
    console.log(doc);
  })
  .catch(function(error) {
    throw error;
  });

Create a new folder

var newFolder = {
  'entity-type': 'document',
  name: 'a-folder',
  type: 'Folder',
  properties: {
    'dc:title': 'foo'
  }
};
nuxeo.repository()
  .create('/', newFolder)
  .then(function(doc) {
    console.log(doc);
  })
  .catch(function(error) {
    throw error;
  });

Delete a document

nuxeo.repository()
  .delete('/a-folder')
  .then(function(res) {
    // res.status === 204
  });

Document

Repository object returns and works with Document objects. Document objects exposes a simpler API to work with a document.

See the Document documentation.

Samples

Retrieve a Document object

nuxeo.repository()
  .fetch('/')
  .then(function(doc) {
    // doc instanceof Nuxeo.Document === true
  })
  .catch(function(error) {
    throw error;
  });

Set a document property

doc.set({ 'dc:title': 'foo' });

Get a document property

doc.get('dc:title');

Save an updated document

nuxeo.repository()
  .fetch('/')
  .then(function(doc) {
    // doc.title !== 'foo'
    doc.set({ 'dc:title': 'foo' });
    return doc.save();
  })
  .then(function(doc) {
    // doc.title === 'foo'
  })
  .catch(function(error) {
    throw error;
  });

Fetch the main Blob of a document

doc.fetchBlob()
  .then(function(res) {
    // in the browser, use res.blob() to work with the converted PDF
    // in Node.js, use res.body
  });

Convert a document main Blob to PDF

doc.convert({ format: 'pdf' })
  .then(function(res) {
    // in the browser, use res.blob() to work with the converted PDF
    // in Node.js, use res.body
  });

Fetch the 'thumbnail' rendition

doc.fetchRendition('thumbnail')
  .then(function(res) {
    // in the browser, use res.blob() to work with the rendition
    // in Node.js, use res.body
  });

Start a workflow

doc.startWorkflow('SerialDocumentReview')
  .then(function(workflow) {
    // workflow instance of Nuxeo.Workflow
  });

Complete a workflow task

workflow.fetchTasks()
  .then(function(tasks) {
    return tasks[0];
  })
  .then(function(tasks) {
    task.variable('participants', ['user:Administrator'])
      .variable('assignees', ['user:Administrator'])
      .variable('end_date', '2011-10-23T12:00:00.00Z');
    return task.complete('start_review', { comment: 'a comment' });
  })
  .then(function(task) {
    // task.state === 'ended'
  })

BatchUpload

The BatchUpload object allows you to upload blobs to a Nuxeo Platform instance, and use them as operation input or as document property value.

See the BatchUpload documentation.

Samples

Create a Nuxeo.Blob to be uploaded

// on the browser, assuming you have a File object 'file'
var blob = new Nuxeo.Blob({ content: file });
// the name, mimeType and size will be extracted from the file object itself, you can still override them.
...
// on Node.js, assuming you have a Stream 'file'
var blob = new Nuxeo.Blob({ content: file, name: 'foo.txt', mimeType: 'plain/text', size: 10 })

Upload a blob

nuxeo.batchUpload()
  .upload(blob)
  .then(function(res) {
    // res.blob instanceof Nuxeo.BatchBlob
    console.log(res.blob);
  })
  .catch(function(error) {
    throw error;
  });

Attach an uploaded blob to a document

nuxeo.batchUpload()
  .upload(blob)
  .then(function(res) {
    return nuxeo.operation('Blob.AttachOnDocument')
      .param('document', '/a-file')
      .input(res.blob)
      .execute();
  })
  .then(function() {
    return nuxeo.repository().fetch('/a-file', { schemas: ['dublincore', 'file']});
  })
  .then(function(doc) {
    console.log(doc.get('file:content'));
  })
  .catch(function(error) {
    throw error;
  });

Users

The Users object allows you to work with users.

See the Users and User documentation.

Samples

Fetch an user

nuxeo.users()
  .fetch('Administrator')
  .then(function(user) {
    // user.id === 'Administrator'
  });

Create a new user

var newUser = {
  properties: {
    username: 'leela',
    firstName: 'Leela',
    company: 'Futurama',
    email: '[email protected]'
  },
};
nuxeo.users()
  .create(newUser)
  .then(function(user) {
    // user.id === 'leela'
  });

Delete an user

nuxeo.users()
  .delete('leela').then(function(res) {
    // res.status === 204
  });

Groups

The Groups object allows you to work with groups.

See the Groups and Group documentation.

Samples

Fetch a group

nuxeo.groups().fetch('administrators')
  .then(function(group) {
    // group.groupname === 'administrators'
  });

Create a new group

var newGroup = {
  groupname: 'foo',
  grouplabel: 'Foo'
};
nuxeo.groups()
  .create(newGroup)
  .then(function(group) {
    // group.groupname === 'foo';
  });

Delete a group

nuxeo.groups()
  .delete('foo').then(function(res) {
    // res.status === 204
  });

Directory

The Directory object allows you to work with directories.

See the Directory and DirectoryEntry documentation.

Samples

Fetch all entries of a directory

nuxeo.directory('nature')
  .fetchAll()
  .then(function(entries) {
    // entries instance of Array
  });

Fetch a given directory entry

nuxeo.directory('nature')
  .fetch('article')
  .then(function(entry) {
    // entry.directoryName === 'nature'
    // entry.properties.id === 'article'
  });

Create a new directory entry

var newEntry = {
  properties: {
    id: 'foo',
    label: 'Foo'
  },
};
nuxeo.directory('nature')
  .create(newEntry)
  .then(function(entry) {
    // entry.directoryName === 'nature'
    // entry.properties.id === 'foo'
  });

Delete a directory entry

nuxeo.directory('nature')
 .delete('foo')
 .then(function(res) {
   // res.status === 204
 });

Contributing

See our contribution documentation.

Requirements

Setup

Install Node.js and then use npm to install all the required libraries:

$ git clone https://github.com/nuxeo/nuxeo-js-client
$ cd nuxeo-js-client
$ npm install

Test

A Nuxeo Platform instance needs to be running on http://localhost:8080/nuxeo for the tests to be run.

Tests can be launched on Node.js with:

$ gulp test:node

For testing the browser client (tests are run on Firefox and Chrome by default):

$ gulp test:browser

To run both Node.js and browser tests:

$ gulp test

Reporting Issues

You can follow the developments in the Nuxeo JS Client project of our JIRA bug tracker: https://jira.nuxeo.com/browse/NXJS.

You can report issues on answers.nuxeo.com.

License

Apache License 2.0 Copyright (c) Nuxeo SA

About Nuxeo

Nuxeo dramatically improves how content-based applications are built, managed and deployed, making customers more agile, innovative and successful. Nuxeo provides a next generation, enterprise ready platform for building traditional and cutting-edge content oriented applications. Combining a powerful application development environment with SaaS-based tools and a modular architecture, the Nuxeo Platform and Products provide clear business value to some of the most recognizable brands including Verizon, Electronic Arts, Sharp, FICO, the U.S. Navy, and Boeing. Nuxeo is headquartered in New York and Paris. More information is available at www.nuxeo.com.

 


8 months ago Thomas Roger Review JavaScript client doc
8 months ago Andrew Goodricke Add content-review-lts2016 to labels
8 months ago Kevin Leturc NXP-19481: Update MarkLogic page to detail how to configure range element indexes
2 years ago Manon Lumeau 14
2 years ago Solen Guitter 13
2 years ago Anahide Tchertchian 12
2 years ago Bertrand Chauvin 11 | Added link to AngularJS doc
3 years ago Solen Guitter 10 | Add link to latest blog post about JavaScript client
3 years ago Solen Guitter 9 | Display readme from GitHub
3 years ago Solen Guitter 8 | Update related pages
3 years ago Alain Escaffre 7
3 years ago Solen Guitter 6
3 years ago Alain Escaffre 5
3 years ago Solen Guitter 4
3 years ago Alain Escaffre 3
3 years ago Alain Escaffre 1
3 years ago Alain Escaffre 2
History: Created by Alain Escaffre