5.0.2 • Published 4 years ago

kuzzle-common-objects v5.0.2

Weekly downloads
394
License
Apache-2.0
Repository
github
Last release
4 years ago

Build Status codecov

Kuzzle common objects

Common objects shared to various Kuzzle components and plugins.

Table of contents:

Request

This constructor is used to transform an API request into a standardized Kuzzle request.

new Request(data, [options])

Arguments

NameTypeDescription
dataobjectPassed to RequestInput constructor
optionsobjectOptional initialization parameters

options may contain the following attributes:

NameTypeDescription
connectionobjectPassed to RequestContext constructor
errorKuzzleError or ErrorInvokes setError at initialization
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 Reference 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
deprecationsobject[]undefinedDeprecations, if any

Methods

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.

Example

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

setError(error)

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.

clearError()

Clear error from request: set error to null and set status to 200.

setResult(result, [options = null])

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 responsefalse

Example

const Request = require('kuzzle-common-objects').Request;

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

console.dir(request.serialize(), {depth: null});

Result:

{ 
  data: { 
    timestamp: 1482143102957,
    requestId: '26d4ec6d-aafb-4ef8-951d-47666e5cf3ba',
    jwt: null,
    volatile: { some: 'volatile data' },
    body: { document: 'content' },
    controller: 'document',
    action: 'create',
    index: 'foo',
    collection: 'bar',
    _id: 'some document ID',
    foo: 'bar' 
  },
  options: { 
    connection: {
      id: null,
      protocol: null,
      ips: [],
      misc: {}
    },
   result: null,
   error: null,
   status: 102 
  } 
}

addDeprecation(version, message)

Adds a deprecation on the request object allowing to notify when a controller or an action is deprecated for a specific version of Kuzzle

::: info Deprecation messages in request responses will only be added during development stages, i.e. if the NODE_ENV environment variable is set to development. :::

Arguments

NameTypeDescription
versionstringtarget version of the deprecation
messagestringdescription of the deprecation

Example

let request = new Request({});
request.addDeprecation('1.0.0', 'You should now use Kuzzle v2')
console.log(request.deprecations) // [{ version: '1.0.0', message: 'You should now use Kuzzle v2' }]

RequestResponse

This object is not exposed and can only be retrieved using the Request.response getter.

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.

Header names are case insensitive.

Example

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

Attributes

Writable

NameTypeDescription
errorKuzzleErrorResponse error, or null
result*Response result, or null
statusintegerResponse HTTP status code

Getters

NameTypeDescription
actionstringParent request invoked controller action
collectionstringParent request data collection
controllerstringParent request invoked controller
headersobjectAn object describing all currently registered headers on that response
indexstringParent request data index
volatileobjectParent request volatile data
requestIdstringParent request unique identifier
deprecationsobject[]Deprecations

Methods

getHeader(name)

Returns the value registered for the response header name

Arguments

NameTypeDescription
namestringHeader name

removeHeader(name)

Removes header name from the response headers.

setHeader(name, value)

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.

setHeaders(headers)

Adds multiple items to the response headers.

Arguments

NameTypeDescription
headersobjectAn object describing the headers to set

The setHeader method will be called for each item of the headers argument.

RequestContext

This constructor is used to create a connection context used by Request.

new RequestContext([options])

Arguments

NameTypeDescription
optionsobjectOptional initialization parameters

options may contain the following attributes:

NameTypeDescription
connectionobjectConnection information
tokenobjectKuzzle internal authorization token object
userobjectKuzzle internal user info object

Attributes

Writable

NameTypeDescription
connectionobjectConnection information
connectionIdstring(deprecated use connection.id instead) Client's connection unique ID
protocolstring(deprecated use connection.protocol instead) Network protocol name
tokenobjectKuzzle internal authorization token object
userobjectKuzzle internal user info object
RequestContext.Connection object format
NameTypeDescription
idstringConnection unique identifier
protocolstringProtocol name (e.g. 'http', 'websocket', 'mqtt', ...)
ipsarrayArray of known IP addresses for the connection
miscobjectContain additional connection properties, depending on the connection's protocol used (for instance, input HTTP headers)

RequestInput

Contains the request's input data

new RequestInput(data)

Arguments

NameTypeDescription
dataobjectStandardized API request (see Websocket requests for instance)

data may contain some or all of the following attributes:

NameTypeDescription
_idstringDocument unique identifier
actionstringKuzzle action to perform
bodyobjectContains request specific data (document content, search queries, ...)
collectionstringData collection
controllerstringKuzzle controller handling the action to perform
indexstringData index
volatileobjectClient's request specific volatile data
jwtstringJWT Authentication token

Other attributes may be defined and will automatically be added to the args object.

Attributes

Writable

NameTypeDefaultDescription
actionstringnullController's action to execute
argsobject(empty)Contains specific request arguments
bodyobjectnullRequest's body (for instance, the content of a document)
headersobjectrequest input headers (e.g. HTTP headers for HTTP or Websocket protocols)
controllerstringnullKuzzle's controller to invoke
volatileobjectnullRequest volatile data
resource._idstringnullDocument unique identifier
resource.collectionstringnullData collection
resource.indexstringnullData index
jwtstringnullJWT Authentication token

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.

const { { BadRequestError } = require('kuzzle-common-objects');

throw new BadRequestError('error message');

ExternalServiceError

Status Code: 500

Used when an external service answers to a request with an error other than a bad request or a service unavailable one.

const { ExternalServiceError } = require('kuzzle-common-objects');

throw new ExternalServiceError('error message');

ForbiddenError

Status Code: 403

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

const { ForbiddenError } = require('kuzzle-common-objects');

throw new ForbiddenError('error message');

GatewayTimeoutError

Status Code: 504

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

const { GatewayTimeoutError } = require('kuzzle-common-objects');

throw new GatewayTimeoutError('error message');

InternalError

Status Code: 500

Standard generic error. Used mainly for uncatched exceptions.

const { InternalError } = require('kuzzle-common-objects');

throw new InternalError('error message');

NotFoundError

Status Code: 404

Used when asked resources cannot be found.

const { NotFoundError } = require('kuzzle-common-objects');

throw new NotFoundError('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.

const { PartialError } = require('kuzzle-common-objects');

throw new PartialError('error message', [{this: 'failed'}, {andThis: 'failed too'}]);

PluginImplementationError

Status Code: 500

Used when a plugin fails.

const { PluginImplementationError } = require('kuzzle-common-objects');

throw new PluginImplementationError('error message');

ServiceUnavailableError

Status Code: 503

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

const { ServiceUnavailableError } = require('kuzzle-common-objects');

throw new ServiceUnavailableError('error message');

SizeLimitError

Status Code: 413

Used to notify about requests exceeding maximum limits.

const { SizeLimitError } = require('kuzzle-common-objects');

throw new SizeLimitError('error message');

UnauthorizedError

Status Code: 401

Used when a user fails a login attempt.

const { UnauthorizedError } = require('kuzzle-common-objects');

throw new UnauthorizedError('error message');
5.0.2

4 years ago

5.0.0

4 years ago

4.2.0

4 years ago

4.1.1

4 years ago

4.1.0

4 years ago

3.0.17

5 years ago

4.0.1

5 years ago

4.0.0

5 years ago

3.0.16

5 years ago

3.0.15

5 years ago

3.0.14

5 years ago

3.0.13

6 years ago

3.0.12

6 years ago

3.0.11

6 years ago

3.0.10

6 years ago

3.0.9

6 years ago

3.0.8

6 years ago

3.0.7

6 years ago

3.0.6

7 years ago

3.0.5

7 years ago

3.0.4

7 years ago

3.0.3

7 years ago

3.0.2

7 years ago

3.0.1

7 years ago

3.0.0

7 years ago

2.1.3

7 years ago

2.1.2

7 years ago

2.1.1

7 years ago

2.1.0

7 years ago

2.0.1

7 years ago

2.0.0

7 years ago

1.0.6

7 years ago

1.0.5

8 years ago

1.0.4

8 years ago

1.0.3

8 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago