Skip to content

Commit fd4713e

Browse files
authored
Merge pull request #272781 from diberry/diberry/0419-signalr-quickstart
Signalr Node + Functions quickstart
2 parents 5ccb1e7 + 19bd74b commit fd4713e

File tree

1 file changed

+56
-205
lines changed

1 file changed

+56
-205
lines changed

articles/azure-signalr/signalr-quickstart-azure-functions-javascript.md

Lines changed: 56 additions & 205 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,17 @@
11
---
2-
title: Azure SignalR Service serverless quickstart - Javascript
2+
title: Azure SignalR Service serverless quickstart - JavaScript
33
description: A quickstart for using Azure SignalR Service and Azure Functions to create an App showing GitHub star count using JavaScript.
44
author: vicancy
55
ms.author: lianwei
6-
ms.date: 12/15/2022
6+
ms.date: 04/19/2023
77
ms.topic: quickstart
88
ms.service: signalr
99
ms.devlang: javascript
1010
ms.custom: devx-track-js, mode-api
1111
---
12-
# Quickstart: Create a serverless app with Azure Functions and SignalR Service using Javascript
12+
# Quickstart: Create a serverless app with Azure Functions and SignalR Service using JavaScript
1313

14-
In this article, you'll use Azure SignalR Service, Azure Functions, and JavaScript to build a serverless application to broadcast messages to clients.
15-
16-
> [!NOTE]
17-
> You can get all code used in the article from [GitHub](https://github.com/aspnet/AzureSignalR-samples/tree/main/samples/QuickStartServerless/javascript).
14+
In this article, you use Azure SignalR Service, Azure Functions, and JavaScript to build a serverless application to broadcast messages to clients.
1815

1916
## Prerequisites
2017

@@ -23,11 +20,11 @@ This quickstart can be run on macOS, Windows, or Linux.
2320
| Prerequisite | Description |
2421
| --- | --- |
2522
| An Azure subscription |If you don't have a subscription, create an [Azure free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F)|
26-
| A code editor | You'll need a code editor such as [Visual Studio Code](https://code.visualstudio.com/). |
27-
| [Azure Functions Core Tools](https://github.com/Azure/azure-functions-core-tools#installing)| Requires version 2.7.1505 or higher to run Python Azure Function apps locally.|
28-
|[Node.js](https://nodejs.org/en/download/)| See supported node.js versions in the [Azure Functions JavaScript developer guide](../azure-functions/functions-reference-node.md#node-version).|
29-
| [Azurite](../storage/common/storage-use-azurite.md)| SignalR binding needs Azure Storage. You can use a local storage emulator when a function is running locally. |
30-
| [Azure CLI](/cli/azure/install-azure-cli)| Optionally, you can use the Azure CLI to create an Azure SignalR Service instance. |
23+
| A code editor | You need a code editor such as [Visual Studio Code](https://code.visualstudio.com/). |
24+
| [Azure Functions Core Tools](https://github.com/Azure/azure-functions-core-tools#installing)| Requires version 4.0.5611 or higher to run Node.js v4 programming model.|
25+
|[Node.js LTS](https://nodejs.org/en/download/)| See supported node.js versions in the [Azure Functions JavaScript developer guide](../azure-functions/functions-reference-node.md#node-version).|
26+
| [Azurite](../storage/common/storage-use-azurite.md)| SignalR binding needs Azure Storage. You can use a local storage emulator when a function is running locally. |
27+
| [Azure CLI](/cli/azure/install-azure-cli)| Optionally, you can use the Azure CLI to create an Azure SignalR Service instance.
3128

3229
## Create an Azure SignalR Service instance
3330

@@ -38,12 +35,11 @@ This quickstart can be run on macOS, Windows, or Linux.
3835
Make sure you have Azure Functions Core Tools installed.
3936

4037
1. Open a command line.
41-
1. Create project directory and then change to it.
38+
1. Create project directory and then change into it.
4239
1. Run the Azure Functions `func init` command to initialize a new project.
4340

4441
```bash
45-
# Initialize a function project
46-
func init --worker-runtime javascript
42+
func init --worker-runtime javascript --language javascript --model V4
4743
```
4844

4945
## Create the project functions
@@ -54,7 +50,7 @@ After you initialize a project, you need to create functions. This project requi
5450
- `negotiate`: Allows a client to get an access token.
5551
- `broadcast`: Uses a time trigger to periodically broadcast messages to all clients.
5652

57-
When you run the `func new` command from the root directory of the project, the Azure Functions Core Tools creates the function source files storing them in a folder with the function name. You'll edit the files as necessary replacing the default code with the app code.
53+
When you run the `func new` command from the root directory of the project, the Azure Functions Core Tools creates the function source files storing them in a folder with the function name. You edit the files as necessary replacing the default code with the app code.
5854

5955
### Create the index function
6056

@@ -64,52 +60,10 @@ When you run the `func new` command from the root directory of the project, the
6460
func new -n index -t HttpTrigger
6561
```
6662

67-
1. Edit *index/function.json* and replace the contents with the following json code:
68-
69-
```json
70-
{
71-
"bindings": [
72-
{
73-
"authLevel": "anonymous",
74-
"type": "httpTrigger",
75-
"direction": "in",
76-
"name": "req",
77-
"methods": [
78-
"get",
79-
"post"
80-
]
81-
},
82-
{
83-
"type": "http",
84-
"direction": "out",
85-
"name": "res"
86-
}
87-
]
88-
}
89-
```
63+
1. Edit *src/functions/httpTrigger.js* and replace the contents with the following json code:
64+
65+
:::code language="javascript" source="~/azuresignalr-samples/samples/QuickStartServerless/javascript/v4-programming-model/src/functions/index.js":::
9066

91-
1. Edit *index/index.js* and replace the contents with the following code:
92-
93-
```javascript
94-
var fs = require('fs').promises
95-
96-
module.exports = async function (context, req) {
97-
const path = context.executionContext.functionDirectory + '/../content/index.html'
98-
try {
99-
var data = await fs.readFile(path);
100-
context.res = {
101-
headers: {
102-
'Content-Type': 'text/html'
103-
},
104-
body: data
105-
}
106-
context.done()
107-
} catch (err) {
108-
context.log.error(err);
109-
context.done(err);
110-
}
111-
}
112-
```
11367

11468
### Create the negotiate function
11569

@@ -119,42 +73,10 @@ When you run the `func new` command from the root directory of the project, the
11973
func new -n negotiate -t HttpTrigger
12074
```
12175

122-
1. Edit *negotiate/function.json* and replace the contents with the following json code:
123-
```json
124-
{
125-
"disabled": false,
126-
"bindings": [
127-
{
128-
"authLevel": "anonymous",
129-
"type": "httpTrigger",
130-
"direction": "in",
131-
"methods": [
132-
"post"
133-
],
134-
"name": "req",
135-
"route": "negotiate"
136-
},
137-
{
138-
"type": "http",
139-
"direction": "out",
140-
"name": "res"
141-
},
142-
{
143-
"type": "signalRConnectionInfo",
144-
"name": "connectionInfo",
145-
"hubName": "serverless",
146-
"connectionStringSetting": "AzureSignalRConnectionString",
147-
"direction": "in"
148-
}
149-
]
150-
}
151-
```
152-
1. Edit *negotiate/index.js* and replace the content with the following JavaScript code:
153-
```js
154-
module.exports = async function (context, req, connectionInfo) {
155-
context.res.body = connectionInfo;
156-
};
157-
```
76+
1. Edit *src/functions/negotiate.js* and replace the contents with the following json code:
77+
78+
:::code language="javascript" source="~/azuresignalr-samples/samples/QuickStartServerless/javascript/v4-programming-model/src/functions/negotiate.js":::
79+
15880
### Create a broadcast function.
15981

16082
1. Run the following command to create the `broadcast` function.
@@ -163,73 +85,9 @@ When you run the `func new` command from the root directory of the project, the
16385
func new -n broadcast -t TimerTrigger
16486
```
16587

166-
1. Edit *broadcast/function.json* and replace the contents with the following code:
167-
168-
```json
169-
{
170-
"bindings": [
171-
{
172-
"name": "myTimer",
173-
"type": "timerTrigger",
174-
"direction": "in",
175-
"schedule": "*/5 * * * * *"
176-
},
177-
{
178-
"type": "signalR",
179-
"name": "signalRMessages",
180-
"hubName": "serverless",
181-
"connectionStringSetting": "AzureSignalRConnectionString",
182-
"direction": "out"
183-
}
184-
]
185-
}
186-
```
187-
188-
1. Edit *broadcast/index.js* and replace the contents with the following code:
189-
190-
```javascript
191-
var https = require('https');
192-
193-
var etag = '';
194-
var star = 0;
195-
196-
module.exports = function (context) {
197-
var req = https.request("https://api.github.com/repos/azure/azure-signalr", {
198-
method: 'GET',
199-
headers: {'User-Agent': 'serverless', 'If-None-Match': etag}
200-
}, res => {
201-
if (res.headers['etag']) {
202-
etag = res.headers['etag']
203-
}
204-
205-
var body = "";
206-
207-
res.on('data', data => {
208-
body += data;
209-
});
210-
res.on("end", () => {
211-
if (res.statusCode === 200) {
212-
var jbody = JSON.parse(body);
213-
star = jbody['stargazers_count'];
214-
}
215-
216-
context.bindings.signalRMessages = [{
217-
"target": "newMessage",
218-
"arguments": [ `Current star count of https://github.com/Azure/azure-signalr is: ${star}` ]
219-
}]
220-
context.done();
221-
});
222-
}).on("error", (error) => {
223-
context.log(error);
224-
context.res = {
225-
status: 500,
226-
body: error
227-
};
228-
context.done();
229-
});
230-
req.end();
231-
}
232-
```
88+
1. Edit *src/functions/broadcast.js* and replace the contents with the following code:
89+
90+
:::code language="javascript" source="~/azuresignalr-samples/samples/QuickStartServerless/javascript/v4-programming-model/src/functions/broadcast.js":::
23391

23492
### Create the index.html file
23593

@@ -239,41 +97,37 @@ The client interface for this app is a web page. The `index` function reads HTML
23997
1. Create the file *content/index.html*.
24098
1. Copy the following content to the *content/index.html* file and save it:
24199

100+
:::code language="html" source="~/azuresignalr-samples/samples/QuickStartServerless/javascript/v4-programming-model/src/content/index.html":::
242101

243-
```html
244-
<html>
245-
246-
<body>
247-
<h1>Azure SignalR Serverless Sample</h1>
248-
<div id="messages"></div>
249-
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7/signalr.min.js"></script>
250-
<script>
251-
let messages = document.querySelector('#messages');
252-
const apiBaseUrl = window.location.origin;
253-
const connection = new signalR.HubConnectionBuilder()
254-
.withUrl(apiBaseUrl + '/api')
255-
.configureLogging(signalR.LogLevel.Information)
256-
.build();
257-
connection.on('newMessage', (message) => {
258-
document.getElementById("messages").innerHTML = message;
259-
});
260-
261-
connection.start()
262-
.catch(console.error);
263-
</script>
264-
</body>
265-
266-
</html>
267-
```
102+
### Setup Azure Storage
268103

104+
Azure Functions requires a storage account to work. Choose either of the two following options:
269105

270-
### Add the SignalR Service connection string to the function app settings
106+
* Run the free [Azure Storage Emulator](../storage/common/storage-use-azurite.md).
107+
* Use the Azure Storage service. This may incur costs if you continue to use it.
108+
109+
#### [Local emulation](#tab/storage-azurite)
110+
111+
1. Start the Azurite storage emulator:
271112

272-
Azure Functions requires a storage account to work. You can install and run the [Azure Storage Emulator](../storage/common/storage-use-azurite.md). **Or** you can update the setting to use your real storage account with the following command:
273113
```bash
274-
func settings add AzureWebJobsStorage "<storage-connection-string>"
114+
azurite -l azurite -d azurite\debug.log
275115
```
276116

117+
1. Make sure the `AzureWebJobsStorage` in *local.settings.json* set to `UseDevelopmentStorage=true`.
118+
119+
#### [Azure Blob Storage](#tab/azure-blob-storage)
120+
121+
Update the project to use the Azure Blob Storage connection string.
122+
123+
```bash
124+
func settings add AzureWebJobsStorage "<storage-connection-string>"
125+
```
126+
127+
---
128+
129+
### Add the SignalR Service connection string to the function app settings
130+
277131
You're almost done now. The last step is to set the SignalR Service connection string in Azure Function app settings.
278132
279133
1. In the Azure portal, go to the SignalR instance you deployed earlier.
@@ -283,33 +137,30 @@ You're almost done now. The last step is to set the SignalR Service connection s
283137
284138
1. Copy the primary connection string, and execute the command:
285139
286-
```bash
287-
func settings add AzureSignalRConnectionString "<signalr-connection-string>"
288-
```
140+
```bash
141+
func settings add AzureSignalRConnectionString "<signalr-connection-string>"
142+
```
289143
290144
### Run the Azure Function app locally
291145
292-
Start the Azurite storage emulator:
293-
294-
```bash
295-
azurite
296-
```
297-
298146
Run the Azure Function app in the local environment:
299147
300148
```bash
301149
func start
302150
```
303151
304-
> [!NOTE]
305-
> If you see an errors showing read errors on the blob storage, ensure the 'AzureWebJobsStorage' setting in the *local.settings.json* file is set to `UseDevelopmentStorage=true`.
306-
307152
After the Azure Function is running locally, go to `http://localhost:7071/api/index`. The page displays the current star count for the GitHub Azure/azure-signalr repository. When you star or unstar the repository in GitHub, you'll see the refreshed count every few seconds.
308153

309-
Having issues? Try the [troubleshooting guide](signalr-howto-troubleshoot-guide.md) or [let us know](https://aka.ms/asrs/qscsharp)
154+
Having issues? Try the [troubleshooting guide](signalr-howto-troubleshoot-guide.md) or [let us know.](https://aka.ms/asrs/qscsharp)
310155

311156
[!INCLUDE [Cleanup](includes/signalr-quickstart-cleanup.md)]
312157

158+
## Sample code
159+
160+
You can get all code used in the article from GitHub repository:
161+
162+
* [aspnet/AzureSignalR-samples](https://github.com/aspnet/AzureSignalR-samples/tree/main/samples/QuickStartServerless/javascript/v4-programming-model).
163+
313164
## Next steps
314165

315166
In this quickstart, you built and ran a real-time serverless application in localhost. Next, learn more about how to bi-directional communicating between clients and Azure Function with SignalR Service.

0 commit comments

Comments
 (0)