NAV

Plugin creation prerequisites

Writing plugin code

Plugins must be written in Javascript, for the Node.js interpreter. You must be accustomed to how modules are loaded and exported.

As Kuzzle treats plugins as Node.js modules, plugins must make themselves available to Kuzzle using module.exports. Otherwise Kuzzle won’t be able to instantiate them.

Plugin default configuration

Plugins must have a package.json file in their root directory, containing a pluginInfo entry.

The optional defaultConfig attribute is used by Kuzzle to initialize the plugin configuration when installing it.

This configuration can then be changed using the command-line interface.

Default configuration example:

"name": "plugin-name",
"version": "0.0.1",
"main": "./lib/index.js",
"pluginInfo": {
  "defaultConfig": {
    "any": "information",
    "useful": ["to", "the", "plugin"]
  }
}

Special plugin configurations

Additionally to plugins’ custom configuration, there are a few reserved words used by Kuzzle to configure how a plugin is loaded:

"name": "plugin-name",
"version": "0.0.1",
"main": "./lib/index.js",
"pluginInfo": {
    "defaultConfig": {
      "threads": 0,
      "privileged": false
    }
  }

Where:

Keyword Type Default Value Description
threads unsigned integer 0 If > 0, the plugin will be treated as a worker plugin (see below)
privileged boolean false If true, the plugin is loaded with privileged access to the running Kuzzle instance (see Plugin Context below)
Ignored if threads is greater than 0

Plugin init function

Plugins must expose a init function.

Kuzzle calls these init function at startup, during initialization, and ignore any plugin without this function exposed.

Expected arguments: function (config, context)

Where:

  • config (JSON Object): JSON object containing the current plugin configuration
  • context (JSON Object): the plugin context

Plugin types

To plug itself to Kuzzle, a plugin exposes properties, telling Kuzzle what the plugin does, and how and when it should be invoked.

Depending on the properties it exposes, a plugin can be of one or several of the following types detailed below.

Listener plugins

listener plugins simply listen to events, and are supplied with these events data. These plugins cannot change the provided data, and Kuzzle does not wait for them to process the data either.

To configure a plugin as a listener on Kuzzle events, it needs to expose a hooks JSON object, linking Kuzzle events name with the names of plugin functions to execute.
Each function that Kuzzle needs to call must also be exposed.

Example

function MyPlugin () {
  /*
    This exposed "hooks" property tells Kuzzle that it needs to
    attach the plugin function "myFunction" to the Kuzzle event
    "eventType:hookName"

    The function "myFunction" will be called whenever the event
    "eventType:hookName" is fired.
   */
  this.hooks = {
    'eventType:hookName': 'myFunction'
  };

  /*
   Required plugin initialization function
   (see the "Plugin prerequisites" section)
   */
  this.init = function (config, context) {
    // initializes the plugin
  };

  /*
   The configured function to call whenever the
   "eventType:hookName" event is fired
   */
  this.myFunction = function (message, event) {
    console.log(`Event ${event} triggered`);
    console.log(`Message received: ${message}`);
  };
}

// Exports the plugin objects, allowing Kuzzle to instantiate it
module.exports = MyPlugin;

Worker plugins

A worker plugin is simply a listener plugin running in separate processes. This is especially useful when you have to perform cost-heavy operations without impeding Kuzzle performances.

To convert a listener plugin to a worker one, you only need to add the following attribute to the plugin configuration: threads: <number of threads>

If this number of threads is greater than 0, Kuzzle will launch the plugin on as many separate threads.
If there are more than 1 thread for that plugin, each time a listened event is fired, Kuzzle will pick one thread to notify using round-robin.

Plugin configuration example:

{
  "version": "2.0.1",
  "defaultConfig": {
    "threads": 2
  },
  "activated": true
}

Pipe plugins

pipe plugins, like listener plugins, are attached to Kuzzle events, and they are supplied with these events data.
But unlike listener plugins, Kuzzle waits for their results before continuing the process.

This means that pipe plugins may:

  • modify the provided data on the fly
  • instruct Kuzzle to abort the request, sending an immediate and custom answer to the requesting client

Where a listener exposes a hooks property, a pipe plugin needs to expose its events in a pipes one, listing the listened events, and the plugin functions to invoke whenever these events are fired (see the example below).

Since pipe plugins are a part of how Kuzzle processes client requests, Kuzzle enforces a timeout on them, rejecting the request altogether if a pipe plugin fails to respond in a timely fashion, and forwarding an appropriate GatewayTimeoutError error to the original client.
The timeout value can be configured in Kuzzle configuration file.

A single event can be listened by multiple pipe plugins. When this is the case, Kuzzle calls the attached plugins sequentially, without any particular order.

pipe plugins functions take a callback as their last parameter, and this callback must be called at the end of the processing with the following arguments: callback(error, object), where:

  • error: set this value to a KuzzleError object to make Kuzzle abort the request, and return that error to the client. Otherwise, set it to null
  • object: the resulting data, given back to Kuzzle for processing

The following plugin example adds a createdAt attribute to all newly created documents:

function MyPlugin () {
  /*
    This exposed "pipes" property tells Kuzzle that it needs to
    attach the plugin function "addCreatedAt" to the Kuzzle event
    "document:beforeCreate"

    The function "addCreatedAt" will be called whenever the event
    "document:beforeCreate" is fired. Kuzzle will wait for
    the function's result before continuing the request process
   */
  this.pipes = {
    'document:beforeCreate': 'addCreatedAt'
  };

  /*
    Required plugin initialization function
    (see the "Plugin prerequisites" section)
   */
  this.init = function (config, context) {
    // Plugin initialization
  };

  // Called whenever "document:beforeCreate" is fired
  this.addCreatedAt = function (request, callback) {
    request.input.body.createdAt = Date.now();
    callback(null, request);
  };
}

// Exports the plugin objects, allowing Kuzzle to instantiate it
module.exports = MyPlugin;

Controller plugins

Kuzzle API is divided into “controllers”, each one of them exposing “actions” to execute (see API reference).

controller plugins extend Kuzzle API by adding new controllers to it, each with their own list of available actions.

How is the API extended

To avoid name conflicts, added controllers are prefixed with the plugin name.

Examples:

  • HTTP: GET http://<server>:<port>/_plugin/<plugin name>/<url defined by the plugin>/<resources>

  • Other protocols:

{
  controller: '<plugin name>/<added controller name>',
  action: '<action of the added controller>',
  ...
}

How to implement a controller plugin

A controller plugin must expose to Kuzzle the following objects:

  • A controllers object, describing the new controller to add. It will automatically be made available to any network protocol, except for HTTP

  • A routes objects, describing how the new controller should be exposed to the HTTP protocol. Only GET and POST verbs are accepted.

  • Controller’s actions functions. These methods take a Request object as an argument, and must return a Promise resolving with the action’s result, or rejecting with a KuzzleError object.

Controller plugin implementation example

function MyPlugin () {
  /*
    This exposed "controllers" property tells Kuzzle that it needs to extend
    its API with new controllers and actions.

    Here, we add a controller "newController", with 2 described actions:
    "myAction" and "myOtherAction".

    These actions point to functions exposed to Kuzzle by the plugin.

    Any network protocol other than HTTP will be able to invoke this new
    controller with the following JSON object:

    {
      controller: '<plugin name>/newController',
      action: 'myAction',
      ...
    }
   */
  this.controllers = {
    newController: {
      myAction: 'actionImplementation',
      myOtherAction: 'otherActionImplementation'
    }
  };

  /*
    We also want to expose our new controller to the HTTP protocol.
    To do so, we give Kuzzle instructions on how we want to expose our
    controller to HTTP.
    Any parameter starting with a ':' in the URL will be made dynamic by Kuzzle.

    The first route exposes the following GET URL:
      http://<kuzzle server>:<port>/_plugin/<plugin name>/foo/<dynamic value>

    Kuzzle will provide the function 'actionImplementation' with a Request object,
    containing the "name" property: request.input.args.name = '<dynamic value>'

    The second route exposes the following POST URL:
      http://<kuzzle server>:<port>/_plugin/<plugin name>/bar

    Kuzzle will provide the content body of the request in the Request object
    passed to the function 'otherActionImplementation', in the request.input.body
    property
   */
  this.routes = [
    {verb: 'get', url: '/foo/:name', controller: 'newController', action: 'myAction'},
    {verb: 'post', url: '/bar', controller: 'newController', action: 'myOtherAction'}
  ];

  /*
    Required plugin initialization function
    (see the "Plugin prerequisites" section)
   */
  this.init = function (config, context) {
    // plugin initialization
  };

  /*
    Implements the action newController/myAction
    Takes a Request object as an argument, and MUST return
    a promise resolved (or rejected) with the action's result
    This result can be of any JS type (scalar, object, array), and
    will be used to build a response to send to the requesting client

    See the "How plugins receive action arguments" chapter just below
    for more information.
   */
  this.actionImplementation = function (request) {
    // do action

    // optional: set network specific headers
    if (request.context.protocol === 'http') {
      // expires in 1h
      request.response.setHeader('expires', new Date(Date.now() + 3600000).toUTCString());
    }

    // Resolve with the result content. For instance:
    return Promise.resolve({acknowledge: true});
  };

  /*
    Implements the action newController/myOtherAction
    Takes a Request object as an argument, and MUST return
    a promise resolved (or rejected) with the action's result
    This result can be of any JS type (scalar, object, array), and
    will be used to build a response to send to the requesting client

    See the "How plugins receive action arguments" chapter just below
    for more information.
   */
  this.otherActionImplementation = function (request) {
    // do action
    return Promise.resolve(/* result content */);

  };
}

// Exports the plugin objects, allowing Kuzzle to instantiate it
module.exports = MyController;

How plugins receive action arguments

All action functions receive a Request object as main argument. Kuzzle will fill it with arguments provided by clients invoking the added controller:

  • HTTP:

    • dynamic arguments provided in the URL, headers and query string arguments are stored in request.input.args
    • content body is made available in request.input.body
    • if the URL contains an index, a collection or a _id argument, it will be stored in request.input.resource
  • Other protocols:

    • if the provided JSON object contains a body object, then its content will be stored in request.input.body
    • the following fields at the root of the provided JSON objects are available in request.input.resource: index, collection, _id
    • any unrecognized property at the root of the provided JSON object will be stored in the request.input.args part of the Request object

Protocol plugins

Kuzzle core only supports HTTP communications natively. All other supported protocols are implemented as protocol plugins.
By default, the Kuzzle official docker image is shipped with the following protocol plugins:

How it works

Requests sent by clients can be forwarded to Kuzzle by protocol plugins using the router accessor
To access these methods, simply call context.accessors.router.<router method>:

Router method Arguments Returns Description
newConnection protocol name (string)
connection ID (string)
A promise resolving to a RequestContext object Declares a new connection to Kuzzle.
execute request (Request object)
callback (a callback resolved with Kuzzle’s response)
Executes a client request.
removeConnection RequestContext (obtained with newConnection) Asks Kuzzle to remove the corresponding connection and all its subscriptions

Kuzzle expects protocol plugins to expose the following methods:

Method Arguments Description
init pluginConfiguration, context Plugin initialization function
joinChannel {channel, id} Tells protocol plugins that the connection id subscribed to the channel channel
leaveChannel {channel, id} Tells protocol plugins that the connection id left the channel channel
notify {channels, id, payload} Asks protocol plugins to emit a data payload (JSON Object) to the connection id (string), on the channels channels (array of strings)
broadcast {channels, payload} Asks protocol plugins to emit a data payload (JSON Object) to clients connected to the channels list channels (array of strings)
disconnect id Asks protocol plugins to force-close the connection id

The connection id Kuzzle sends to plugins is the one declared by protocol plugins using context.accessors.router.newConnection.

For more information about channels, see our API Documentation

protocol plugin implementation example

function MyPlugin () {
  this.pluginContext = null;

  // Example on how to maintain client contexts
  this.clients = {};

  /*
   Required plugin initialization function
   (see the "Plugin prerequisites" section)
  */
  this.init = function (config, context) {
    // plugin initialization
    this.pluginContext = context;
  };

  /*
   This function is only an example showing how to interact with
   clients and with Kuzzle. It does not implement any actual protocol.

   The way a protocol plugins handles clients closely depends on the
   implemented protocol.
   */
  this.handleClient = function () {
    // when a client connects
    this.on('onClientConnect', function (connectionId) {
      this.pluginContext.accessors.router.newConnection("protocol name", connectionId)
        .then(context => {
          this.clients[connectionId] = context;
        });
    });

    // when a client sends a request
    this.on('onClientRequest', function (connectionId, data) {
      // Instantiates a Request object to be passed to Kuzzle
      let request = new Request(data, this.clients[connectionId]);

      this.pluginContext.accessors.router.execute(request, response => {
        // forward the response to the client
      });
    });

    // whenever a client is disconnected
    this.on('onClientDisconnect', function (connectionId) {
      this.pluginContext.accessors.router.removeConnection(this.clients[connectionId]);
      delete this.clients[connectionId];
    });
  };

  /*
   Invoked by Kuzzle when a "data.payload" payload needs to be
   broadcasted to the "data.channels" channels

   The payload is a Kuzzle response as a plain-old JSON object
  */
  this.broadcast = function (data) {
    data.channels.forEach(channel => {
      // sends data.payload to the channel
    });
  };

  /*
   Invoked by Kuzzle when a "data.payload" payload needs to be
   notified to the connection "data.id", on the "data.channels" channels

   The payload is a Kuzzle response as a plain-old JSON object
  */
  this.notify = function (data) {
    data.channels.forEach(channel => {
      // sends "data.payload" to the connection "data.id" and to
      // the channel "channel"
    });
  };

  /*
    Invoked by Kuzzle when the connection "data.id" joins the
    channel "data.channel"
   */
  this.joinChannel = function (data) {
     // ...
  };

  /*
    Invoked by Kuzzle when the connection "data.id" leaves the
    channel "data.channel"
   */
  this.leaveChannel = function (data) {
    // ...
  };

  /*
    Invoked by Kuzzle when it needs to force-close a client connection
   */
  this.disconnect = function (id) {
    // close the connection opened by the connection "id"
  };
};

// Exports the plugin objects, allowing Kuzzle to instantiate it
module.exports = MyPlugin;

Authentication plugin

Kuzzle handles users security and authentication. The supported authentication strategies can be extended using authentication plugins.

Any strategy supported by Passport can be used to extend Kuzzle supported strategies, like we did with our official OAUTH2 Authentication plugin.

Choose or implement a Passport strategy

Passport supports a wide range of authentication strategies. If that is not enough, you can also implement your own strategy for your authentication plugin.

In any case, the chosen strategy must be available in the plugin local directory when Kuzzle installs it, either by adding the strategy in the plugin’s NPM dependencies, or by including the strategy code directly in the plugin repository.

Create a verification function

Since Kuzzle uses Passport directly, using a strategy with Kuzzle is the same than using one with Passport.

First, you have to implement a verify function, which will be provided to a Passport strategy constructor. This function is then used by the Passport strategy to authorize or to deny access to a user.

The number of arguments taken by this verify function depends on the authentication strategy. For instance, a local password strategy needs the verify callback to be provided with an user name and his password.

All strategies require this verify callback to take a done callback as its last argument, supplying Passport with the authenticated user’s information.

Register the strategy to Kuzzle

Once you chose a strategy and implemented its corresponding verify callback function, all you have to do is to register it to Kuzzle, using the passport accessor available in the plugin context:

pluginContext.accessors.passport.use(strategy);

(optional) Scope of access

Some authentication procedures, like OAUTH 2.0, need a scope of access to be configured.

Kuzzle authentication plugins support scope of access. To add one in your plugin, simply expose a scope attribute. Its format depends on the provider the strategy implements.

Authentication plugin example, using the LocalStrategy strategy

const LocalStrategy = require('passport-local').Strategy;

function MyAuthenticationPlugin () {
  this.context = null;

  /*
    Required plugin initialization function
    (see the "Plugin prerequisites" section)
   */
  this.init = function (pluginConfiguration, pluginContext) {
    this.context = pluginContext;

    this.context.accessors.passport.use(new LocalStrategy(this.verify.bind(this)));
  }

  this.verify = function (username, password, done) {
    // Code performing the necessary verifications
    if (success) {
      done(null, this.context.accessors.users.load(username));
    }
    else {
      done(new this.context.errors.ForbiddenError('Login failed'));
    }
  };
};

// Exports the plugin objects, allowing Kuzzle to instantiate it
module.exports = MyAuthenticationPlugin;

The plugin context

The plugin context is an object containing a set of constructors, accessors and configurations, allowing plugins to interact with Kuzzle.

A plugin context is provided by Kuzzle to plugins when calling their init function.
Each plugin receives its own plugin context instance.

Here is the list of shared objects contained in the provided context:

Attribute path Purpose
context.accessors.execute Access to Kuzzle API
context.accessors.passport Access to Kuzzle Passport instance. Allow authentication plugins to register a new login strategy to Kuzzle.
context.accessors.router Access to Kuzzle protocol communication system. Allow protocol plugins to interface themselves with Kuzzle.
context.accessors.users Access to users management, especially useful for authentication plugins. Provides methods for handling users. This accessor is mainly used by authentication plugins.
context.accessors.validation Access to validation mechanisms, useful to validate documents and add field types.
context.config Contains the entire Kuzzle instance configuration (most of it coming from Kuzzle configuration file)
context.constructors.Dsl Constructor allowing plugins to instantiate their own Kuzzle real-time engine instance
context.constructors.Request Constructor for standardized requests sent to Kuzzle
context.constructors.BaseValidationType Constructor for the Validation Type base constructor
errors.<ErrorConstructor> Kuzzle error constructors, built dynamically from available Kuzzle error objects at runtime

Note: context.accessors are not available to worker plugins, as they are run in their own process(es), without access to Kuzzle instances.

Accessor

execute

Sends a request to Kuzzle API.

Arguments

Name Type Description
request Request A Request to execute
callback(error, request) Function Function executed with the request’s result

Note: when callback is invoked, the request argument is ALWAYS filled, even when there is an error. This argument is the provided request, with its result and/or error parts filled. To obtain the standardized Kuzzle response from it, simply use the getter request.response.

Example:

let
  derivedRequest = new context.constructors.Request(request, {
    index: 'index',
    collection: 'collection',
    controller: 'read',
    action: 'get',
    _id: 'documentID'
  });

context.accessors.execute(request, (error, request) => {
  /*
   Kuzzle's response can be obtained with request.response

   See Request constructor documentation for more information
   */
});

passport.use

Implements Passport use() method

Arguments

Name Type Description
strategy Strategy object A Passport instantiated strategy object

Example:

var LocalStrategy = require('passport-local').Strategy;

function verify (username, password, done) {
  // verification code
  if (userVerified) {
    done(null, userInformation);
  }
  else {
    done(error);
  }
}

pluginContext.accessors.passport.use(new LocalStrategy(verify.bind(this)));

router.newConnection

Declares a new connection for a given protocol.

Arguments

Name Type Description
protocolName string Protocol name, used for Kuzzle internal statistics
connectionUniqueId string Unique ID identifying the user connection

Returns

A promise resolving to a RequestContext object. This object is needed for other router methods.

router.execute

Forward a request to Kuzzle.

Arguments

Name Type Description
request Request An user request wrapped as a Request instance
callback function Callback called with the request corresponding results

Callback

The callback is invoked once the request has been processed by Kuzzle.
The provided callback is resolved with a response argument, which is a plain-object, representing a standardized Kuzzle response.

router.removeConnection

Removes a connection from the connection pool maintained by Kuzzle.
Not calling this method after a connection is dropped will result in a memory-leak.

Arguments

Name Type Description
context RequestContext Object identifying the connection context. Obtained by calling newConnection()

users.create

Creates a new user in Kuzzle. Will return an error if the user already exists.

Arguments

Name Type Default Value Description
loginName string Name of the user’s login to create
userProfile string default User profile
userInfo object {} Misc. information about the user

Returns

A promise resolving a user object containing the created information.

users.load

Loads a user from Kuzzle

Arguments

Name Type Description
loginName string Name of the user’s login to load

Returns

A promise resolving to a user object containing the user information.

validation.validate

Validates a document wrapped in a Request object.

Arguments

Name Type Description
request Request A document wrapped as a Request object
verbose boolean Defines the behavior of the validation

Returns

If verbose is set to false:

Returns a promise that resolves to a modified Request instance where defaultValues are applied. Rejects if validation fails.

If verbose is set to true:

Returns a promise that resolves to an object:

{
  errorMessages: ...,
  validation: ...
}

Where:

  • errorMessages is a structured javascript object reflecting the structure of the document with all errors collected during the validation process
  • validation is a boolean reflecting the validation state.

validation.addType

Arguments

Name Type Description
validationType object An object instance of a validation type

Returns

Nothing. Can throw a PluginImplementationError if the validation type has not the expected form.

validationType form

/**
 * @typedef {{
 *   validate: Function,
 *   validateFieldSpecification: Function,
 *   typeName: string,
 *   allowChildren: boolean,
 *   checkAllowedProperties: Function,
 *   allowedTypeOptions: string[]
 * }} ValidationType
 */

See constructor BaseValidationType for more details.

Constructor

BaseValidationType

The BaseValidationType constructor provides a base to create your own validation types. It provides a common structure for all validation types developped in Kuzzle.

You can find an example of a type creation in the Kuzzle source code.

Dsl

The DSL constructor provided in the plugin context gives access to Kuzzle real-time filtering capabilities. It allows managing filters, and testing data to get a list of matching filters.

Each plugin can instantiate its own sandboxed DSL instance:

var dsl = new context.constructors.Dsl();

The DSL exposes the following methods:

exists

Returns a boolean indicating if filters exist for an index-collection pair

Arguments

Name Type Description
index string Data index name
collection string Data collection name

Returns

Returns true if at least one filter exists on the provided index-collection pair, returns false otherwise

getFilterIds

Retrieves filter IDs registered on an index-collection pair

Arguments

Name Type Description
index string Data index name
collection string Data collection name

Returns

An array of filterId corresponding to filters registered on an index-collection pair.

register

Registers a filter to the DSL.

Arguments

Name Type Description
index string Data index name
collection string Data collection name
filters object Filters in Kuzzle DSL format

Returns

A promise resolving to an object containing the following attributes:

  • id: the filter unique identifier
  • diff: false if the filter already existed in the engine. Otherwise, contains an object with the canonical version of the provided filters

remove

Removes all references to a given filter from the DSL

Arguments

Name Type Description
filterId string Filter unique ID. Obtained by using register

Returns

A promise resolved once the filter has been completely removed from the DSL

test

Test data against filters registered in the DSL, returning matching filter IDs, if any.

Arguments

Name Type Description
index string Data index name
collection string Data collection name
data object Data to test against filters
documentId string If applicable, document unique ID

Returns

An array of filterId matching the provided data (and/or documentId, if any).

validate

Tests the provided filters without storing them in the system, to check whether they are well-formed or not.

Arguments

Name Type Description
filters object Filters in Kuzzle DSL format

Returns

A resolved promise if the provided filters are valid, or a rejected one with the appropriate error object otherwise.

Request

This constructor is used to transform an API call into a standardized Kuzzle request. This object is updated along the request process to reflect the current state of the request, and is ultimately used to serialize a standard Kuzzle response to be forwarded to the requesting client.

Network protocol specific headers can be added to the response. If the protocol can handle them, these headers will be used to configure the response sent to the client.
As Kuzzle supports the HTTP protocol natively, this object handles HTTP headers special cases. Other network protocols headers are stored in raw format, and protocol plugins need to handle their own specific headers manually.

For more information about this object, please check our detailed documentation.

Arguments

Name Type Description
request Request Request object used to derive a new object instance
data object Passed to RequestInput constructor
options object Optional initialization parameters

RequestContext is usually obtained with context.accessors.router.newConnection.

If a raw options object is provided, it may contain:

Name Type Description
connectionId string Passed to RequestContext constructor
error KuzzleError or Error Invokes setError at initialization
protocol string Passed to RequestContext constructor
requestId string Initializes the id property
result (varies) Invokes setResult at initialization
status integer HTTP error code
token object Passed to RequestContext constructor
user object Passed to RequestContext constructor

Here is an example:

let derivedRequest = new context.constructors.Request(request, {
  controller: 'write',
  action: 'create',
  index: 'foo',
  collection: 'bar',
  _id: 'some document ID',
  body: {
    document: 'content'
  },
  metadata: {
    some: 'volatile data'
  }
});

Attributes

Read-only

Name Type Description
timestamp integer Request creation timestamp

Writable

Name Type default Description
context RequestContext RequestContext object Request connection context
error KuzzleError null Request error, if any
id string Auto-generated UUID Request unique identifier
input RequestInput RequestInput object Request’s parameters
result (varies) null Request result, if any
status integer 102 HTTP status code

Any undefined attribute from the list above will be set to null.

Please refer to our API Reference for a complete list of controllers-actions and their purposes.

Getters

Name Type Description
response RequestResponse Response view of the request, standardized as the expected Kuzzle API response

response.getHeader

Returns the value registered for the response header name

Arguments

Name Type Description
name string Header name

response.getHeaders()

Returns an object describing all currently registered headers on that response.

if (request.context.protocol === 'http') {
  request.response.setHeader('Content-Type', 'text/plain');

  /*
    Prints:
    { "Content-Type": "text/plain" }
   */
  console.log(request.response.getHeaders());
}

response.removeHeader

Removes header name from the response headers.

setHeader

Adds a header name with value value to the response headers.

Arguments

Name Type Description
name string Header name
value string Header value

For standard headers, if name already exists, then the provided value will be concatenated to the existing value, separated by a comma.

As Kuzzle implements HTTP natively, this behavior changes for some HTTP specific headers, to comply with the norm. For instance set-cookie values are amended in an array, and other headers like user-agent or host can store only 1 value.

serialize

Serializes the Request object into a pair of POJOs that can be sent across the network, and then used to rebuild another equivalent Request object.

let foo = request.serialize();
let bar = new context.constructors.Request(request, foo.data, foo.options);

setError

Adds an error to the request, and sets the request’s status to the error one.

Arguments

Name Type Description
error KuzzleError or Error Error object to set

If a KuzzleError is provided, the request’s status attribute is set to the error one.

Otherwise, the provided error is encapsulated into a InternalError object, and the request’s status is set to 500.

setResult

Sets the request’s result.

Arguments

Name Type Description
result (varies) Request’s result
options object Optional parameters

The options argument may contain the following properties:

Name Type Description Default
status integer HTTP status code 200
headers object Protocol specific headers null
raw boolean Asks Kuzzle to send the provided result directly, instead of encapsulating it in a Kuzzle JSON response false

Errors

KuzzleError

Inherits from Error. Abstract class inherited by Kuzzle error objects.

This class should only be used to create new Kuzzle error objects.

BadRequestError

Status Code: 400

Used to notify about badly formed requests.

var err = new context.errors.BadRequestError('error message');

ForbiddenError`

Status Code: 403

Used when a user tries to use resources beyond his access rights.

var err = new context.errors.ForbiddenError('error message');

GatewayTimeoutError

Status Code: 504

Used when a plugin takes too long to perform a task.

var err = new context.errors.GatewayTimeoutError('error message');

InternalError

Status Code: 500

Standard generic error. Used for uncatched exceptions.

var err = new context.errors.InternalError('error message');

NotFoundError

Status Code: 404

Used when asked resources cannot be found.

var err = new context.errors.NotFoundError('error message');

ParseError

Status Code: 400

Used when a provided resource cannot be interpreted.

var err = new context.errors.ParseError('error message');

PartialError

Status Code: 206

Used when a request only partially succeeded.

The constructor takes an additional array argument containing a list of failed parts.

var err = new context.errors.PartialError('error message', [{this: 'failed'}, {andThis: 'failed too'}]);

PluginImplementationError

Status Code: 500

Used when a plugin fails.

var err = new context.errors.PluginImplementationError('error message');

ServiceUnavailableError

Status Code: 503

Used when a resource cannot respond because it is temporarily unavailable.

var err = new context.errors.ServiceUnavailableError('error message');

SizeLimitError

Status Code: 413

Used to notify about requests exceeding maximum limits.

var err = new context.errors.SizeLimitError('error message');

UnauthorizedError

Status Code: 401

Used when a user fails a login attempt.

var err = new context.errors.UnauthorizedError('error message');

Kuzzle events list

auth

Events triggered when a request is treated in the auth controller.

Event Description Input
auth:after<Action> All actions in auth controller trigger an event after executing Type: Request
auth:before<Action> All actions in auth controller trigger an event before executing Type: Request

bulk

Events triggered when a request is treated in the bulk controller.

Event Description Input
bulk:afterImport The import action in bulk controller triggers an event after executing Type: Request
bulk:beforeImport The import action in bulk controller triggers an event before executing Type: Request

cleanDb

Events triggered when a database reset is asked to the command-line interface.

Event Description Input
cleanDb:deleteIndexes Triggered during cleanDb process just before indexes deletion. Type: Request object.
Contains all indexes to delete in requestObject.data.body.indexes
cleanDb:done Triggered after indexes deletion. /
cleanDb:error Triggered when an error occurred on clean db Type: Error

collection

Events triggered when a request is treated in the collection controller.

Event Description Input
collection:after<Action> All actions in collection controller trigger an event after executing Type: Request
collection:before<Action> All actions in collection controller trigger an event before executing Type: Request

core

Events triggered to synchronize Kuzzle server instances in a cluster.

Event Description Input
core:kuzzleStart Emitted when Kuzzle is started /
core:hotelClerk:addSubscription Sends a diff containing the filters and internal hotelClerk updates hcR object
core:hotelClerk:join Sends hotelClerk diff when a room is joined hcR object
core:hotelClerk:removeRoomForCustomer Sends the room unsubscription information if it changed {connection, roomId}
core:indexCache:add Triggered when data is added to Kuzzle’s index cache {index, collection}
core:indexCache:remove Triggered if some data were actually removed from Kuzzle’s index cache {index, collection}
core:indexCache:reset Triggered if the indexCache is reset {index}
core:overload Triggered when the overload cache is filling up Overload percentage. Type: Number

index

Events triggered when a request is treated in the index controller.

Event Description Input
index:after<Action> All actions in index controller trigger an event after executing Type: Request
index:before<Action> All actions in index controller trigger an event before executing Type: Request

document

Events triggered when a request is treated in the document controller.

Event Description Input
document:after<Action> All actions in document controller trigger an event after executing Type: Request
document:before<Action> All actions in document controller trigger an event before executing Type: Request

http

Event Description Input
http:options Triggered whenever a HTTP OPTIONS methods is handled Type: Request

internalBroker

Events triggered by the Kuzzle internal message broker, used to transmit data between Kuzzle instances.

Event Description Input
internalBroker:connected Triggered when the internal broker is connected Type: String.
'Connected to Kuzzle server'
internalBroker:error Triggered when an error occured in internal broker Type: Object.
{host, port, message, retry}
internalBroker:reregistering Triggered when the internal broker is reregistered Type: String.
'Re-registering room: ' + room
internalBroker:socketClosed Triggered when the socket is closed Type: String
internalBroker:started Triggered when the internal broker is started Type: String.
'Internal broker server started'

ms (memoryStorage)

Events triggered when a request is sent to the memoryStorage controller.

Event Description Input
ms:after<Action> All actions in memoryStorage controller trigger an event after executing Type: Request
ms:before<Action> All actions in memoryStorage controller trigger an event before executing Type: Request

prepareDb

Events triggered during Kuzzle startup, when the database is prepared for Kuzzle’s use.

Event Description Input
prepareDb:createFixturesIndex Triggered during database preparation. Called for each index in fixtures Type: Request.
Contains the index to create in requestObject.index
prepareDb:createInternalIndex Triggered on Kuzzle start to create the internal index %kuzzle Type: Request.
Contains the internal index in requestObject.index
prepareDb:error Triggered when an error occurred during database preparation Type: Error.
prepareDb:importFixtures Triggered during database preparation. Called for each fixtures to import Type: Request.
Contains the index in requestObject.index and bulk in requestObject.data.body
prepareDb:importMapping Triggered during database preparation. Called for each mapping to import Type: Request.
Contains the index in requestObject.index and mapping in requestObject.data.body
prepareDb:updateMappingProfiles Triggered on Kuzzle start to create the internal mapping for Profiles collection Type: Request.
Contains the default mapping in requestObject.data.body
prepareDb:updateMappingRoles Triggered on Kuzzle start to create the internal mapping for Roles collection Type: Request.
Contains the default mapping in requestObject.data.body
prepareDb:updateMappingUsers Triggered on Kuzzle start to create the internal mapping for Users collection Type: Request.
Contains the default mapping in requestObject.data.body

proxy

Events triggered when interacting with proxy.

Event Description Input
proxy:broadcast Triggered before broadcast. You can’t modify the input on this event Type: Object.
{payload, channelsList}
payload is the notification content.
channelsList is an array of channels to broadcast.
proxy:joinChannel Triggered after attaching a user to a room. You can’t modify the input on this event Type: Object.
{channel, id}
channel is the channel name.
id is the connection id
proxy:leaveChannel Triggered before a room is removed for the user. You can’t modify the input on this event Type: Object.
{channel, id}
channel is the channel name.
id is the connection id
proxy:notify Triggered before notifying a connection id Type: Object.
{payload, channelsList, id}
payload is the notification content.
channelsList is an array of channels to notify.
id is the connection id

realtime

Events triggered when a request is sent to the realtime controller.

Event Description Input
realtime:after<Action> All actions in realtime controller trigger an event after executing Type: Request
realtime:before<Action> All actions in realtime controller trigger an event before executing Type: Request

room

Events triggered on subscription rooms activity.

Event Description Input
room:new Triggered when a new room is added in the rooms list. You can’t modify the input on this event Type: Object.
{roomId, index, collection, formattedFilters}
room:remove Triggered after a room is removed from the list. You can’t modify the input on this event Type: String.
The room id

security

Events triggered when a request is sent to the security controller.

Event Description Input
security:after<Action> All actions in security controller trigger an event after executing Type: Request
security:before<Action> All actions in security controller trigger an event before executing Type: Request
security:formatUserForSerialization Triggered before serializing a user. Useful to clean a user like attribute password Type: User

server

Events triggered on server special events or when a request is sent to the server controller.

Event Description Input
server:after<Action> All actions in server controller trigger an event after executing Type: Request
server:before<Action> All actions in server controller trigger an event before executing Type: Request