A simple Express application with LoopBack 4 REST API

Overview

Express is an unopinionated Node.js framework. LoopBackREST API can be mounted to an Express application and be used as middleware.This way the user can mix and match features from both frameworks to suit theirneeds.

Note:

If you want to use LoopBack as the host instead and mount your Expressapplication on a LoopBack 4 application, seeMounting an Express Router.

This tutorial assumes familiarity with scaffolding a LoopBack 4 application,Models, DataSources,Repositories, and Controllers. To seehow they’re used in a LoopBack application, please see theTodo tutorial.

Try it out

If you’d like to see the final results of this tutorial as an exampleapplication, follow these steps:

  • Run the lb4 example command to select and clone the express-compositionrepository:
  1. lb4 example express-composition
  • Switch to the directory.
  1. cd loopback4-example-express-composition
  • Finally, start the application!
  1. $ npm start
  2. Server is running at http://127.0.0.1:3000

Create your LoopBack Application

Scaffold your Application

Run lb4 app note to scaffold your application and fill out the followingprompts as follows:

  1. $ lb4 app note
  2. ? Project description: An application for recording notes.
  3. ? Project root directory: (note)
  4. ? Application class name: (NoteApplication)
  5. Enable eslint: add a linter with pre-configured lint rules
  6. Enable prettier: install prettier to format code conforming to rules
  7. Enable mocha: install mocha to run tests
  8. Enable loopbackBuild: use @loopback/build helpers (e.g. lb-eslint)
  9. Enable vscode: add VSCode config files
  10. ❯◯ Enable docker: include Dockerfile and .dockerignore
  11. Enable repositories: include repository imports and RepositoryMixin
  12. Enable services: include service-proxy imports and ServiceMixin
  13. # npm will install dependencies now
  14. Application note was created in note.

Add Note Model

Inside the project folder, run lb4 model to create the Note model withEntity model base class. Add an id property with type number, a requiredtitle property with type string, and a content property of type string.

Add a DataSource

Now, let’s create a simple in-memory datasource by running thelb4 datasource ds command and the following full path to file:./data/ds.json.

Similar to the Todo example, let’s create the ds.json by creating a datafolder at the application’s root.

  1. $ mkdir data
  2. $ touch data/ds.json

Then copy and paste the following into the ds.json file:

  1. {
  2. "ids": {
  3. "Note": 3
  4. },
  5. "models": {
  6. "Note": {
  7. "1": "{\"title\":\"Things I need to buy\",\"content\":\"milk, cereal, and waffles\",\"id\":1}",
  8. "2": "{\"title\":\"Great frameworks\",\"content\":\"LoopBack is a great framework\",\"id\":2}"
  9. }
  10. }
  11. }

Add Note Repository

To create the repository, run the lb4 repository command and choose theDsDataSource, as the datasource, Note model as the model, andDefaultCrudRepository as the repository base class.

Add Note Controller

To complete the Note application, create a controller using thelb4 controller note command, with the REST Controller with CRUD functionstype, Note model, and NoteRepository repository. The id’s type will benumber and base HTTP path name is the default /notes.

Create a Facade Express Application

Let’s start by installing dependencies for the express module:

  1. npm install --save express
  2. npm install --save-dev @types/express

Create a new file src/server.ts to create your Express class:

src/server.ts

  1. import * as express from 'express';
  2. export class ExpressServer {
  3. constructor() {}
  4. }

Create two properties, the Express application instance and LoopBack applicationinstance:

  1. import {NoteApplication} from './application';
  2. import {ApplicationConfig} from '@loopback/core';
  3. import * as express from 'express';
  4. export class ExpressServer {
  5. private app: express.Application;
  6. private lbApp: NoteApplication;
  7. constructor(options: ApplicationConfig = {}) {
  8. this.app = express();
  9. this.lbApp = new NoteApplication(options);
  10. }
  11. }

Now, inside the constructor, we’re going to add the basepath and expose thefront-end assets via Express:

  1. this.app.use('/api', this.lbApp.requestHandler);

Let’s also modify public/index.html to update the base path:

public/index.html

  1. <h3>OpenAPI spec: <a href="/api/openapi.json">/openapi.json</a></h3>
  2. <h3>API Explorer: <a href="/api/explorer">/explorer</a></h3>

Then, we can add some custom Express routes, as follows:

  1. import {Request, Response} from 'express';
  2. import * as path from 'path';
  3. export class ExpressServer {
  4. private app: express.Application;
  5. private lbApp: NoteApplication;
  6. constructor(options: ApplicationConfig = {}) {
  7. // earlier code
  8. // Custom Express routes
  9. this.app.get('/', function(_req: Request, res: Response) {
  10. res.sendFile(path.resolve('public/express.html'));
  11. });
  12. this.app.get('/hello', function(_req: Request, res: Response) {
  13. res.send('Hello world!');
  14. });
  15. }
  16. }

And add thepublic/express.htmlfile to your project.

Let’s also install p-event to makesure the server is listening:

  1. npm install --save p-event

Finally, we can add functions to boot the Note application and start theExpress application:

  1. import pEvent from 'p-event';
  2. export class ExpressServer {
  3. private app: express.Application;
  4. private lbApp: NoteApplication;
  5. constructor(options: ApplicationConfig = {}) {
  6. //...
  7. }
  8. async boot() {
  9. await this.lbApp.boot();
  10. }
  11. async start() {
  12. const port = this.lbApp.restServer.config.port || 3000;
  13. const host = this.lbApp.restServer.config.host || '127.0.0.1';
  14. const server = this.app.listen(port, host);
  15. await pEvent(server, 'listening');
  16. }
  17. }

Now that our src/server.ts file is ready, then we can modify oursrc/index.ts file to start the application:

src/index.ts

  1. import {ExpressServer} from './server';
  2. import {ApplicationConfig} from '@loopback/core';
  3. export {ExpressServer, NoteApplication};
  4. export async function main(options: ApplicationConfig = {}) {
  5. const server = new ExpressServer(options);
  6. await server.boot();
  7. await server.start();
  8. console.log('Server is running at http://127.0.0.1:3000');
  9. }

Now let’s start the application and visit http://127.0.0.1:3000:

  1. npm start
  2. Server is running at http://127.0.0.1:3000

If we go to the Explorer, we can makerequests for our LoopBack application. Notice how the server ishttp://127.0.0.1:3000/api.

To view our custom /hello Express route, go to http://127.0.0.1:3000/helloand you should see ‘Hello world!’.

To serve static files in your application, add the following to the end of yourconstructor:

src/server.ts

  1. export class ExpressServer {
  2. private app: express.Application;
  3. private lbApp: NoteApplication;
  4. constructor(options: ApplicationConfig = {}) {
  5. // earlier code
  6. // Serve static files in the public folder
  7. this.app.use(express.static('public'));
  8. }
  9. // other functions
  10. }

Now, you can load any static files in the public/ folder. For example, addthe followingpublic/notes.htmlfile to your project, run npm start again, and visithttp://127.0.0.1:3000/notes.html. You can now see a static file that willdisplay your Notes in a table format. For more information, please visitServing static files in Express.

Congratulations, you just mounted LoopBack 4 REST API onto a simple Expressapplication.