MoodleWSClient

MoodleWSClient

A class representing a connection to a Moodle REST API. This class is exported as the @maynoothuniversity/moodle-ws-client module.

Constructor

Fcnew MoodleWSClient(moodleBaseUrl, token, optionsopt)

Note that this constructor will throw a ValidationError if invalid parameters are passed.

See:
Parameters:
Name Type Attributes Description
moodleBaseUrl SecureUrl

the base URL of the Moodle site.

token MoodleToken

the token to authenticate with.

options Object <optional>
Name Type Attributes Default Description
acceptUntrustedTLSCert boolean <optional>
false

whether or not to accept TLS certificates that don't pass validation. Unless your Moodle server uses a self-signed certificate, don't set this to true!

timeout Duration <optional>
5000

the default timeout to use when making requests to the web service.

Throws:

A validation error is thrown when invalid parameters are passed.

Type
ValidationError

Methods

F(static) encodeWSArguments() → {PlainObject}

A function for converting JavaScript datastructures into parameters for submission to the Moodle web services API.

The function translates booleans to '0' and '1' automatically.

I.e. it would convert:

{
  criteria: [
    {
      key: 'email',
      value: '%%'
    },
    {
      key: 'deleted',
      value: false
    },
  ]
}

to:

{
  'criteria[0][key]': 'email',
  'criteria[0][value]': '%%',
  'criteria[1][key]': 'deleted',
  'criteria[1][value]': '0'
}
Throws:
  • A validation error is thrown if the first parameter is not an object.

    Type
    ValidationError
    • a type error is thrown if the datastrucure to be converted contains anything other than a number, a string, a boolean, an array, or a plain object.
    Type
    TypeError
Returns:
Type:
PlainObject

FapiUrl() → {SecureUrl}

Get the URL for the Moodle instance's REST API.

Returns:
Type:
SecureUrl

FmoodleUrl() → {SecureUrl}

Get the Moodle instance's base URL.

Returns:
Type:
SecureUrl

Fping() → {Object}

Test connectivity to the REST API. This function is implemented as a registered shortcut to the core_webservice_get_site_info web service function with the HTTP method GET and no arguments.

See:
Returns:
Type:
Object

FregisterShortcut(shortcut, wsFunctionName, method) → {MoodleWSClient}

Register a shortcut. This function creates functions with a given name that act as wrappers for the .submit() function with the given HTTP method web service function name.

Parameters:
Name Type Description
shortcut JsFunctionName

the name for the shortcut function.

wsFunctionName WsFunctionName

the name of the Moodle web service function this shortcut will invoke.

method HttpMethod

the HTTP method this shortcut function will invoke the Moodle web service with.

Returns:
Type:
MoodleWSClient

Returns a reference to self to facilitate function chaining.

Example
// create a .addUser() function which calls .submit() with the HTTP
// method POST and the web service function name core_user_create_users
myMoodle.registerShortcut('addUser', 'core_user_create_users', 'POST');

// use the .addUser function to create a user
let userDetails = {
    username: 'jbloggs',
    createpassword: true,
    firstname: 'Jane',
    lastname: 'Bloggs',
    email: 'jane.bloggs@uni.edu'
};
myMoodle.addUser({users: [userDetails]});
// equivalent to:
// myMoodle.submit('POST', 'core_user_create_users', {users: [userDetails]});

FregisterShortcuts(shortcuts) → {MoodleWSClient}

Register multiple shortcuts at once.

See:
Parameters:
Name Type Description
shortcuts PlainObject

a plain object mapping shortcut names to two-entry arrays of strings, the first being the Moodle web service function name, the second the HTTP method, e.g.:

{
  addUser: ['core_user_create_users ', 'POST'],
  deleteUser: ['core_user_delete_users ', 'DELETE']
}
Returns:
Type:
MoodleWSClient

Returns a reference to self to facilitate function chaining.

F(async) submit(method, wsFunctionName, wsParameters, optionsopt) → {PlainObject}

Submit a request to the Moodle REST API.

Parameters:
Name Type Attributes Default Description
method HttpMethod
wsFunctionName WsFunctionName
wsParameters PlainObject

a plain object containing the parameters to send to the web service. This object can be used to override the default data format via the moodlewsrestformat key.

options PlainObject <optional>
{}

a plain object which can be used to override default options like timeout. The parameters can be specified as a regular JavaScript data structure, because they will automatically get encoded into the format required by the Moodle web service.

Throws:
  • A validation error is thrown if invalid parameters are passed.

    Type
    ValidationError
  • A web service error is thrown if the reply received from the web service is a JSON string representing an object with the key exception.

    Type
    MoodleWSError
Returns:
Type:
PlainObject

Returns a promise of aplain object generated by parsing the body of the web service response as a JSON string.

Examples

A call with no web service parameters

let siteInfoPromise = myMoodleWS.submit('GET', 'core_webservice_get_site_info');

A call with web service parameters

let usersPromise = myMoodleWS.submit(
    'GET',
    'core_user_get_users',
    {
        criteria: [ { key: 'email', value: '%%' } ]
    }
);
// webservice parameters will get automatically translated to:
// {
//     'criteria[0][key]': 'email',
//     'criteria[0][value]': '%%'
// }