bl-getting-started
Tutorials /

Get Started with Business Logic

This tutorial is an introduction to help get started writing custom server code with Kinvey's Business Logic feature. You will add business logic to a collection that returns a JSON body and a valid HTTP response code. The business logic script will prevent any data being saved to the collection.

This tutorial assumes that you have

  1. Created a Kinvey app.
  2. Created a collection in the app.

Your first code

Let's start with the canonical "Hello, World!" example.

First, browse to Collection Hooks under Business Logic in the left sidebar and click Add a Hook. Next, select your collection name from the dropdown.

Navigate to Business Logic

Choose the onPreSave option to create a hook that will run before every save operation:

New Collection Hook

Update the function stub to have the following code:

function onPreSave(request,response,modules){
    response.body = {message: "Hello, World!"};
    response.complete(201);
}

and click Save.

Testing the Code

Open the Logs panel by clicking the Logs button in the top left of the editor. Then click Test, and check the logs panel for the result.

Test the Code

Logging

Often you need to see what is happening in your logic while it is running on your backend. The logger module gives you the ability to log data and access those logs.

Adding the New Code

Update your onPreSave hook to the following:

function onPreSave(request,response,modules){
    // Add logging capability
    var logger = modules.logger;

    // Log the parameter "name" passed in the request body
    logger.info(request.body.name);

    response.body = {message: "Hello, World!"};
    response.complete(201);
}

then click Save.

Testing the Code

Reveal the Test panel by clicking text Test, and add a request body with a name:

{"name": "Brian"}

then click the Send Request button. The Kinvey response will still be the same:

{
    "message": "Hello, World!"
}

But you should also see a log line with the the name you supplied.

Business Logic Log View

Getting Friendly

The final update you'll make in your Business Logic is to use a value in the request to build your response.

Updating the Code

Go back to the onPreSave hook and update your code to the following:

function onPreSave(request,response,modules){
    var logger = modules.logger;

    logger.info(request.body.name);

    response.body = {message: "Hello, " + request.body.name + "!"};
    response.complete(201);
}

Testing the Code

Send another test request just as you did previously, ensuring the request body still has a name property.

Hello World!

The Kinvey response will now be:

{
    "message": "Hello, Brian!"
}

For more examples of what you can do with Business Logic see our examples.

For complete details on all modules, the request object and the response object see the Business Logic Reference.