constructors


BaseValidationType

Since Kuzzle v1.0.0

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

Since Kuzzle v1.0.0

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

Each plugin can instantiate its own sandboxed DSL instance:

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

The DSL exposes the following methods:

exists

Since Kuzzle v1.0.0

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

Arguments

NameTypeDescription
indexstringData index name
collectionstringData collection name

Returns

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

getFilterIds

Since Kuzzle v1.0.0

Retrieves filter IDs registered on an index-collection pair

Arguments

NameTypeDescription
indexstringData index name
collectionstringData collection name

Returns

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

normalize

Since Kuzzle v1.1.0

Returns a promise resolved if the provided filters are well-formed.
The resolved object is a normalized and optimized version of the supplied filters, along with its corresponding Room unique identifier.

This method does not modify the DSL storage. To register the filters, the store method must be called afterwards.
If you do not need the Room unique identifier prior to store the DSL filters, then consider using register instead.

Arguments

NameTypeDescription
indexstringData index name
collectionstringData collection name
filtersobjectFilters in Kuzzle DSL format

Returns

A promise resolving to an object containing the following attributes:

  • index: data index name
  • collection: data collection name
  • normalized: an object containing the optimized version of the supplied filters
  • id: the room unique identifier

register

Since Kuzzle v1.0.0

Registers a filter to the DSL. This method is equivalent to executing normalize + store.

Arguments

NameTypeDescription
indexstringData index name
collectionstringData collection name
filtersobjectFilters 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

Since Kuzzle v1.0.0

Removes all references to a given filter from the DSL

Arguments

NameTypeDescription
filterIdstringFilter unique ID. Obtained by using register

Returns

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

store

Since Kuzzle v1.1.0

Stores normalized filters (obtained with normalize) in the DSL storage.

Arguments

NameTypeDescription
normalizedObjectNormalized filters

Returns

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

test

Since Kuzzle v1.0.0

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

Arguments

NameTypeDescription
indexstringData index name
collectionstringData collection name
dataobjectData to test against filters
documentIdstringIf applicable, document unique ID

Returns

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

validate

Since Kuzzle v1.0.0

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

Arguments

NameTypeDescription
filtersobjectFilters in Kuzzle DSL format

Returns

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


Repository

Since Kuzzle v1.0.0

The Repository constructor provided in the plugin context gives access to methods that allow the plugin to interact with its plugin storage. The plugin storage is a dedicated index in Elasticsearch where the plugin can create collections. To do so the plugin should first bootstrap the index.

Once done, the plugin can instantiate repositories to interact with the different collections it created.

Arguments

NameTypeDescription
collectionstringThe collection linked to the repository
ObjectConstructorconstructor function(optional) Will be used as constructor for the fetched documents instead of Object

Usage

Each plugin can instantiate its own repositories linked to its own sandboxed plugin storage:

function ObjectConstructor() {
  this.someProperty = 'someValue';
}

var someCollectionRepository = new context.constructors.Repository('someCollection', ObjectConstructor);

The Repository exposes the following methods:

create

Since Kuzzle v1.0.0

Creates a document in the plugin storage.

Arguments

NameTypeDescription
documentObjectThe document you want to create. It must contain a unique _id string property. You don't need to worry about collisions with other plugins as your plugin storage is only accessible by your plugin
optionsObjectOptional arguments

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

NameTypeDescription
refreshstringValue can only be wait_for if provided. See Elasticsearch documentation for more information.

Returns

Returns a promise that resolves to an object respresentation of Elasticsearch request result.

Usage

someCollectionRepository.create({
  _id: '<a unique id>',
  someField: 'some content',
  anotherField: 'another content',
  ...
})
  .then(result => {
    console.log(result);
  });

/**
 * Outputs:
 * { _index: '%some-plugin',
 *   _type: 'someCollection',
 *   _id: '<a unique id>',
 *   _version: 1,
 *   result: 'created',
 *   _shards: { total: 2, successful: 1, failed: 0 },
 *   created: true,
 *   _source: { someField: 'some content', anotherField: 'another content' } }
 */

createOrReplace

Since Kuzzle v1.0.0

Creates or replaces a document in the plugin storage.

Arguments

NameTypeDescription
documentobjectThe document you want to create or replace. It must contain a unique _id string property. You don't need to worry about collisions with other plugins as your plugin storage is only accessible by your plugin
optionsObjectOptional arguments

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

NameTypeDescription
refreshstringValue can only be wait_for if provided. See Elasticsearch documentation for more information.

Returns

Returns a promise that resolves to an object representation of Elasticsearch request result (see create usage).

Usage

someCollectionRepository.createOrReplace({
  _id: '<a unique id>',
  someField: 'some content',
  anotherField: 'another content',
  ...
});

delete

Since Kuzzle v1.0.0

Deletes a document from the plugin storage.

Arguments

NameTypeDescription
documentobjectThe document _id of the document you want to delete.
optionsObjectOptional arguments

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

NameTypeDescription
refreshstringValue can only be wait_for if provided. See Elasticsearch documentation for more information.

Returns

Returns a promise that resolves to an array of objects which is a representation of the Elasticsearch request result.

Usage

someCollectionRepository.delete('someDocumentId')
  .then(result => {
    console.log(result);
  });

/**
 * Outputs:
 *  [ { found: true,
 *    _index: '%some-plugin',
 *    _type: 'someCollection',
 *    _id: '<a unique id>',
 *    _version: 3,
 *    result: 'deleted',
 *    _shards: { total: 2, successful: 1, failed: 0 } } ]
 */

get

Since Kuzzle v1.0.0

Retrieves a document from the plugin storage.

Arguments

NameTypeDescription
documentIdstringThe document identifier of the document you want to retrieve.

Returns

Returns a promise that resolves to an Object or an ObjectConstructor if provided in the constructor.

Usage

someCollectionRepository.get('someDocumentId', 'someCollection');

mGet

Since Kuzzle v1.0.0

Retrieves multiple documents from the plugin storage.

Arguments

NameTypeDescription
documentIdsarray<string>An array of document identifier of the documents you want to retrieve.

Returns

Returns a promise that resolves to an array of Object or ObjectConstructor if provided in the constructor.

Usage

someCollectionRepository.mGet(['someDocumentId', 'anotherDocument']);

replace

Since Kuzzle v1.0.0

Replaces a document in the plugin storage.

Arguments

NameTypeDescription
documentobjectThe content of the document. It must contain a unique _id string property.
optionsObjectOptional arguments

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

NameTypeDescription
refreshstringValue can only be wait_for if provided. See Elasticsearch documentation for more information.

Returns

Returns a promise that resolves to an object respresentation of Elasticsearch request result (see create usage).

Usage

someCollectionRepository.replace({
  _id: '<a unique id>',
  someField: 'some content',
  anotherField: 'another content',
  ...
});

search

Since Kuzzle v1.0.0

Searches documents that match the provided query in the collection.

Arguments

NameTypeDescription
queryobjectThe query sent to Elastisearch.
fromintegerProvides the offset of the returned documents.
sizeintegerProvides the count of the returned documents.

Returns

Returns a promise that resolves to an object of the form {total: number, hits: array<object>} where hits contains an array of Object or ObjectConstructor if provided in the constructor and total the count of documents that match the query.

Usage

someCollectionRepository.search({
  query: {
    match_all: {}
  }
}, 0, 10);

update

Since Kuzzle v1.0.0

Updates a document in the plugin storage. You can provide a partial document to add or update one or more fields.

Arguments

NameTypeDescription
documentobjectThe partial content of the document. It must contain a unique _id string property.
optionsObjectOptional arguments

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

NameTypeDescription
refreshstringValue can only be wait_for if provided. See Elasticsearch documentation for more information.

Returns

Returns a promise that resolves to an object which is a representation of the Elasticsearch request result.

Usage

someCollectionRepository.update({
  _id: '<a unique id>',
  anotherField: 'changed content'
});
/**
 * Outputs:
 * { _index: '%some-plugin',
 *   _type: 'someCollection',
 *   _id: '<a unique id>',
 *   _version: 2,
 *   result: 'updated',
 *   _shards: { total: 0, successful: 0, failed: 0 } }
 */

Request

Since Kuzzle v1.0.0

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.

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.

Constructors

new Request(<request object>, <data>, [options])

Since Kuzzle v1.0.0

NameTypeDescription
requestRequestRequest object used to derive a new object instance
dataobjectJSON object following the same standard than for non-HTTP API calls
See the RequestInput constructor for more information
optionsobjectOptional initialization parameters

This constructor creates a new Request object from the provided one, and then adds the supplied data to complete the new object.

This constructor is particularly useful when a plugin needs to execute an API request derivated from a user request, as most of the relevant information will be carried over to the new object.

Properties that are automatically copied to the new object:

  • All resources properties: _id, collection, index
  • Additional arguments: request.input.args
  • JSON Web Token, if any

Example:

const derivedRequest = new context.constructors.Request(request, {
  controller: 'document',
  action: 'create',
  body: {
    document: 'content'
  }
});

new Request(<data>, [options])

Since Kuzzle v1.2.0

NameTypeDescription
dataobjectJSON object following the same standard than for non-HTTP API calls
See the RequestInput constructor for more information
optionsobjectOptional initialization parameters

This constructor allows for creating new Request objects without the need to provide a source.

The provided data object must contain a lot more information than what's needed by the constructor method described above, so if a Request object is available to your method, you should probably use it to instantiate one of those objects.

Example:

const request = new context.constructors.Request({
  controller: 'document',
  action: 'create',
  index: 'index',
  collection: 'collection',
  _id: 'documentId',
  body: {
    document: 'content'
  }
});

The "options" parameter

If a raw options object is provided to one of the Request constructors (see above), then it may contain the following properties:

NameTypeDescription
connectionIdstringPassed to RequestContext constructor
errorKuzzleError or ErrorInvokes setError at initialization
protocolstringPassed to RequestContext constructor
requestIdstringInitializes the id property
result(varies)Invokes setResult at initialization
statusintegerHTTP error code
tokenobjectPassed to RequestContext constructor
userobjectPassed to RequestContext constructor

Attributes

Read-only

NameTypeDescription
timestampintegerRequest creation timestamp

Writable

NameTypedefaultDescription
idstringAuto-generated UUIDRequest unique identifier
statusinteger102HTTP status code

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

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

Getters

NameTypeDescription
contextRequestContextRequestContext objectRequest connection context
errorKuzzleErrornullRequest error, if any
inputRequestInputRequestInput objectRequest's parameters
responseRequestResponseResponse view of the request, standardized as the expected Kuzzle API response
result(varies)nullRequest result, if any

response.getHeader

Since Kuzzle v1.0.0

Returns the value registered for the response header name

Arguments

NameTypeDescription
namestringHeader name

response.removeHeader

Since Kuzzle v1.0.0

Removes header name from the response headers.

setHeader

Since Kuzzle v1.0.0

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

Arguments

NameTypeDescription
namestringHeader name
valuestringHeader 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

Since Kuzzle v1.0.0

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

Since Kuzzle v1.0.0

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

Arguments

NameTypeDescription
errorKuzzleError or ErrorError 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

Since Kuzzle v1.0.0

Sets the request's result.

Arguments

NameTypeDescription
result(varies)Request's result
optionsobjectOptional parameters

The options argument may contain the following properties:

NameTypeDescriptionDefault
statusintegerHTTP status code200
headersobjectProtocol specific headersnull
rawbooleanAsks Kuzzle to send the provided result directly,instead of encapsulating it in a Kuzzle JSON responsefalse