The Ultimate Guide For Building RTA

Previously on Angular Universal: Server Side Rendering With StrongLoop I explained how to forget about the SEO Nightmare of Angular 1 by integrating Angular Universal with the StrongLoop’s LoopBack Framework.

Today I’m super excited to present you the latest 2 modules I just published this week for you to build Real Time Applications in the easier way ever possible:

[Public Applause Sound in the Background]

Presenting The LoopBack SDK Builder

LoopBack SDK Builder

The LoopBack SDK Builder is a community driven module forked from the official loopback generator loopback-sdk-angular for Angular 1.

But what is the reason for this fork? Read here for reasons

Now that you know the reasons and in order to build a complete solution to integrate these technologies I needed to actively work on the NativeScript SDK Builder that not only implement AJAX Requests as the official module, but also to support connection through WebSockets for Angular 2 and NativeScript which goes beyond of the original scope of the loopback-sdk-angular therefore I can provide you with a greater solution with native support for the next module I will present.

Presenting The LoopBack Component PubSub

LoopBack Component PubSub

The LoopBack Component PubSub is a module I built to provide an implementation of the PubSub Pattern in the easier way possible so we turn the LoopBack Framework into a truly Real Time API Framework.

Project Description

If you have been following my post series and read The Ultimate Guide for Native App Development I demonstrated a complete fullstack solution for you to build truly native mobile applications in less than 50 lines of code.

But… As I said before we can do even more advanced examples so today we are going to automatically build a SDK for NativeScript that provides both RESTful and WebSockets communication in order to create a native chat app project.

What is the difference between this chat project and others? Well, most of the tutorials you find are either way confusing or incomplete.

Following this tutorial you will be able to develop a complete -Hopefully not so complex- solution. Since users, rooms and messages will be persisted in a database, also the LoopBack SDK Builder and LoopBack Component PubSub modules implement security mechanisms in order to register and authenticate users in both HTTP and WS requests.

So… Since I know this will be a little more overwhelming I will split this tutorial into a series of 2 or maybe 3 posts -who knows-.

Technology Stack

  • MongoDB.- Building on the Best of Relational with the Innovations of NoSQL.
  • LoopBack.- The Node.js API Framework.
  • Angular 2.- Development platform for building mobile and desktop applications.
  • NativeScript 2.- Truly native mobile apps with Angular.

Requirements

GitHub Example Code Repository

Native Chat Application Example

Setup Environment

Ok since you already have installed the environment stack, now we need to install the platforms needed for this project, for this we are going to use NPM.

1
$ npm install -g strongloop nativescript

Setup REST API Project

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
$ mkdir native-chat
$ mkdir native-chat/native-chat-api
$ cd native-chat/native-chat-api
$ slc loopback


_-----_
| | .--------------------------.
|--(o)--| | Let's create a LoopBack |
`---------´ | application! |
( _´U`_ ) '--------------------------'
/___A___\
| ~ |
__'.___.'__
´ ` |° ´ Y `

? What's the name of your application? native-chat-api

? What kind of application do you have in mind? api-server (A LoopBack API server with local User auth)
Generating .yo-rc.json


I'm all done. Running npm install for you to install the required dependencies. If this fails, try running the command yourself.


create .editorconfig
create .jshintignore
create .jshintrc
create server/boot/root.js
create server/middleware.json
create server/middleware.production.json
create server/server.js
create README.md
create server/boot/authentication.js
create .gitignore
create client/README.md
native-chat-api@1.0.0 /Volumes/backup/development/www/mean.expert/examples/native-chat/native-chat-api

Next steps:

Create a model in your app
$ slc loopback:model

Compose your API, run, deploy, profile, and monitor it with Arc
$ slc arc

Run the app
$ node .

We have just created a LoopBack Application, if you run the $ node . command, you will have a fully working RESTful API running in your machine/server that includes built in User Model, Authentication mechanism and API Explorer. But we still need to configure a datasource to connect with our MongoDB Instance.

For those who doesn’t know The StrongLoop‘s LoopBack Framework but you come from languages like PHP or Ruby Lang and you use Laravel, Ruby on Rails or from any language but you know the Active Record Pattern, well.. if you love these frameworks, or you love the Active Record Pattern, this is the framework in node that implements it the best, so you should be loving it by now.

Setup DataBase and DataSource

Click on the following links to create a DB Instance and a DataSource

Create Account Model

The only model that will not extend from PersistedModel is the Account Model since this one will extend from UserModel

1
2
3
4
5
6
7
8
9
10
11
12
$ slc loopback:model Account
? Enter the model name: Account
? Select the data-source to attach undefined to: db (memory)
? Select model's base class User
? Expose Account via the REST API? Yes
? Custom plural form (used to build REST URL): accounts
? Common model or server only? common
Let's add some Account properties now.


Let's add another Account property.
Enter an empty property name when done.
? Property name:

Create Room Model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ slc loopback:model Room
? Enter the model name: Room
? Select the data-source to attach undefined to: db (memory)
? Select model's base class PersistedModel
? Expose Room via the REST API? Yes
? Custom plural form (used to build REST URL): Rooms
? Common model or server only? common
Let's add some Room properties now.


Let's add another Room property.
Enter an empty property name when done.
? Property name: text
? Property type: string
? Property required: yes

Let's add another Room property.

Enter an empty property name when done.
? Property name:

Create Message Model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ slc loopback:model Message
? Enter the model name: Message
? Select the data-source to attach undefined to: db (memory)
? Select model's base class PersistedModel
? Expose Message via the REST API? Yes
? Custom plural form (used to build REST URL): messages
? Common model or server only? common
Let's add some Message properties now.


Let's add another Message property.
Enter an empty property name when done.
? Property name: text
? Property type: string
? Property required: yes

Let's add another Message property.

Enter an empty property name when done.
? Property name:

Relationships

Account has and belongs to many Room

1
2
3
4
5
6
native-chat-api jcasarrubias$ slc loopback:relation
? Select the model to create the relationship from: Account
? Relation type: has and belongs to many
? Choose a model to create a relationship with: Room
? Enter the property name for the relation: rooms
? Optionally enter a custom foreign key:

Room has and belongs to many Account

1
2
3
4
5
6
native-chat-api jcasarrubias$ slc loopback:relation
? Select the model to create the relationship from: Room
? Relation type: has and belongs to many
? Choose a model to create a relationship with: Account
? Enter the property name for the relation: accounts
? Optionally enter a custom foreign key:

Room has many Message

1
2
3
4
5
6
7
native-chat-api jcasarrubias$ slc loopback:relation
? Select the model to create the relationship from: Room
? Relation type: has many
? Choose a model to create a relationship with: Message
? Enter the property name for the relation: messages
? Optionally enter a custom foreign key:
? Require a through model? No

Message belongs to Room

1
2
3
4
5
6
native-chat-api jcasarrubias$ slc loopback:relation
? Select the model to create the relationship from: Message
? Relation type: belongs to
? Choose a model to create a relationship with: Room
? Enter the property name for the relation: room
? Optionally enter a custom foreign key:

Account has many Message

1
2
3
4
5
6
7
native-chat-api jcasarrubias$ slc loopback:relation
? Select the model to create the relationship from: Account
? Relation type: has many
? Choose a model to create a relationship with: Message
? Enter the property name for the relation: messages
? Optionally enter a custom foreign key:
? Require a through model? No

Message belongs to Account

1
2
3
4
5
6
native-chat-api jcasarrubias$ slc loopback:relation
? Select the model to create the relationship from: Message
? Relation type: belongs to
? Choose a model to create a relationship with: Account
? Enter the property name for the relation: account
? Optionally enter a custom foreign key:

Install SDK Builder and PubSub Modules

The SDK Builder should be stored as development dependency, but the pub sub component should be installed as dependency.

1
2
$ npm install --save-dev @mean-expert/loopback-sdk-builder
$ npm install --save loopback-component-pubsub

Configure SDK Builder

Update your package.json file by adding a new script with the following command:

1
2
3
4
5
{
"scripts": {
"build:sdk": "./node_modules/.bin/lb-sdk server/server.js ../native-chat-app/app/sdk -d nativescript2 -i enabled"
}
}

Setup PubSub Module

Update the server/component-config.json as follows:

1
2
3
4
5
6
7
8
{
"loopback-component-explorer": {
"mountPath": "/explorer"
},
"loopback-component-pubsub": {
"auth": false // For this part of the tutorial
}
}

Update the server/model-config.json as follows:

1
2
3
4
5
6
7
8
9
{
"mixins": [
"loopback/common/mixins",
"loopback/server/mixins",
"../common/mixins",
"./mixins",
"../node_modules/loopback-component-pubsub/mixins"
]
}

Enable PubSub for the Room Model

Add a mixins section within the common/models/room.json file to enable the PubSub functionality.

1
2
3
4
5
{
"mixins": {
"PubSub": true
}
}

Update Server File

Update the start method within the server/server.js file as follows:

1
2
3
4
5
6
7
8
9
10
11
app.start = function() {
return server = app.listen(function() {
app.emit('started', server);
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};

Create NativeScript Application

Lets create our NativeScript 2 Application and sdk directory:

1
2
3
$ cd ../
$ tns create native-chat-app --ng
$ mkdir native-chat-app/app/sdk

Build LoopBack SDK for NativeScript

1
2
$ cd native-chat-api
$ npm run build:sdk

Install App Dependencies

1
2
$ cd ../native-chat-app
$ npm install --save @angular/http nativescript-socket.io

Develop Basic Version of Mobile App

We are basically done of configurations, we already have in place a Chat REST/WS API ready to star receiving request from our client application, for now I just want to test everything went well and we are able to connect our ends.

For now we are just going update the app.component as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Component } from "@angular/core";
import { API_PROVIDERS, LoopBackConfig, RoomApi } from './sdk';

@Component({
selector: "my-app",
template: `
<StackLayout>
<Label text="Real Time App" class="title"></Label>
</StackLayout>
`,

providers: [API_PROVIDERS, RoomApi]
})

export class AppComponent {
constructor(private room: RoomApi) {
// local network IP or public IP/DNS
LoopBackConfig.setBaseURL('http://192.168.100.5:3000');
LoopBackConfig.setApiVersion('api');
room.onCreate().subscribe((res: { id: number | string, name: string }) => {
alert(res.name);
});
}
}

Lets test our application

Open 2 terminal windows and start both… The API and App (use device or emulator, your choice)

Terminal 1:

1
2
3
4
5
$ cd native-chat-api
$ node .
RTC server listening at ws://0.0.0.0:3000/
Web server listening at: http://0.0.0.0:3000
Browse your REST API at http://0.0.0.0:3000/explorer

Terminal 2:

1
2
$ cd native-chat-app
$ tns livesync android --watch

If you create a room using the LoopBack API Explorer, you will be able to see an alert dialog with the name of the room you enter, just like:

Basic Test

What is next?

In my next blog posts I will continue with this tutorial by building the rest of the application, adding sections to register, login and chat rooms.

If you like this series and want be aware of next releases and new packages, follow me on Twitter @johncasarrubias and if you feel it leave a comment here.

Thanks for reading.


Comments:

...