Skip to content

nodejs-projects-kenanhancer/serverless-azure-functions-typescript-demo

Repository files navigation

Serverless Azure Functions TypeScript Demo

Just follow this README document to see deployed Azure Functions with Serverless Framework with Microsoft Azure Provider as shown in the following screenshots :)

Image1

Image2

Documentation


Links

Getting started

Pre-requisites


Install Npm Packages

Install all packages and dependencies via node package manager

npm install

# or

yarn install

Install or Update Serverless Framework

# Install
npm install -g serverless

# Update
npm update -g serverless

Setup Microsoft Azure CLI

If you don't have Microsoft Azure CLI in your local, install it from Microsoft Azure CLI

Install Microsoft Azure CLI on macOS

brew update && brew install azure-cli

Setup Microsoft Azure Functions Core Tools CLI

If you don't have Setup Microsoft Azure Functions Core Tools CLI in your local, download and install it from Setup Microsoft Azure Functions Core Tools CLI

Install Microsoft Azure Functions Core Tools CLI on macOS

brew tap azure/functions
brew install azure-functions-core-tools@3
# if upgrading on a machine that has 2.x installed
brew link --overwrite azure-functions-core-tools@3

Setup Microsoft Azure Emulator

This is necessary for local development. If you run npm start, below code will be runned automatically. Refer to Azurite for more details.

npx azurite --silent

Image5


Setup Microsoft Azure Storage Explorer

If you don't have Microsoft Azure Storage Explorer in your local, download and install Microsoft Azure Storage Explorer. It looks like as the following screenshot.

Image18

Install Microsoft Azure Storage Explorer on macOS

brew install --cask microsoft-azure-storage-explorer

Setup ngrok

ngrok is used, in order to test and debug EventGrid messages locally. Refer to ngrok for more details.

Port 7071 should be updated due to value of LocalHttpPort field in local.settings.json file.

npx ngrok http -host-header=localhost 7071

Image22

After ngrok is started, we should create a new Event Subscription in Azure EventGrid Topics

Image23

Image24

Syntax should be as below;

{ngrok https url}/runtime/webhooks/EventGrid?functionName={EventGrid Function Name}

So i used the following url in my case. I just copy ngrok url from the running ngrok process in my local

https://1770a1713d5b.ngrok.io/runtime/webhooks/EventGrid?functionName=eventGridTrigger_fn1

Image25

After saving Event Subscription, ngrok application will take a request locally as shown in the following screenshot.

Image26

If we need to send message to EventGrid, then update TopicEndpointUri and TopicKeySetting fields in local.settings.json file. Those two fields

In order to take TopicEndpointUri value, run the following command then copy and paste to TopicEndpointUri field in local.settings.json file.

az eventgrid topic show --name <topic name> -g <resource group name> --query "endpoint" --output tsv

In order to take TopicKeySetting value, run the following command then copy and paste to TopicKeySetting field in local.settings.json file.

az eventgrid topic key list --name <topic name> -g <resource group name> --query "key1" --output tsv

Running and Debugging Code Locally

To build the function binding files without spawning the process to start the function app.

npx sls offline build

Image6

Starts the function app.

npx sls offline

or

run Azure Functions Core Tools directly.

func host start

# or

# --port, -p	The local port to listen on. Default value: 7071
func host start --port 7071

Image7

or just use below code.

npm start

Image19

  • If there are more than one project working with Microsoft Azure Emulator, than change value of LocalHttpPort field in local.settings.json file

    • default value is "LocalHttpPort": 7071
  • Set value of AzureWebJobsStorage field in local.settings.json file one of the following values. (If you need to to connect Table storage as well then use second option)

    1. "AzureWebJobsStorage": "UseDevelopmentStorage=true;"
    2. "AzureWebJobsStorage": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;"

Domains

dev and prod environments should be updated.

Env Url
local for HTTP triggered functions http://localhost:7071/api
local for Non-HTTP triggered functions http://localhost:7071/admin/functions
dev http://localhost:7071/api
prod http://localhost:7071/api

Testing Azure HTTP and Webhook Triggered Functions Locally

Use one of the following commands to call Azure Http Function locally, and --port argument should be updated due to value of LocalHttpPort field in local.settings.json file.

npx sls invoke local --port 7071 --function hello --data '{\"name\":\"kenan\"}'

Image13

Likewise, curl port value should be updated as well.

Syntax of HTTP and Webhook

http://localhost:{port}/api/{function_name}
curl http://localhost:7071/api/hello?name=kenan
curl --get http://localhost:7071/api/hello?name=Azure%20Rocks
curl --request POST http://localhost:7071/api/hello --data '{"name":"Azure Rocks"}'
curl --request POST -H "Content-Type:application/json" --data '{"input":"sample queue data"}' http://localhost:7071/api/hello

Image14

Testing Azure Non-HTTP Triggered Functions Locally

Syntax of Non-HTTP

http://localhost:{port}/admin/functions/{function_name}
curl --request POST -H "Content-Type:application/json" --data '{"input":"sample queue data"}' http://localhost:7071/admin/functions/QueueTrigger

Testing Deployed Azure HTTP and Webhook Triggered Functions

just without the local and port options.

npx sls invoke --function hello --data '{\"name\":\"kenan\"}'

Image15

or

use curl command as below.

curl http://kenan-ukw-dev-azure-functions-typescript.azurewebsites.net/api/hello?name=kenan

Image16

Azure Deployment Steps

Login to Azure

Use one of the following Azure Login commands

az login

# or

az login --use-device-code

then run the following commands.

az account list # Get a list of subscriptions for the logged in account.
az account set --subscription <SUBSCRIPTION_ID> # choose the one you want
az account show # Get the details of a subscription.

then run below shell script to create .env.servicePrincipal file with new Azure credential tokens in project root folder.

. sp.sh

then run below script to export Azure credentials

source .env.servicePrincipal

Deploy to Azure

npm run deploy

Deployment is done and screenshot is below.

Image8

Now we should see deployed Resource Group in Azure Resouce groups Image3

Image4

Image2

Serverless CLI

Refer to Serverless docs for more information.

If you don't want to use npx sls, then install Serverless Framework globally with the following command.

npm install -g serverless

Deploy Azure Functions

$ npx sls deploy --region "West US 2"

$ npx sls deploy --region "North Central US"

$ npx sls deploy --region "West Europe"

$ npx sls deploy --region "West Europe" --prefix "kenanSquad"

$ npx sls deploy --region "West Europe" --prefix "kenanSquad" --stage "dev"

$ npx sls deploy --region "West Europe" --prefix "kenanSquad" --stage "test"

$ npx sls deploy --region "West Europe" --prefix "kenanSquad" --stage "prod"

Remove Deployed Azure Function App

If at any point you no longer need your service, you can run the following command to delete the resource group containing your Azure Function App and other depoloyed resources using

npx sls remove

You will then be prompted to enter the full name of the resource group as an extra safety before deleting the entire resource group.

You can bypass this check by running

npx sls remove --force

Azure API Management service is soft-deleted so that we can recover it if needed. But in order to delete it permanently,

refer to Microsoft Azure API Management docs for more details.

List Azure Deployment

Run the following command to list information about your deployments.

npx sls deploy list

Image10

Print serverless.yml

Run the following command to print your serverless.yml config file with all variables resolved.

Refer to Serverless docs for more information.

npx sls print

Image9

Dry-Run Deployment

Before you deploy your new function app, you may want to double check the resources that will be created, their generated names and other basic configuration info

This will print out a basic summary of what your deployed service will look like

# -d is short for --dryrun
npx sls deploy --dryrun

For a more detailed look into the generated ARM template for your resource group, add the --arm (or -a) flag

npx sls deploy --dryrun --arm

Image12

Get Summary of Deployed Azure Function App

To see a basic summary of your application (same format as the dry-run)

npx sls info

To look at the ARM template for the last successful deployment, add the --arm (or -a) flag

npx sls info --arm

You can also get information services with different stages, regions or resource groups by passing any of those flags. Example

npx sls info --stage prod --region ukw

Image11

Cleanup serverless.yml

To clean up files generated from the npx sls offline build

npx sls offline cleanup

Creating or Removing Azure Functions

npx sls func add --name testFunc1
npx sls func remove --name testFunc1

Creating new Serverless Framework Project

If you want to see project template types, then run the following command.

sls create --help

Image21

sls create -t azure-nodejs-typescript

Microsoft Azure CLI

Login to Azure

az login

# or

az login --use-device-code

List All Azure Subscriptions

az account list

# or

az account list --output=table

Show Current Azure Subscription

az account show

Set Azure Subscription

az account set --subscription <SUBSCRIPTION_ID>

List All Azure Regions

az account list-locations -o table

Image17

List All Azure Runtimes

az webapp list-runtimes

Image20

Create Resource Group

az group create --name azure-sdk-demo --location westus

az group create --name AzureFunctionsQuickstart-rg --location westeurope

Create Key Vault

az keyvault create --name "<your-unique-keyvault-name>" --resource-group "<your-resource-group-name>" --location "ukwest"

az keyvault create --name "kenankeyvault1" --resource-group "kenan-ukw-dev-greeting-api-rg" --location "ukwest"

# or 

az keyvault create --name kenankeyvault2 --resource-group kenan-ukw-dev-greeting-api-rg --location ukwest

Retrieve Secret from Key Vault

az keyvault secret show --name "ExamplePassword" --vault-name "<your-unique-keyvault-name>" --query "value"

az keyvault secret show --name "ExampleUsername" --vault-name "kenankeyvault1" --query "value"

az keyvault secret show --name "ExamplePassword" --vault-name "kenankeyvault1" --query "value"

Deploy ARM Template

azuredeploy.json

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "storageAccountName": {
            "type": "string",
            "metadata": {
                "description": "Storage Account Name"
            },
            "minLength": 3,
            "maxLength": 24
        }
    },
    "functions": [],
    "variables": {},
    "resources": [
        {
            "name": "[parameters('storageAccountName')]",
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2019-06-01",
            "tags": {
                "displayName": "storageaccount1"
            },
            "location": "[resourceGroup().location]",
            "kind": "StorageV2",
            "sku": {
                "name": "Premium_LRS",
                "tier": "Premium"
            }
        }
    ],
    "outputs": {}
}

azuredeploy.parameters.json

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "storageAccountName": {
            "value": "storageaccount1"
        }
    }
}
az group create --name arm-vscode --location eastus

az deployment group create --resource-group arm-vscode --template-file azuredeploy.json --parameters azuredeploy.parameters.json

You can cleanup resource

az group delete --name arm-vscode

Create Storage Account under Resource Group

az  storage account create --name azuresdkdemo --resource-group azure-sdk-demo --location westus

List Storage Account

az storage account list --resource-group azure-sdk-demo --output=table

Create Custom EventGrid Topic

topicname=<your-topic-name>
resourcegroupname=<your-resource-group-name>

az eventgrid topic create --name $topicname -l ukwest -g $resourcegroupname

Send Event to EventGrid Topic

  • topicname should be EventGrid name
  • resourceGroupName should be Resouce group field value in EventGrid
resourceGroupName="kenan-ukw-dev-azure-functions-typescript-rg"
topicname="eventgridbroker"

endpoint=$(az eventgrid topic show --name $topicname -g $resourceGroupName --query "endpoint" --output tsv)

key=$(az eventgrid topic key list --name $topicname -g $resourceGroupName --query "key1" --output tsv)

data='"data":{"make":"Ducati","model":"Monster","message":{"insured_name":"CharlieHorton"}}'

event='[ {"id": "2f6b1fc2-12cd-4f0e-98c2-899648eae4b9", "eventType": "PublishSubmission", "subject": "PublishOffer", "eventTime": "2021-05-05T09:06:47.575711Z", "dataVersion": "1.0", '$data'} ]'

curl -X POST -H "aeg-sas-key: $key" -d "$event" $endpoint

or

npm run sendEventToEventGridTopic

Microsoft Azure Functions Core Tools CLI

Create Local Functions Project

refer to Microsoft Azure Functions Core Tools CLI for more details

func init MyFunctionProj

# TypeScript
func init LocalFunctionProj --typescript

# JavaScript
func init LocalFunctionProj --javascript

Create New Function in Project

func new

# HTTP Triggered Function
func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"

Run Function Locally

func start

# or

func host start

# or with port number

func host start --port 7071

# or

func start --port 7071

Deploy Project Files

func azure functionapp publish <FunctionAppName>

About

Serverless Framework Azure Functions with TypeScript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published