You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 7-8.RSVP
Socket
Socket
Sign inDemoInstall

kuzzle-common-objects

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

kuzzle-common-objects

Common objects shared to various Kuzzle components and plugins


Version published
Weekly downloads
205
decreased by-11.64%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

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 object
errorKuzzleErrornull
inputRequestInputRequestInput object
responseRequestResponseResponse view of the request, standardized as the expected Kuzzle API response
result(varies)null
deprecationsobject[]undefined

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');

FAQs

Package last updated on 06 Nov 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc