### Basic usage of the install method Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend/install/index.md Example of how to use the install method to register a task with an ID and a handler function. ```javascript await app.install('mappings-2.4.3', () => {}) ``` -------------------------------- ### Start the Kuzzle application and interact with the API Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/getting-started/write-application/index.md Start the Kuzzle application using Backend.start() and then interact with the Kuzzle API. This example creates a new index if it doesn't exist. ```javascript app.start() .then(async () => { // Interact with Kuzzle API to create a new index if it does not already exist if (! await app.sdk.index.exists('nyc-open-data')) { await app.sdk.index.create('nyc-open-data'); } }) .catch(console.error); ``` -------------------------------- ### install Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend/install/index.md Registers code to be executed once on application startup for a given environment. If the handler throws an error, the application will not start. ```APIDOC ## install ### Description Registers code executed when the application starts, and only once on any given environment. Once successfully executed, the code associated to an install identifier will never be run again on that environment. ::: info If this method throws, the application won't start. ::: ### Method Signature ```ts install (id: string, handler: () => Promise, description?: string): void ``` ### Usage Example ```js await app.install('mappings-2.4.3', () => {}) ``` ``` -------------------------------- ### Complete Kuzzle Application Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/getting-started/write-application/index.md Instantiate a Kuzzle backend, register a controller with an action, start the application, and interact with the Kuzzle API to create an index. ```javascript import { Backend } from 'kuzzle'; // Instantiate an application const app = new Backend('playground'); // Now we can register features // Register a new controller app.controller.register('greeting', { actions: { sayHello: { handler: async request => { return `Hello, ${request.input.args.name}` } } } }); // Start the application app.start() .then(async () => { // Now we can interact with Kuzzle API // Interact with Kuzzle API to creates a new index if it does not exists if (! await app.sdk.index.exists('nyc-open-data')) { await app.sdk.index.create('nyc-open-data'); } }) .catch(console.error); ``` -------------------------------- ### Start Kuzzle Development Stack (Elasticsearch 7) Source: https://github.com/kuzzleio/kuzzle/blob/master/CONTRIBUTING.md Clone the repository and start a Kuzzle cluster with development tools enabled, using Elasticsearch 7. Ensure Docker and Docker Compose are installed. ```bash git clone git@github.com:kuzzleio/kuzzle.git cd kuzzle docker compose -f docker-compose.yml up ``` -------------------------------- ### start Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend/start/index.md Starts the application. Returns a Promise resolving when the application is running. ```APIDOC ## start ### Description Starts the application. Once the promise returned by this method resolves, the application is in the `running` phase. ### Method start(): Promise ### Returns Returns a Promise resolving when the application is running. ### Usage ```js try { await app.start() // Application is now in "running" phase } catch (error) { console.log(error) } ``` ``` -------------------------------- ### Basic Kuzzle Application Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/introduction/what-is-kuzzle/index.md Instantiate a new Kuzzle backend, register a controller with an action, and start the application. Ensure Kuzzle is properly installed and configured before running. ```javascript import { Backend } from 'kuzzle'; // Instantiate a new application const app = new Backend('playground'); // Declare a "greeting" controller app.controller.register('greeting', { actions: { // Declare a "sayHello" action sayHello: { handler: request => `Hello, ${request.input.args.name}` } } }); // Start the application app.start() .then(() => { app.log.info('Application started'); }); ``` -------------------------------- ### Define and Use a Controller Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend-controller/use/index.md Example of defining a custom controller class and registering it with the application using `app.controller.use()`. This must be done before the application starts. ```javascript import { KuzzleRequest, Controller } from 'kuzzle' class EmailController extends Controller { constructor (app) { super(app) this.definition = { actions: { send: { handler: this.send } } } } async send (request: KuzzleRequest) { // ... } } app.controller.use(new EmailController(app)) ``` -------------------------------- ### Response Example for createCredentials (local strategy) Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/security/create-credentials/index.md Example response when creating credentials using the 'local' authentication strategy. ```json { "status": 200, "error": null, "action": "createCredentials", "controller": "security", "_id": "", "result": { "username": "MyUser", "kuid": "" } } ``` -------------------------------- ### Example Permissions JSON Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/main-concepts/permissions/index.md An example JSON file defining roles, profiles, and users for loading permissions. ```json // permissions.json { "roles": { "driver": { "controllers": { "auth": { "actions": { "*": "*" } } } } }, "profiles": { "driver": { "policies": [ { "roleId": ["driver"] } ] } }, "users": { "aschen": { "content": { "profileIds": ["driver"] } } } } ``` -------------------------------- ### Get Role Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/security/get-role/index.md This is an example of a successful response when retrieving a role. It includes the role's `_id` and its `_source` definition. ```json { "status": 200, "error": null, "result": { "_id": "", "_source": { "controllers": { "*": { "actions": true } } } }, "action": "getRole", "controller": "security", "requestId": "" } ``` -------------------------------- ### HTTP Request Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/auth/get-my-rights/index.md This example demonstrates how to retrieve user rights using an HTTP GET request. ```APIDOC ## GET /_me/_rights ### Description Returns the exhaustive list of granted or denied rights for the currently logged in user. ### Method GET ### Endpoint http://kuzzle:7512/_me/_rights ### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **hits** (array) - An array of objects, each detailing a specific right. - **controller** (string) - The API controller the right applies to. - **action** (string) - The action within the controller. - **index** (string) - The index the right applies to. - **collection** (string) - The collection within the index. - **value** (string) - The right granted ('allowed') or denied ('denied'). ### Response Example ```json { "status": 200, "error": null, "result": { "hits": [ { "controller": "document", "action": "get", "index": "foo", "collection": "bar", "value": "allowed" } ] } } ``` ``` -------------------------------- ### Example Response Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/security/get-credential-fields/index.md This is an example of a successful response when querying credential fields for the 'local' strategy. ```json { "status": 200, "error": null, "action": "getCredentialFields", "controller": "security", "result": ["username", "password"] } ``` -------------------------------- ### Usage Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend-plugin/get/index.md Example of how to retrieve the 'mailer' plugin instance and cast it to a `MailerPlugin` type. ```javascript const mailerPlugin = app.plugin.get('mailer'); ``` -------------------------------- ### Set Configuration Value Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend-config/set/index.md Example of setting a configuration value for 'limits.documentsWriteCount' to 1000. ```javascript app.config.set('limits.documentsWriteCount', 1000) ``` -------------------------------- ### Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/memory-storage/del/index.md This is an example of a successful response when deleting keys. It indicates the number of keys that were deleted. ```javascript { "requestId": "", "status": 200, "error": null, "controller": "ms", "action": "del", "collection": null, "index": null, "result": 3 } ``` -------------------------------- ### Install Dependencies for Development Source: https://github.com/kuzzleio/kuzzle/blob/master/vagrant/plugins/vagrant-reload/README.md Use Bundler to install the necessary dependencies for developing the vagrant-reload plugin. ```bash bundle ``` -------------------------------- ### Join response example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/realtime/join/index.md This is an example of the response received after successfully joining a subscription. It includes the `roomId` and `channel` identifiers for the re-established subscription. ```javascript { "status": 200, "error": null, "index": null, "collection": null, "controller": "realtime", "action": "subscribe", "volatile": {}, "requestId": "", "result": { "channel": "", "roomId": "" } } ``` -------------------------------- ### Basic Kuzzle application structure Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/getting-started/run-kuzzle/index.md The `app.ts` file contains the core logic to start a Kuzzle application. It initializes the Backend and starts the server. ```typescript import { Backend } from "kuzzle"; const app = new Backend("playground"); app .start() .then(() => { app.log.info("Application started"); }) .catch(console.error); ``` -------------------------------- ### Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/auth/update-self/index.md Example of a successful response from the updateSelf API. It includes the user's _id and any updated _source properties. ```json { "status": 200, "error": null, "action": "updateSelf", "controller": "auth", "requestId": "", "result": { "_id": "", "_source": { "fullname": "Walter Smith" } } } ``` -------------------------------- ### List Subscriptions - Example Response Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/realtime/list/index.md This is an example of a successful response when listing subscriptions, showing subscription identifiers and their active connection counts. ```json { "error": null, "status": 200, "index": null, "collection": null, "controller": "realtime", "action": "list", "requestId": "", "result": { "": { "": { "afcd909773f197ab859447594bfbd154": 12, "4adbc1948ac4dc84ac89d14b488bcad1": 4 }, "": { "bcd4ab54cdb4ad5b464ba4cd4564dc46": 1 } }, "": { "": { "5fad4034eed4dc84ac40dc4b48dcdad23": 35 } } } } ``` -------------------------------- ### Create User with Local Credentials (Example) Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/main-concepts/authentication/index.md This example demonstrates creating a user with local credentials, including username and password. These credentials will be securely stored by the 'local' strategy plugin. ```bash kourou security:createUser '{ content: { profileIds: ["default"] }, credentials: { local: { username: "mylehuong", password: "password" } } }' ``` -------------------------------- ### Create Index and Collection, then Subscribe to Notifications Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/main-concepts/realtime-engine/index.md Use Kourou to create the necessary index and collection, then use wscat to subscribe to real-time database notifications for that collection. Ensure the index and collection exist before subscribing. ```bash # Creates index and collection kourou collection:create nyc-open-data yellow-taxi # Subscribes to database notifications npx wscat -c ws://localhost:7512 --wait 300 --execute '{ "controller": "realtime", "action": "subscribe", "index": "nyc-open-data", "collection": "yellow-taxi", "body": {} }' ``` -------------------------------- ### HTTP mget Request Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/memory-storage/mget/index.md Example of how to make an HTTP GET request to retrieve multiple keys using the mget endpoint. ```http URL: http://kuzzle:7512/ms/_mget?keys=key1,key2,... Method: GET ``` -------------------------------- ### Search Documents Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/getting-started/store-and-access-data/index.md This example demonstrates how to search for documents. It shows the connection status and the retrieved documents with their IDs and content. ```bash 🚀 Kourou - Searches for documents [ℹ] Connecting to ws://localhost:7512 ... [ℹ] Document ID: leGnvZIBq6PFWFR7wmw8 Content: { "name": "Melis-7", "city": "Antalya", "age": 32, "_kuzzle_info": { "author": "-1", "createdAt": 1729758741051, "updatedAt": null, "updater": null } } [ℹ] Document ID: l-GnvZIBq6PFWFR7wmxD Content: { "name": "Melis-9", "city": "Antalya", "age": 34, "_kuzzle_info": { "author": "-1", "createdAt": 1729758741059, "updatedAt": null, "updater": null } } [✔] 2 documents fetched on a total of 2 ``` ```bash 🚀 Kourou - Searches for documents [ℹ] Connecting to http://localhost:7512 ... [ℹ] Document ID: OYgZJnUBacNMjDl2504F Content: { "name": "Melis-7", "city": "Antalya", "age": 32, "_kuzzle_info": { "author": "-1", "createdAt": 1602662033156, "updatedAt": null, "updater": null } } [ℹ] Document ID: O4gZJnUBacNMjDl2504n Content: { "name": "Melis-9", "city": "Antalya", "age": 34, "_kuzzle_info": { "author": "-1", "createdAt": 1602662033189, "updatedAt": null, "updater": null } } [✔] 2 documents fetched on a total of 2 ``` -------------------------------- ### Instantiate and use a plugin Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend-plugin/use/index.md Example of how to define a plugin class and then use it with the application's plugin manager. ```javascript import { Plugin, PluginContext, JSONObject } from 'kuzzle' class MailerPlugin extends Plugin { constructor () { } async init (config: JSONObject, context: PluginContext) { this.config = config; this.context = context; } } app.plugin.use(new MailerPlugin()) ``` -------------------------------- ### Get the search body Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/kuzzle-request/get-search-body/index.md Call the getSearchBody() method on a KuzzleRequest object to retrieve the search body. This method is available starting from Kuzzle version 2.11.0. ```typescript const searchBody = request.getSearchBody(); ``` -------------------------------- ### Get Server Statistics Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/server/get-stats/index.md Retrieves statistics snapshots for the server. You can filter the results by providing a start and end time in milliseconds since the Unix epoch. ```APIDOC ## GET /_getStats ### Description Returns statistics snapshots within a provided timestamp range. ### Method GET ### Endpoint http://kuzzle:7512/_getStats #### Query Parameters - **startTime** (Epoch-millis) - Optional - The start of the time range for statistics snapshots. - **stopTime** (Epoch-millis) - Optional - The end of the time range for statistics snapshots. ### Response #### Success Response (200) - **total** (integer) - Total number of available snapshots. - **hits** (array) - Array of statistic snapshots. Each snapshot contains: - **completedRequests** (object) - Completed requests, per network protocol. - **connections** (object) - Number of active connections, per network protocol. - **failedRequests** (object) - Failed requests, per network protocol. - **ongoingRequests** (object) - Requests underway, per network protocol. - **timestamp** (integer) - Snapshot timestamp, in Epoch-millis format. ### Response Example ```json { "status": 200, "error": null, "action": "getStats", "controller": "server", "requestId": "", "result": { "total": 1, "hits": [ { "completedRequests": { "websocket": 148, "http": 24, "mqtt": 78 }, "failedRequests": { "websocket": 3 }, "ongoingRequests": { "mqtt": 8, "http": 2 }, "connections": { "websocket": 13 }, "timestamp": 1453110641308 } ] } } ``` ``` -------------------------------- ### Example: Registering a greeting controller Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend-controller/register/index.md This example demonstrates how to register a controller named 'greeting' with a 'sayHello' action. The action is configured to respond to POST requests. ```javascript import { KuzzleRequest } from 'kuzzle' app.controller.register('greeting', { actions: { sayHello: { handler: async (request: KuzzleRequest) => `Hello, ${request.input.args.name}`, http: [{ verb: 'post', path: 'greeting/hello/:name', openapi: { description: "Simply say hello", parameters: [{ in: "path", name: "name", schema: { type: "string" }, required: true, }], responses: { 200: { description: "Custom greeting", content: { "application/json": { schema: { type: "string", } } } } } } }] } } }) ``` -------------------------------- ### init Method Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/write-protocols/methods/init/index.md Initializes the protocol. Called once during Kuzzle startup. ```APIDOC ## init(entryPoint, context) ### Description Initializes the protocol. Called once, during Kuzzle startup. ### Parameters #### Path Parameters * **entryPoint** (`EntryPoint`) - Required - Provides an interface to protocol related methods. * **context** (`context`) - Required - Generic interface exposing objects and methods not directly related to the network layer. ### Return The `init` function can optionally return a promise. If it does, Kuzzle waits for the promise to be resolved before continuing its own initialization. If a promise is returned and rejected, or if the `init` function throws an error, Kuzzle aborts its start sequence and shuts down. ``` -------------------------------- ### Get Profile Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/security/get-profile/index.md A successful response includes the profile's `_id` and its `_source` content, which details its configuration like rate limits and policies. ```json { "status": 200, "error": null, "result": { "_id": "", "_source": { "rateLimit": 50, "policies": [ { "roleId": "" }, { "roleId": "", "restrictedTo": [ { "index": "" }, { "index": "", "collections": [ "", "" ] } ] } ] }, "action": "getProfile", "controller": "security", "requestId": "" } } ``` -------------------------------- ### Example Response for getCredentials (local strategy) Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/security/get-credentials/index.md This is an example of a successful response when retrieving credentials using the 'local' authentication strategy. It includes user details like username and kuid. ```json { "status": 200, "error": null, "action": "getCredentials", "controller": "security", "_id": "", "result": { "username": "MyUser", "kuid": "" } } ``` -------------------------------- ### Get Server Info via HTTP Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/server/info/index.md Use this endpoint to retrieve server information over HTTP. No specific setup is required beyond a running Kuzzle instance. ```http URL: http://kuzzle:7512 URL(2): http://kuzzle:7512/_serverInfo Method: GET ``` -------------------------------- ### Example Response with Local Strategy Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/auth/get-my-credentials/index.md This is an example of a successful response when using the 'local' authentication strategy. It includes user details like username and KUID. ```json { "status": 200, "error": null, "action": "getMyCredentials", "controller": "auth", "result": { "username": "MyUser", "kuid": "" } } ``` -------------------------------- ### Greeting Controller Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/develop-on-kuzzle/api-controllers/index.md This example demonstrates how to register a 'greeting' controller with a 'sayHello' action that handles POST requests to '/greeting/hello/:name'. It shows how to access request arguments and body within the handler. ```APIDOC ## POST greeting/hello/:name ### Description Handles a greeting request, extracting parameters like `_id`, `name`, `age`, and the request body. ### Method POST ### Endpoint /greeting/hello/:name ### Parameters #### Path Parameters - **name** (string) - Required - The name to greet. #### Query Parameters - **_id** (string) - Required - A unique identifier for the request. - **age** (integer) - Optional - The age of the person. #### Request Body - **city** (string) - Required - The city of the person. ### Request Example ```bash curl \ -X POST \ -H "Content-Type: application/json" \ "localhost:7512/_/greeting/hello/aschen?_id=JkkZN62jLSA&age=27" \ --data '{ "city" : "Antalya" }' ``` ### Response #### Success Response (200) This endpoint does not explicitly define a success response body in the documentation. The handler logic focuses on assertions. ### KuzzleRequest Access Example ```js import assert from 'assert'; app.controller.register('greeting', { actions: { sayHello: { handler: async (request: KuzzleRequest) => { assert(request.input.args._id === 'JkkZN62jLSA'); assert(request.input.args.name === 'aschen'); assert(request.input.args.age === '27'); assert(request.input.body.city === 'Antalya'); // equivalent to assert(request.getId() === 'JkkZN62jLSA'); assert(request.getString('name') === 'aschen'); assert(request.getInteger('age') === '27'); assert(request.getBodyString('city') === 'Antalya'); }, http: [ { verb: 'POST', path: 'greeting/hello/:name' } ] } } }); ``` ``` -------------------------------- ### Check admin existence via HTTP Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/server/admin-exists/index.md Use this HTTP GET request to check if an administrator account exists. No specific setup is required beyond having Kuzzle running. ```http URL: http://kuzzle:7512/_adminExists Method: GET ``` -------------------------------- ### Get Public API Routes Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/server/public-api/index.md Retrieves a list of all available API routes, including those provided by Kuzzle core and installed plugins. This is essential for SDKs to dynamically build requests. ```APIDOC ## GET /_publicApi ### Description Returns an object containing the definition of the available API. Each key matches an API controller. ### Method GET ### Endpoint /_publicApi ### Query Parameters None ### Request Body None ### Response #### Success Response (200) - **result** (object) - An object where keys are controller names and values are objects defining the actions within each controller, including their HTTP endpoints. ### Response Example { "status": 200, "error": null, "controller": "server", "action": "publicApi", "result": { "auth": { "login": { "controller": "auth", "action": "login", "http": [ { "url": "/_login/:strategy", "verb": "GET" }, { "url": "/_login/:strategy", "verb": "POST" } ] } }, "plugin-test/example": { "liia": { "controller": "plugin-test/example", "action": "liia", "http": [ { "url": "_plugin/plugin-test/liia", "verb": "GET" } ] } } } } ``` -------------------------------- ### Intercept Document Fetching Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/events/generic-document/index.md Use the 'generic:document:beforeGet' pipe to intercept document fetching. This example prevents fetching documents with IDs starting with 'foobar_' in the 'foo:bar' collection. ```javascript class PipePlugin { init(customConfig, context) { this.pipes = { 'generic:document:beforeGet': async (documents, request) => { // The "documents" argument contains the documents about to be // fetched. // // Example: refuses to fetch documents with ids starting with "foobar_" // in collection foo:bar const { index, collection } = request.input.args; if (index === 'foo' && collection === 'bar') { for (const document of documents) { if (document._id.startsWith('foobar_')) { throw context.errors.ForbiddenError('Cannot fetch foobar documents'); } } } return documents; } }; } } ``` -------------------------------- ### Create a user using the API Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/getting-started/set-up-permissions/index.md Use the `security:createUser` API action to create a new user. This example creates a user named `dummyUser` associated with the `dummyProfile` and sets up local credentials. ```bash curl -XPOST http://localhost:7512/users/dummyUser/_create \ -H 'Content-Type: application/json'\ -d '{ "content": { "profileIds": ["dummyProfile"] }, "credentials": { "local": { "username": "melis", "password": "password" } } }' ``` -------------------------------- ### HTTP Request Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/security/search-api-keys/index.md This example demonstrates how to search for API keys using an HTTP POST request. It includes a sample request body with a match query. ```APIDOC ## POST /users//api-keys/_search ### Description Searches for API keys belonging to a specific user. ### Method POST ### Endpoint http://kuzzle:7512/users//api-keys/_search ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user whose API keys are to be searched. #### Query Parameters - **from** (integer) - Optional - The offset from the first result to fetch. - **size** (integer) - Optional - The maximum number of API keys to return in a single response page. - **lang** (string) - Optional - Specifies the query language. Defaults to `elasticsearch`. `koncorde` can also be used. ### Request Body - **match** (object) - Optional - A query object to filter the API keys. If empty, all API keys for the user are returned. - **description** (string) - Example filter for the description field. ### Request Example ```json { "match": { "description": "sigfox" } } ``` ### Response #### Success Response (200) - **total** (integer) - The total number of API keys found. - **hits** (array) - An array of objects, each representing a found API key. - **_id** (string) - The ID of the API key. - **_source** (object) - The content of the API key (excluding the token). - **userId** (string) - The user's KUID. - **expiresAt** (integer) - The expiration date in UNIX micro-timestamp format (-1 if never expires). - **ttl** (integer) - The original time-to-live. - **description** (string) - The description of the API key. - **fingerprint** (string) - The SHA256 hash of the authentication token. #### Response Example ```json { "status": 200, "error": null, "action": "searchApiKeys", "controller": "security", "requestId": "", "result": { "total": 2, "hits": [ { "_id": "api-key-1", "_source": { "userId": "mWakSm4BWtbu6xy6NY8K", "expiresAt": -1, "ttl": -1, "description": "Sigfox callback authentication token", "fingerprint": "4ee98cb8c614e99213e7695f822e42325d86c93cfaf39cb40e860939e784c8e6" } }, { "_id": "api-key-1", "_source": { "userId": "mWakSm4BWtbu6xy6NY8K", "expiresAt": -1, "ttl": -1, "description": "Another key", "fingerprint": "abcdef123456..." } } ] } } ``` ``` -------------------------------- ### Successful Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/document/get/index.md A successful GET request returns a JSON object containing the document's metadata and its source content. The `_source` property holds the actual document data. ```json { "status": 200, "error": null, "index": "", "collection": "", "controller": "document", "action": "get", "requestId": "", "result": { "_id": "", "_version": 1, "_source": { "name": { "first": "Steve", "last": "Wozniak" }, "hobby": "Segway polo", "_kuzzle_info": { "author": "Bob", "createdAt": 1481816934209, "updatedAt": null, "updater": null } } } } ``` -------------------------------- ### Readiness Endpoint Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/main-concepts/api/index.md Kuzzle exposes a readiness endpoint at GET /_ready. It returns a 200 status code if the server is running and ready, and a 503 status code if the server is starting, shutting down, unhealthy, or overloaded. ```APIDOC ## GET /_ready ### Description Checks if the Kuzzle server is running and ready to accept new incoming requests. Useful for readiness probes in containerized environments. ### Method GET ### Endpoint /_ready ### Response #### Success Response (200) Indicates the Kuzzle server is healthy and ready. #### Error Response (503) Indicates the Kuzzle server is not ready due to: - Node starting procedure not finished. - Node is shutting down. - Cluster does not have enough healthy nodes. - Kuzzle server is overloaded. ``` -------------------------------- ### Greeting Controller Example (Other Protocols) Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/develop-on-kuzzle/api-controllers/index.md This example shows how to invoke the 'sayHello' action using other protocols like WebSockets, sending a JSON payload that includes controller, action, and request details. ```APIDOC ### Other protocols Other protocols directly **use JSON payloads**. These payloads contain all the information directly: ```bash npx wscat -c ws://localhost:7512 --execute '{ "controller": "greeting", "action": "sayHello", "_id": "JkkZN62jLSA", "age": 27, "name": "aschen", "body": { "city": "Antalya" } }' ``` We can retrieve them in the [KuzzleRequest](/core/2/framework/classes/kuzzle-request) object passed to the `handler`: ```js import assert from 'assert'; app.controller.register('greeting', { actions: { sayHello: { handler: async (request: KuzzleRequest) => { assert(request.input.args._id === 'JkkZN62jLSA'); assert(request.input.args.name === 'aschen'); assert(request.input.args.age === '27'); assert(request.input.body.city === 'Antalya'); // equivalent to assert(request.getId() === 'JkkZN62jLSA'); assert(request.getString('name') === 'aschen'); assert(request.getInteger('age') === '27'); assert(request.getBodyString('city') === 'Antalya'); }, } } }); ``` ``` -------------------------------- ### sscan Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/memory-storage/sscan/index.md Iterates incrementally over members contained in a set of unique values, using a cursor. An iteration starts when the cursor is set to 0. To get the next page of results, re-send the request with the updated cursor position. The scan ends when the cursor returned by the server is 0. ```APIDOC ## GET /ms/_sscan/<_id?cursor=[&match=][&count=] ### Description Iterates incrementally over members contained in a set of unique values, using a cursor. ### Method GET ### Endpoint /ms/_sscan/<_id> ### Parameters #### Query Parameters - **cursor** (integer) - Required - The cursor offset for the iteration. - **match** (string) - Optional - Search only keys matching the provided pattern. - **count** (integer) - Optional - Approximate number of items per result set (default is 10). ### Response #### Success Response (200) - **result** (array) - An array containing two elements: a new cursor position (0 when at the end) and an array of found keys. ### Response Example ```json { "requestId": "", "status": 200, "error": null, "controller": "ms", "action": "sscan", "collection": null, "index": null, "result": [ 13, [ "member1", "member2", "..." ] ] } ``` ``` -------------------------------- ### get Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend-errors/get/index.md Get a standardized KuzzleError ```APIDOC ## get ### Description Get a standardized KuzzleError. ### Method ```js get (domain: string, subDomain: string, name: string, placeholders: any[]): KuzzleError ``` ### Parameters #### Path Parameters - **domain** (string) - Required - Domain name - **subDomain** (string) - Required - Subdomain name - **name** (string) - Required - Standard error name - **placeholders** (any[]) - Required - Other placeholder arguments ``` -------------------------------- ### Create a user using the CLI Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/getting-started/set-up-permissions/index.md Use the `kourou security:createUser` command to create a new user. This example creates a user named `dummyUser` associated with the `dummyProfile` and sets up local credentials. ```bash kourou security:createUser '{ content: { profileIds: ["dummyProfile"] }, credentials: { local: { username: "melis", password: "password" } } }' ``` -------------------------------- ### Install vagrant-reload Plugin Source: https://github.com/kuzzleio/kuzzle/blob/master/vagrant/plugins/vagrant-reload/README.md Install the vagrant-reload plugin using the Vagrant CLI. ```bash vagrant plugin install vagrant-reload ``` -------------------------------- ### Registering a Controller and Action Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/develop-on-kuzzle/api-controllers/index.md This example shows how to register a new controller named 'greeting' with an action 'sayHello'. The handler function processes the request and returns a personalized greeting. ```APIDOC ## Handler Function The handler is the function that will **be called each time our API action is executed**. This function **takes a [KuzzleRequest](/core/2/framework/classes/kuzzle-request) object** as a parameter and **must return a Promise** resolving on the result to be returned to the client. This function is defined in the `handler` property of an action. Its signature is: `(request: KuzzleRequest) => Promise`. ```js app.controller.register('greeting', { actions: { sayHello: { // Handler function for the "greeting:sayHello" action handler: async (request: KuzzleRequest) => { return `Hello, ${request.getString('name')}`; } } } }); ``` The result returned by our `handler` will be **converted to JSON format** and integrated into the standard Kuzzle response in the `result` property. ```bash npx wscat -c ws://localhost:7512 --execute '{ "controller": "greeting", "action": "sayHello", "name": "Yagmur" }' { "requestId": "a6f4f5b6-1aa2-4cf9-9724-12b12575c047", "status": 200, "error": null, "controller": "greeting", "action": "sayHello", "collection": null, "index": null, "volatile": null, "result": "Hello, Yagmur", # <= handler function return value "room": "a6f4f5b6-1aa2-4cf9-9724-12b12575c047" } ``` ``` -------------------------------- ### init(config, context) Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/abstract-classes/plugin/init/index.md Abstract method to initialize the plugin. It receives configuration and a plugin context. It can optionally return a promise that Kuzzle will wait for before continuing its initialization. ```APIDOC ## init(config, context) ### Description Plugins must expose an `init` function. If it is missing, Kuzzle fails to load the plugin and aborts its start sequence. The `init` method is called once during startup, and it is used to initialize the plugin. ### Parameters #### Path Parameters - **config** (JSONObject) - Required - Contains the custom plugin configuration - **context** (PluginContext) - Required - The plugin context, exposing various accessors, constructors, and helpers. ### Return The `init` function can optionally return a promise. If it does, Kuzzle waits for the promise to be resolved before continuing its own initialization. If a promise is returned and rejected, or if the `init` function throws an error, Kuzzle aborts its start sequence and shuts down. ``` -------------------------------- ### Example Document Creation and Notification Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/getting-started/subscribe-realtime-notifications/index.md This example shows the JSON payload for creating a new document and the subsequent realtime notification received in the terminal, including details about the API action and the document's source. ```json { "name": "Nerwin", "city": "Montreal", "age": 26 } ``` ```text 🚀 Kourou - Subscribes to realtime notifications [ℹ] Connecting to ws://localhost:7512 ... [ℹ] Waiting for realtime notifications on "nyc-open-data":"yellow-taxi" ... [ℹ] New notification triggered by API action "document:create" { "_id": "dvIdJ3UB1MqPtuLKxKDS", "_source": { "name": "Nerwin", "city": "Montreal", "age": 26, "_kuzzle_info": { "author": "-1", "createdAt": 1602679063751, "updatedAt": null, "updater": null } }, "_version": 1 } ``` -------------------------------- ### Registering a Realtime Subscription Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend-subscription/add/index.md Example of how to use the `app.subscription.add` method to register a new realtime subscription. It demonstrates passing connection details, index, collection, filters, and subscription options like `users`, `scope`, and `volatile` data. ```javascript const { roomId, channel } = await app.subscription.add( request.context.connection, "lamaral", "windsurf", { range: { wind: { gte: 20 } }, }, { users: "all", scope: "in", volatile: { name: "Aschen" }, } ); ``` -------------------------------- ### HTTP Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/auth/create-my-credentials/index.md Example of a successful response when creating credentials using the 'local' authentication strategy via HTTP. Includes the status, action, controller, and the created user's details. ```json { "status": 200, "error": null, "action": "createMyCredentials", "controller": "auth", "result": { "username": "MyUser", "kuid": "" } } ``` -------------------------------- ### Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/realtime/validate/index.md This is an example of a successful response. The 'valid' property indicates if the data passed validation. ```json { "status": 200, "error": null, "index": "", "collection": "", "controller": "realtime", "action": "validate", "result": { "valid": true } } ``` -------------------------------- ### zscore Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/memory-storage/zscore/index.md This is an example of a successful response when retrieving the score of a member from a sorted set. ```json { "requestId": "", "status": 200, "error": null, "controller": "ms", "action": "zscore", "collection": null, "index": null, "result": 23 } ``` -------------------------------- ### Example Response for Local Strategy Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/security/get-credentials-by-id/index.md Presents a typical response structure when fetching credentials for the 'local' strategy, including username and KUID. ```json { "status": 200, "error": null, "action": "getCredentialsById", "controller": "security", "result": { "username": "johndoe@kuzzle.io", "kuid": "" } } ``` -------------------------------- ### Configure storageEngine with .kuzzlerc Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/guides/advanced/configuration/index.md Example of setting the storage engine host in a .kuzzlerc file. ```json { "services": { "storageEngine": { "client": { "host": "http://localhost:9200" } } } } ``` -------------------------------- ### Install method signature Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend/install/index.md Defines the signature for the install method, which registers an identifier and a handler function to be executed once. ```typescript install (id: string, handler: () => Promise, description?: string): void ``` -------------------------------- ### Create API Key using Kuzzle SDK Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/auth/create-api-key/index.md This example demonstrates creating an API key using the Kuzzle SDK. It includes the controller, action, and body with a description. Optional arguments like `_id`, `expiresIn`, and `refresh` can also be provided. ```javascript { "controller": "auth", "action": "createApiKey", "body": { "description": "Sigfox callback authentication api key" }, // optional arguments "_id": "api-key-id", "expiresIn": -1, "refresh": "wait_for" } ``` -------------------------------- ### in Filter Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/koncorde-filters-syntax/clauses/index.md Example of an 'in' filter matching documents where the 'firstName' field is either 'Grace' or 'Ada'. ```javascript { in: { firstName: ['Grace', 'Ada'] } } ``` -------------------------------- ### MQTT Client Interaction Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/protocols/mqtt/index.md This example demonstrates how two MQTT clients can interact using Kuzzle's MQTT protocol. Client 1 subscribes to the `Kuzzle/response` topic, while Client 2 publishes a request to the `Kuzzle/request` topic. Client 1 then receives the response. ```bash # client 1 $ mosquitto_sub -t Kuzzle/response ``` ```bash # client 2 $ mosquitto_pub -t Kuzzle/request -m '{"controller": "server", "action": "now"}' ``` ```bash # client 1 $ {"requestId":"83a63209-7633-4884-9f1a-c490ce446ddf","status":200,"error":null,"controller":"server","action":"now","collection":null,"index":null,"volatile":null,"result":{"now":1509967201489}} ``` -------------------------------- ### HTTP Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/auth/update-my-credentials/index.md An example of a successful response when updating credentials using the 'local' authentication strategy. It returns the updated user's username and KUID. ```json { "status": 200, "error": null, "action": "updateMyCredentials", "controller": "auth", "result": { "username": "MyUser", "kuid": "" } } ``` -------------------------------- ### mDeleteProfiles Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/security/m-delete-profiles/index.md This is an example of a successful response from the mDeleteProfiles action, listing the IDs of the profiles that were deleted. ```json { "status": 200, "error": null, "action": "mDeleteProfiles", "controller": "security", "requestId": "", "result": [ "profile1", "profile2", "..." ] } ``` -------------------------------- ### Instantiate and use a custom StorageClient Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/framework/classes/backend-storage/properties/index.md This example demonstrates how to create a new Elasticsearch client instance using `app.storage.Client`. You can optionally provide custom configuration via `clientConfig` to the constructor. ```javascript const esRequest = { body: { name: 'Aschen', age: 27 }, index: '&nyc-open-data.yellow-taxi', op_type: 'create' } // Instantiate and use a new client const storageClient = new app.storage.Client() await storageClient.index(esRequest) ``` -------------------------------- ### strlen Response Example Source: https://github.com/kuzzleio/kuzzle/blob/master/doc/2/api/controllers/memory-storage/strlen/index.md This is an example of a successful response from the strlen command, indicating the length of the string value. ```json { "requestId": "", "status": 200, "error": null, "controller": "ms", "action": "strlen", "collection": null, "index": null, "result": 6 } ```