Core
Guides v2.x
2

Create new Controllers #

The Kuzzle API is composed of actions grouped in controllers.
A controller is a logical container that groups several actions together.

Each action receives a KuzzleRequest object argument, and is in charge of returning a result which will be transmitted in the response.

Register a new Controller #

We are going to modify the app.ts file to register a controller to expose new API actions.

For this, we need to use the Backend.controller.register method.

You can also declare Controller class for a better code organization.

This method takes the controller name and a ControllerDefinition which defines the controller actions:

Copied to clipboard!
app.controller.register('greeting', {
  actions: {
    sayHello: {
      handler: async request => {
        return `Hello, ${request.getString('name')}`
      }
    }
  }
});

The code above will register a greeting controller with a sayHello action.
We defined a handler function that uses the name argument from the request and returns a Promise resolving to a string.

Kuzzle will generate a default HTTP route of the following format if none is provided:
GET /_/<controller-name>/<action-name>
Controller names and action names are converted to kebab-case in auto-generated URLs.
See our in-depth guide to learn how to declare your own HTTP routes

We can now test our new action: