Skip to main content

7 posts tagged with "typescript"

View All Tags

· 7 min read

Overview :

Before two weeks Ryan Dahl (Founder of Node.JS) announced the first version of [Deno](https://deno.land/). As the tagline says A secure runtime for JavaScript and TypeScript. Deno is a runtime for Javascript and Typescript that is based on the V8 JavaScript engine and the Rust programming language. I have been a Node developer for 2 years in the past, if you want to get started with Deno knowing Node.js would be an added advantage. Even though Deno has arrived as a competitor for NodeJS in the industry not so quick but people are sure that it'll take over.

I was reading lot of documentations and materials to understand the difference. So, here are the advantages that i see from Deno,

  • It is Secure by default. No file, network, or environment access, unless explicitly enabled.
  • Supports TypeScript out of the box.
  • Ships only a single executable file.
  • Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
  • Deno does not use npm
  • Deno does not use package.json in its module resolution algorithm.
  • All async actions in Deno return a promise. Thus Deno provides different APIs than Node.
  • Uses "ES Modules" and does not support require().
  • Deno has a built-in test runner that you can use for testing JavaScript or TypeScript code.
  • Deno always dies on uncaught errors.

I was very excited as other developers when Deno was announced. In this post i will demonstrate how to create a simple Web API with Deno and deploy to production on Web App with Azure.

PreRequisities:

You will need to have an Azure Subscription. If you do not have an Azure subscription you can simply create one with free trial.

Install Deno :

Using Shell (macOS, Linux):

curl -fsSL https://deno.land/x/install/install.sh | sh

Using PowerShell (Windows):

iwr https://deno.land/x/install/install.ps1 -useb | iex

Using Homebrew (macOS):

brew install deno

Using Chocolatey (Windows):

choco install deno

Using Scoop (Windows):

scoop install deno

Services used:

  • Azure Web App
  • Github Actions

Step 1 : Create Deno Rest API

I will not be going through each step on how to create the REST API, however if you are familiar with creating APIs with Node , it is the same way that you need to do. You need to have the main file server.ts which will have those routes defined. (server.ts)

import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
const PORT = 8001;

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Server at ${PORT}`);
await app.listen({ port: PORT });

One feature that i personally liked in DENO is that it provides developers to code with  TypeScript that addresses "design mistakes" in Node.js. In this case i am going to create an API to fetch/add/delete products and my interface would look like as below (types.ts),

export interface Product {
id: String;
name: String;
description: String;
price: Number;
status: String;
}

Similar to how you would define routes in Node, you need to define the routes for different endpoints when user want to execute fetch/add/delete operations as follows(routes.ts),

import { Router } from "https://deno.land/x/oak/mod.ts";
import { delete_product, add_product, get_product, get_products } from "./Controllers/Products.ts";

const router = new Router();

router.get("/", ctx => {
ctx.response.body = "Welcome to Deno!";
});

router.get("/get/:id", get_product);
router.post("/add", add_product);
router.get("/get_all_products", get_products);
router.get("/delete/:id", delete_product);

export default router;

The final step is to create the code for the logic of those each routes. You need to implement the methods which are defined in those routes. For example get_products would look like


import { Product } from "../Types.ts";

let products: Product[] = [
{
id: "1",
name: "Iphone XI",
description: "256GB",
price: 799,
status: "Active"
}
];

const get_products = ({response}: {response: any}) => {
response.status = 200;
response.body = products;
};

You can access the whole code from this Repository.

Run the DENO app:

Once you are good with everything, you can run the app in local and check if the endpoints are working as expected.

deno run -A server.ts

And you would see the app running in port 8001 , and you can access the endpoints as follows ,

Deno API

Step 2 : Create Azure Resources

Now we are good with the first step and you can see the app running successfully in local. As the next step let's go ahead and deploy the app to Azure. Inorder to deploy the app, you need to create a Resource Group first.

Create a ResourceGroup Named Deno-Demo

You can navigate to Azure Portal and search for Resource Group in the search bar and create a new one as defined here!

Next step is to create the Web App , as we are going to deploy this app to a Linux environment, you can set the configuration as follows,

Web App Configuration

Step 3 : Deploy to Azure with Github Actions

One of the recent inventions by Github team that was loved by all developers were Github Actions. Personally i am a big fan of Github actions and i have published few posts earlier explaining the same. To configure the Github Action to our application, first you need to push the code to your github repository.

Create a deno.yml

To deploy the app , we first need to create the workflow under the actions. you can create a new workflow by navigating to Actions tab and create new workflow

New Workflow

I am assuming that you are familiar with important terms of Github Actions, if you are new you can explore here. In this particular example i will be using one package created by Anthony Chu who is a Program Manager in Azure functions team. And my deno.yml looks like below,

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:

build-and-deploy:
runs-on: ubuntu-latest
steps:

- uses: actions/checkout@v2

- uses: azure/[email protected]
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}

- name: Set up Deno
uses: denolib/setup-deno@master
with:
deno-version: 1.0.2

- name: Bundle and zip Deno app
run: |
deno bundle server.ts server.bundle.js
zip app.zip server.bundle.js
- name: Deploy to Azure Web Apps
uses: anthonychu/azure-webapps-deno-deploy@master
with:
app-name: denodemo
resource-group: deno-demo
package: app.zip
script-file: server.bundle.js
deno-version: "1.0.2"

One important thing you need to verify is the resource-group and the app-name as you created on Azure.

Also you need to add secrets of your application under secrets in Github repository. You can generate a new Service Principal and obtain the secret as below,


az ad sp create-for-rbac --name "deno-demo" --role contributor --scopes /subscriptions/{SubscriptionID}/resourceGroups/deno-demo --sdk-auth

It will generate a JSON like below,

Generate Service Principal

You can copy and paste the JSON under the secret named "AZURE_CREDENTIALS" ,

Add Secret

Now we are good with everything, you can update some file on the repository and see the workflow getting triggered. You can monitor the deployment by navigating to the workflow.

Workflow Execution

Once everything is successful you can navigate to Azure portal and open the Web App endpoint to see if the app is running successfully.

WebApp with Deno API

You can see the app running successfully on Azure.

Deno Web API on azure.

Final words

I really enjoyed learning about the Deno project and created this simple app. I hope this article can be of value for anyone getting started with Deno with Azure.  I see it Deno gaining in popularity, yes. However, I do not see it replacing NodeJS and npm based on several factors. If you found this article useful, or if you have any questions please reach out me on Twitter. Cheers!

· 7 min read

Overview :

Before two weeks Ryan Dahl (Founder of Node.JS) announced the first version of [Deno](https://deno.land/). As the tagline says A secure runtime for JavaScript and TypeScript. Deno is a runtime for Javascript and Typescript that is based on the V8 JavaScript engine and the Rust programming language. I have been a Node developer for 2 years in the past, if you want to get started with Deno knowing Node.js would be an added advantage. Even though Deno has arrived as a competitor for NodeJS in the industry not so quick but people are sure that it'll take over.

I was reading lot of documentations and materials to understand the difference. So, here are the advantages that i see from Deno,

  • It is Secure by default. No file, network, or environment access, unless explicitly enabled.
  • Supports TypeScript out of the box.
  • Ships only a single executable file.
  • Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
  • Deno does not use npm
  • Deno does not use package.json in its module resolution algorithm.
  • All async actions in Deno return a promise. Thus Deno provides different APIs than Node.
  • Uses "ES Modules" and does not support require().
  • Deno has a built-in test runner that you can use for testing JavaScript or TypeScript code.
  • Deno always dies on uncaught errors.

I was very excited as other developers when Deno was announced. In this post i will demonstrate how to create a simple Web API with Deno and deploy to production on Web App with Azure.

PreRequisities:

You will need to have an Azure Subscription. If you do not have an Azure subscription you can simply create one with free trial.

Install Deno :

Using Shell (macOS, Linux):

curl -fsSL https://deno.land/x/install/install.sh | sh

Using PowerShell (Windows):

iwr https://deno.land/x/install/install.ps1 -useb | iex

Using Homebrew (macOS):

brew install deno

Using Chocolatey (Windows):

choco install deno

Using Scoop (Windows):

scoop install deno

Services used:

  • Azure Web App
  • Github Actions

Step 1 : Create Deno Rest API

I will not be going through each step on how to create the REST API, however if you are familiar with creating APIs with Node , it is the same way that you need to do. You need to have the main file server.ts which will have those routes defined. (server.ts)

import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
const PORT = 8001;

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Server at ${PORT}`);
await app.listen({ port: PORT });

One feature that i personally liked in DENO is that it provides developers to code with  TypeScript that addresses "design mistakes" in Node.js. In this case i am going to create an API to fetch/add/delete products and my interface would look like as below (types.ts),

export interface Product {
id: String;
name: String;
description: String;
price: Number;
status: String;
}

Similar to how you would define routes in Node, you need to define the routes for different endpoints when user want to execute fetch/add/delete operations as follows(routes.ts),

import { Router } from "https://deno.land/x/oak/mod.ts";
import { delete_product, add_product, get_product, get_products } from "./Controllers/Products.ts";

const router = new Router();

router.get("/", ctx => {
ctx.response.body = "Welcome to Deno!";
});

router.get("/get/:id", get_product);
router.post("/add", add_product);
router.get("/get_all_products", get_products);
router.get("/delete/:id", delete_product);

export default router;

The final step is to create the code for the logic of those each routes. You need to implement the methods which are defined in those routes. For example get_products would look like


import { Product } from "../Types.ts";

let products: Product[] = [
{
id: "1",
name: "Iphone XI",
description: "256GB",
price: 799,
status: "Active"
}
];

const get_products = ({response}: {response: any}) => {
response.status = 200;
response.body = products;
};

You can access the whole code from this Repository.

Run the DENO app:

Once you are good with everything, you can run the app in local and check if the endpoints are working as expected.

deno run -A server.ts

And you would see the app running in port 8001 , and you can access the endpoints as follows ,

Deno API

Step 2 : Create Azure Resources

Now we are good with the first step and you can see the app running successfully in local. As the next step let's go ahead and deploy the app to Azure. Inorder to deploy the app, you need to create a Resource Group first.

Create a ResourceGroup Named Deno-Demo

You can navigate to Azure Portal and search for Resource Group in the search bar and create a new one as defined here!

Next step is to create the Web App , as we are going to deploy this app to a Linux environment, you can set the configuration as follows,

Web App Configuration

Step 3 : Deploy to Azure with Github Actions

One of the recent inventions by Github team that was loved by all developers were Github Actions. Personally i am a big fan of Github actions and i have published few posts earlier explaining the same. To configure the Github Action to our application, first you need to push the code to your github repository.

Create a deno.yml

To deploy the app , we first need to create the workflow under the actions. you can create a new workflow by navigating to Actions tab and create new workflow

New Workflow

I am assuming that you are familiar with important terms of Github Actions, if you are new you can explore here. In this particular example i will be using one package created by Anthony Chu who is a Program Manager in Azure functions team. And my deno.yml looks like below,

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:

build-and-deploy:
runs-on: ubuntu-latest
steps:

- uses: actions/checkout@v2

- uses: azure/[email protected]
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}

- name: Set up Deno
uses: denolib/setup-deno@master
with:
deno-version: 1.0.2

- name: Bundle and zip Deno app
run: |
deno bundle server.ts server.bundle.js
zip app.zip server.bundle.js
- name: Deploy to Azure Web Apps
uses: anthonychu/azure-webapps-deno-deploy@master
with:
app-name: denodemo
resource-group: deno-demo
package: app.zip
script-file: server.bundle.js
deno-version: "1.0.2"

One important thing you need to verify is the resource-group and the app-name as you created on Azure.

Also you need to add secrets of your application under secrets in Github repository. You can generate a new Service Principal and obtain the secret as below,


az ad sp create-for-rbac --name "deno-demo" --role contributor --scopes /subscriptions/{SubscriptionID}/resourceGroups/deno-demo --sdk-auth

It will generate a JSON like below,

Generate Service Principal

You can copy and paste the JSON under the secret named "AZURE_CREDENTIALS" ,

Add Secret

Now we are good with everything, you can update some file on the repository and see the workflow getting triggered. You can monitor the deployment by navigating to the workflow.

Workflow Execution

Once everything is successful you can navigate to Azure portal and open the Web App endpoint to see if the app is running successfully.

WebApp with Deno API

You can see the app running successfully on Azure.

Deno Web API on azure.

Final words

I really enjoyed learning about the Deno project and created this simple app. I hope this article can be of value for anyone getting started with Deno with Azure.  I see it Deno gaining in popularity, yes. However, I do not see it replacing NodeJS and npm based on several factors. If you found this article useful, or if you have any questions please reach out me on Twitter. Cheers!

· 3 min read

Hey NG folks, ng-Srilanka 2019, the First-ever Angular conference on the 14th of September 2019 was a great success. It was a dream come true moment for me. Yes, I am one of those developers who marries one platform or framework and doesn’t care too much about the other ones. I have been an Angularjs/Angular developer for the past 7 years. One of the reasons why I wanted to make this happen was because of the strong and wide Angular community in Sri Lanka. When I became a GDE in Angular in 2018, my first aim was to build a strong developer,especially Angular community in SriLanka. NG-Srilanka has been a 2 year dream and finally I am glad it happened with all grandeur .

To those who missed the event this year, below are some of the biggest highlights and benefits that ng-Srilanka had to offer that you can take right back to your development desk.

First ever Angular conference:

It was such an honor for me and my team to organize this fantastic conference for the first time in SriLanka and 2nd Angular conference in SouthEast Asia. When we started it we never imagined NG-Srilanka will grow into a large international conference which will attract such a strong support from the industry.

For the community, by the community:

A set of volunteers from the two top universities in SriLanka focused on reaching out to and building interest in the local community. The event was adorned by 400+ passionate developers from 15+ universities and 20+ companies. We ensured that we had a diverse speaker line up and further promoted diversity with scholarships and ensured that most participants made it to the event.

NG-Scholarship for students :

Unlike most of the Angular conferences, we came up with a scholarship program to provide free training on Angular by the local experts. The scholarship winners were selected based on the knowledge on Angular and their passion to learn more.

Great Agenda:

NG-Sri Lanka 2019 kicked off with @mgechev of the Angular team, who joined us from California and delivered the keynote. Later, the sessions were divided into two tracks named "Stacked" and "Sandwich". "Stacked" track touched upon various topics on Angular and "Sandwich track" deep dived into specific workshops. The event was also garnsihed with few lighter moments like entertainment performances by NSBM students.

Finally the speakers addressed the audience in an open QnA session, through which certain Angular topics were further discussed.This was a huge value add for the attendees, and proved truly a platform where many meaningful conversations can happen.

An AWESOME Team:

The real success of ng-Srilanka was the team behind it. Thank you, to the fantastic co-organizers who worked with me day and night, the amazing support staff , dedicated volunteers, the sponsors, the awesome speakers and of course the great attendees.I would like to thank everyone who contributed to the success of the event, devoted their time and support to make this conference a big HIT.

Such a nerve wracking but amazing experience! So lucky to work with such a supportive team.

We've been recieving wonderful feedback from the speakers,attendees and several others on social media about the conference. Looking forward to NG-Srilanka 2020!

· 4 min read

I was at the Global Azure Bootcamp recently concluded last week, one of the participant came and asked me, "Hey what is Cosmos DB" I casually responded “Well, that’s Microsoft’s globally distributed, massively scalable, horizontally partitioned, low latency, fully indexed, multi-model NoSQL database". The immediate question came after that was whether it supports hybrid applications. In this blog I will be explaining how to leverage the features of cosmos db when you're building hybrid applications.

Ionic framework is an open source library of mobile-optimized components in JavaScript, HTML, and CSS. It provides developers with tools for building robust and optimized hybrid apps which works on Android,IOS and web.  Ionic comes with very native-styled mobile UI elements and layouts that you’d get with a native SDK on iOS or Android.

Let's see how to build Hybrid application with Ionic and Cosmosdb

PreRequisites:

You need to have npm and node installed on your machine to get started with Ionic.

Step 1: Make sure you've installed ionic in your machine with the following command,

ionic -v

Step 2: Install Ionic globally

if it's not installed, install it by using the command

npm i -g ionic

Step 3: Create a new ionic project

Ionic start is a command to create a new ionic project. You pass in the directory name to create, and the template to use. The template can be a built-in one (tabs, blank) or can point to a GitHub URL.

The aim is to create a simple ToDo application which displays lists of tasks, and user should be able to add new tasks.

Lets create a blank project with the command

 ionic start cosmosdbApp tabs

You will see a new project getting created.

Step 4: Run the ionic app

You can run the app with a simple command by navigating to the folder and then run

Ionic serve

This starts a local web server and opens your browser at the URL, showing the Ionic app in your desktop browser. Remember, ionic is just HTML, CSS and JavaScript!

It will open the application in the default browser with the default app.

If you're stuck at any point you can refer to my slides on How to get started with Ionic and follow the steps.

https://slides.com/sajeetharansinnathurai/ionicnsbm#/10

Step 5: Create the cosmosdb account on azure portal,

We need to create an cosmosdb account and use the Endpoint and SecretKey in our application. You can follow the

Blog on how to create it from the azure portal

https://sajeetharan.wordpress.com/2018/03/26/wear-out-the-features-of-azure-cosmosdb-with-aspnetcore-application/

Create a database named "ToDoList" and containeras "Items".

Once created, lets go back to the application.

Step 6: Lets add Cosmosdb SDK to the project

To consume the Cosmosdb service in the application we need to add the Azure Cosmos Javascript SDK to the project. This can be done with the command

npm i @azure/cosmos

Step 7:  You need to create an interface/model which will be used to save/retrieve the objects from the cosmosdb

https://gist.github.com/sajeetharan/a1dff67c87dce10bc2220aa0e9c550c3

Step 8: You need to add two pages home and todo page , home to display the lists of items inside the containerand todo page to add a new item. These two pages can be generated insdie the module with the command,

ionic g page home

Ionic g page todo

https://gist.github.com/sajeetharan/85229d091990d149b9c09d71f3387287

Step 9: We need to add a service to embed the logic to communicate with the cosmosdb you can create a new service inside the module as,

ionic g service cosmos

https://gist.github.com/sajeetharan/d7336abce15fa4d10ffd9d806b819462

As we need to make use of the available methods inside the @azure/cosmos You can import cosmos with the line,

import * as Cosmos from "@azure/cosmos";

Now make use of all the available functions in the SDK to add,delete,update items in the cosmosdb.

Step 8: To make application compatible with android/ios , run the following command,

Ionic cordova build ios/android

If you want to make the development faster, you could try building your ionic application with capacitor as well.

Now your hybrid application uses cosmosdb as a backend, with this demo you know how to use cosmosdb as a database for your hybrid application. I hope you should be able to create more applications in the future with cosmosdb and ionic.

You can check the demo application source code from here.

· 2 min read

Hey guys, There has not been a  proper resource to have a checklist to make sure that applicaiton is flawless.I decided to write a simple tips on checklist items needed before you deploy your app to production.Following are a few Angular Code Review Checklists useful while doing a peer review of Angular code. Make sure to check these when you are building a production ready application

#1 - Code modularity  

Layered Code with good Modularity.

#2 - Component per file 

Each file must not contain more than one Component/Controller, etc.

#3 - Routing

Always configure routing with lazy loading

#4 - Shared resources at centralized location

Store images/language translations under assets

#5 - 3rd Party libraries 

 If you are integrating with any 3rd party libraries make sure to check for Security Flaws

#6 - Data security 

Use  Encryption of Sensitive Data

#7 - Offline data security

Consider security if you are storing Data in localstorage or session storage.

#8 - Cookies data and handwiring of secrets 

 Security Flaws

#9 - Don't use pipe/functions in the template

Calling function binding in the template will lead to  performance issue

#10 - Change detection + state management & reactive extensions

Use RxJS, NgRx/Store (or Redux)

#11 - Use javascript or typescript

 Stick to ONE & Avoid Hybrid

#12 - Don't use pipe/functions in the template

 Bundling, Chunking, Treeshaking, Minification, Uglification, Compression

#13 - ECMAscript compatibility - ES7

#14 - Angular Style Guide (Official Reference)

 https://angular.io/guide/styleguide

#15 - Async service

 Adequate and Appropriate use of it.

#16 - Hierarchical components,models,interfaces etc

#17 - Constants

No-Scattered Hard-Coded constants data but must be at one place.

#18 - Images,fonts and other static files

Place them in respective directories and not scattered across.

#19 - TSLint.json

To follow Angular Style Guide in order to run SonarQube or Codelyzer. Follow https://github.com/Angular-Projects-V-1-to-X/codelyzer

#20 - Finally to improve performance 

Refer the steps  - https://github.com/mgechev/angular-performance-checklist

Hope it helps all the developers out there.