Developing and Deploying LoopBack Applications with Appsody

Appsody helps developers build containerized applications for the cloud that are ready to be deployed to Kubernetes without the user needing to be an expert on the underlying container technology.

The LoopBack team has recently contributed the Node.js LoopBack stack which extends the Node.js stack and provides a powerful solution to build open APIs and Microservices in TypeScript with LoopBack, an open source Node.js API framework. It is based on LoopBack 4.

This tutorial is going to show you how to scaffold, run, stop, debug, and test a LoopBack 4 application in the Appsody development environment.

Prerequisites

In order to follow this tutorial, you need to install the Appsody CLI, which also requires you to have Docker installed.

Install the Appsody CLI

Follow the Installing Appsody guide to install the CLI for your platform.

Scaffolding a LoopBack 4 Application using Appsody

Using the Appsody CLI, you can quickly scaffold a LoopBack 4 application.

  1. Open a terminal window.

  2. Create a directory named appsodyLB4Todo:

    mkdir appsodyLB4Todo
    
  3. Navigate to that directory:

    cd appsodyLB4Todo
    
  4. List the available Appsody stacks (and templates) with:

    appsody list
    

    You should see the nodejs-loopback stack (and template) listed:

    REPO            ID                              VERSION         TEMPLATES               DESCRIPTION
    
    ...
    *incubator      nodejs-loopback                 0.3.0           *scaffold               LoopBack 4 API Framework for Node.js
    ...
    
  5. Scaffold a LoopBack 4 application in the current directory by using the appsody init command as follows:

    appsody init nodejs-loopback
    

    The output should look similar to the following:

    Checking stack requirements...
    Docker requirements met.
    Appsody requirements met.
    Running appsody init...
    Downloading nodejs-loopback template project from https://github.com/appsody/stacks/releases/download/nodejs-loopback-v0.3.0/incubator.nodejs-loopback.v0.3.0.templates.scaffold.tar.gz
    Download complete. Extracting files from /Users/helenmasters/appsodyLB4Todo/nodejs-loopback.tar.gz
    Setting up the development environment
    Your Appsody project name has been set to appsodylb4todo
    Pulling docker image docker.io/appsody/nodejs-loopback:0.3
    Running command: docker pull docker.io/appsody/nodejs-loopback:0.3
    0.3: Pulling from appsody/nodejs-loopback
    ...
    Status: Downloaded newer image for appsody/nodejs-loopback:0.3
    Running command: docker run --rm --entrypoint /bin/bash docker.io/appsody/nodejs-loopback:0.3 -c "find /project -type f -name .appsody-init.sh"
    Successfully initialized Appsody project with the nodejs-loopback stack and the default template.
    

    The most important lines to make note of are:

    Your Appsody project name has been set to appsodylb4todo
    
    and
    
    Successfully initialized Appsody project with the nodejs-loopback stack and the default template.
    
  6. Install all the dependencies of this application with:

    npm install
    
  7. Now that all the dependencies are installed, open this project in your favorite IDE.

    This tutorial is going to use VS Code:

    code .
    
  8. The basic structure of the application looks like this:

    lb4appsody_template_files_1.png

    One important file is the Appsody configuration file for your project, which is named .appsody-config.yaml. It defines the name of your project, and the stack on which it is based.

    project-name: appsodylb4todo
    stack: appsody/nodejs-loopback:0.3
    
  9. The source code for the LoopBack 4 application is located in the src directory.

    lb4appsody_template_files_2.png

  10. This basic application only defines one API endpoint '/ping' in the file src/controllers/ping.controller.ts

    The initial application is very similar to the one generated by the 'lb4 app' command, but it's going to be a loaded by a facade that sets up health and metrics for cloud native observability.

In the next section, you are going to add more API endpoints.

Building Your Application

The template application is only a starting point.

Now you are going to build a more realistic LoopBack 4 application.

You are going to use the todo list application from the Todo Tutorial as an example.

Add the Todo model

To add the Todo model you need the 'lb4' application generator installed.

Install the Loopback 4 CLI

Install the LoopBack 4 command line interface by entering the following command:

npm i -g @loopback/cli

Create the Todo model

Create the Todo model using:

lb4 model

You are prompted with different questions. Specify the responses as follows:

? Model class name: todo
? Please select the model base class: Entity (A persisted m
odel with an ID)
? Allow additional (free-form) properties? No
Model Todo will be created in src/models/todo.model.ts

Let's add a property to Todo
Enter an empty property name when done

? Enter the property name: id
? Property type: number
? Is id the ID property? Yes
? Is id generated automatically? Yes

Let's add another property to Todo
Enter an empty property name when done

? Enter the property name: title
? Property type: string
? Is it required?: Yes
? Default value [leave blank for none]:

Let's add another property to Todo
Enter an empty property name when done

? Enter the property name: desc
? Property type: string
? Is it required?: No
? Default value [leave blank for none]:

Let's add another property to Todo
Enter an empty property name when done

? Enter the property name: isComplete
? Property type: boolean
? Is it required?: No
? Default value [leave blank for none]:

Let's add another property to Todo
Enter an empty property name when done

You are not going to add further properties, so just hit the ENTER key at this point. The output is then generated as follows:

? Enter the property name:
  create src/models/todo.model.ts
  update src/models/index.ts

Model Todo was created in src/models/

Add a Datasource

  1. Next, create a datasource for an in-memory database by using:

    lb4 datasource
    

    You are prompted with different questions. Specify the responses as follows:

    ? Datasource name: db
    ? Select the connector for db: In-memory db (supported by StrongLoop)
    ? window.localStorage key to use for persistence (browser only):
    ? Full path to file for persistence (server only): ./data/db.json
    create src/datasources/db.datasource.config.json
    create src/datasources/db.datasource.ts
    update src/datasources/index.ts
    
    Datasource Db was created in src/datasources/
    
  2. Create a folder named: /appsodyLB4Todo/data

  3. Create a file named: /appsodyLB4Todo/data/db.json

  4. Place the following content inside db.json:

    {
      "ids": {
        "Todo": 5
      },
      "models": {
        "Todo": {
          "1": "{\"title\":\"Take over the galaxy\",\"desc\":\"MWAHAHAHAHAHAHAHAHAHAHAHAHAMWAHAHAHAHAHAHAHAHAHAHAHAHA\",\"id\":1}",
          "2": "{\"title\":\"destroy alderaan\",\"desc\":\"Make sure there are no survivors left!\",\"id\":2}",
          "3": "{\"title\":\"play space invaders\",\"desc\":\"Become the very best!\",\"id\":3}",
          "4": "{\"title\":\"crush rebel scum\",\"desc\":\"Every.Last.One.\",\"id\":4}"
        }
      }
    }
    

Add a Repository

Next, add a repository to handle the database CRUD functions of the Todo model by using:

lb4 repository

You are prompted with different questions. Specify the responses as follows:

? Please select the datasource: DbDatasource
? Select the model(s) you want to generate a repository: Todo
? Please select the repository base class: DefaultCrudRepository (Legacy juggler bridge)
   create src/repositories/todo.repository.ts
   update src/repositories/index.ts

Repository TodoRepository was created in src/repositories/

Add a Controller

Now, create a controller to define and handle the request-response lifecycle for our API endpoints by using:

lb4 controller

You are prompted with different questions. Specify the responses as follows:

? Controller class name: todo
Controller Todo will be created in src/controllers/todo.controller.ts

? What kind of controller would you like to generate? REST Controller with CRUD functions
? What is the name of the model to use with this CRUD repository? Todo
? What is the name of your CRUD repository? TodoRepository
? What is the name of ID property? id
? What is the type of your ID? number
? Is the id omitted when creating a new instance? Yes
? What is the base HTTP path name of the CRUD operations? /todos
   create src/controllers/todo.controller.ts
   update src/controllers/index.ts

Controller Todo was created in src/controllers/

Look inside src/controllers/todo.controller.ts, there are several more endpoints:

  • GET / POST / PATCH /todos
  • GET / PATCH / PUT / DEL /todos/{id}
  • GET /todos/count

So, in total, these are the available endpoints of this application:

Using the Appsody run, test, and debug commands

At this point, your application has been fully enabled. This means that you can now run, test, and debug your application in the continuous containerized environment provided by the Appsody Stack. Once you have entered appsody run in the terminal and your Appsody local development environment is up and running you can check out the endpoints listed in the previous section.

For more information see the documentation for Appsody local development.

If your application is currently running under Appsody, you can stop it with Ctrl+C, or by running the command appsody stop from another terminal.

To turn on debug tracing in a LoopBack 4 application running under the control of Appsody, you need to use the --docker-options parameter. You can specify this parameter for the run, debug and test commands: appsody [run | debug | test] --docker-options "--env DEBUG=loopback*"