add javascript example

Signed-off-by: Sarthak Sharma <sartsharma@microsoft.com>
This commit is contained in:
Sarthak Sharma 2022-11-11 01:24:56 +05:30
parent 568beceeff
commit eb05e090d2
13 changed files with 9330 additions and 4 deletions

View File

@ -34,15 +34,14 @@ async Task subscribeToConfigUpdates()
{
// Add delay to allow app channel to be ready
Thread.Sleep(3000);
try
{
try{
var subscription = await httpClient.GetStringAsync($"{baseURL}/v1.0-alpha1/configuration/{DAPR_CONFIGURATION_STORE}/subscribe");
if (subscription.Contains("errorCode"))
{
Console.WriteLine("Error subscribing to config updates, err:" + subscription);
Environment.Exit(1);
}
Console.WriteLine("App subscribed to config changes with subscription id: " + subscription);
Console.WriteLine("App subscribed to config changes with subscription id: " + subscription);
}
catch (Exception ex)
{
@ -59,7 +58,7 @@ async Task readConfigurationChanges()
using var sr = new StreamReader(request.Body);
var config = await sr.ReadToEndAsync();
dynamic update = JObject.Parse(config);
Console.WriteLine("Configuration update " + update.items.ToString(Formatting.None));
Console.WriteLine("Configuration update "+ update.items.ToString(Formatting.None));
});
await app.StartAsync();
}

View File

@ -0,0 +1,5 @@
##lint files
*.cjs
##node modules
node_modules

View File

@ -0,0 +1,73 @@
# Dapr Configuration API
In this quickstart, you'll create a microservice which makes use of Dapr's Configuration API. Configuration items are key/value pairs containing configuration data such as app ids, partition keys, database names etc. The service gets configuration items from the configuration store and subscribes for configuration updates.
Visit [this](https://docs.dapr.io/developing-applications/building-blocks/configuration/) link for more information about Dapr and Configuration API.
> **Note:** This example leverages HTTP `requests` only. If you are looking for the example using the Dapr Client SDK (recommended) [click here](../sdk/).
This quickstart includes one service:
- Node service `order-processor`
## Run order-updater app
> **Note:** `order-updater` app adds configuration items to the configuration store and keeps updating their value to simulate dynamic changes to configuration data. You need to start and keep it running before running `order-processor` service.
1. Navigate to [`order-updater`](./../../order-updater/) directory.
2. Check the [`Readme`](./../../order-updater/README.md) to start the app and keep it running in the terminal.
<!-- STEP
name: Run order-updater service
background: true
sleep: 10
timeout: 90
-->
```bash
cd ./../../order-updater
go run .
```
<!-- END_STEP -->
3. This will add configuration items to redis config store and keep updating their values.
## Run order-processor
1. Navigate to folder and install dependencies:
<!-- STEP
name: Install Node dependencies
-->
```bash
cd ./order-processor
npm install
```
<!-- END_STEP -->
1. Run the Node app with Dapr:
<!-- STEP
name: Run order-processor service
expected_stdout_lines:
- '== APP == Configuration for orderId1: { orderId1: { value: '
- '== APP == Configuration for orderId2: { orderId2: { value: '
- '== APP == App subscribed to config changes with subscription id:'
- '== APP == Configuration update {"orderId1":{"value":'
- '== APP == Configuration update {"orderId2":{"value":'
- "Exited App successfully"
expected_stderr_lines:
output_match_mode: substring
match_order: none
timeout: 30
-->
```bash
cd ./order-processor
dapr run --app-id order-processor --components-path ../../../components/ --app-port 6001 -- node index.js
```
<!-- END_STEP -->

View File

@ -0,0 +1,2 @@
include ../../../docker.mk
include ../../../validate.mk

View File

@ -0,0 +1,67 @@
import axios from "axios";
import express from "express";
const DAPR_HOST = process.env.DAPR_HOST ?? "localhost";
let DAPR_PORT = process.env.DAPR_HTTP_PORT ?? 3500;
let APP_PORT = process.env.APP_PORT ?? 6001;
const DAPR_CONFIGURATION_STORE = "configstore";
const BASE_URL = `http://${DAPR_HOST}:${DAPR_PORT}/v1.0-alpha1/configuration/${DAPR_CONFIGURATION_STORE}`;
const CONFIGURATION_ITEMS = ["orderId1", "orderId2"];
const app = express();
app.use(express.json());
async function main() {
// Get config items from the config store
CONFIGURATION_ITEMS.forEach((item) => {
axios
.get(`${BASE_URL}?key=${item}`)
.then((response) => {
console.log("Configuration for " + item + ":", response.data);
})
.catch((error) => {
console.log("Could not get config item, err:" + error);
process.exit(1);
});
});
subscribeToConfigUpdates();
readConfigurationChanges();
// Exit app after 20 seconds
setTimeout(() => {
process.exit(0);
}, 20000);
}
async function subscribeToConfigUpdates() {
// Add delay to allow app channel to be ready
await sleep(3000);
// Subscribe to config updates
axios
.get(`${BASE_URL}/subscribe`)
.then((response) => {
console.log("App subscribed to config changes with subscription id: ", response.data);
})
.catch((error) => {
console.log("Error subscribing to config updates, err:" + error);
process.exit(1);
});
}
async function readConfigurationChanges() {
// Create POST endpoint to receive config updates
app.post("/configuration/configstore/*", (req, res) => {
console.log("Configuration update", JSON.stringify(req.body.items));
res.sendStatus(200);
});
app.listen(APP_PORT, () => console.log("App listening for config updates"));
}
async function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
main().catch((e) => console.error(e));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
{
"name": "order-processor",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node ."
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.25.0",
"express": "^4.18.2"
},
"devDependencies": {
"eslint": "^8.8.0",
"eslint-plugin-react": "^7.28.0"
}
}

View File

@ -0,0 +1,5 @@
##lint files
*.cjs
##node modules
node_modules

View File

@ -0,0 +1,70 @@
# Dapr Configuration API
In this quickstart, you'll create a microservice which makes use of Dapr's Configuration API. Configuration items are key/value pairs containing configuration data such as app ids, partition keys, database names etc. The service gets configuration items from the configuration store and subscribes for configuration updates.
Visit [this](https://docs.dapr.io/developing-applications/building-blocks/configuration/) link for more information about Dapr and Configuration API.
This quickstart includes one service:
- Node service `order-processor`
## Run order-updater app
> **Note:** `order-updater` app adds configuration items to the configuration store and keeps updating their value to simulate dynamic changes to configuration data. You need to start and keep it running before running `order-processor` service.
1. Navigate to [`order-updater`](./../../order-updater/) directory.
2. Check the [`Readme`](./../../order-updater/README.md) to start the app and keep it running in the terminal.
<!-- STEP
name: Run order-updater service
background: true
sleep: 10
timeout: 90
-->
```bash
cd ./../../order-updater
go run .
```
<!-- END_STEP -->
3. This will add configuration items to redis config store and keep updating their values.
## Run order-processor
1. Navigate to folder and install dependencies:
<!-- STEP
name: Install Node dependencies
-->
```bash
cd ./order-processor
npm install
```
<!-- END_STEP -->
1. Run the Node app with Dapr:
<!-- STEP
name: Run order-processor service
expected_stdout_lines:
- '== APP == Configuration for orderId1: {"key":"orderId1","value":'
- '== APP == Configuration for orderId2: {"key":"orderId2","value":'
- '== APP == Configuration update {"orderId1":{"key":"orderId1","value":'
- '== APP == Configuration update {"orderId2":{"key":"orderId2","value":'
- "Exited App successfully"
expected_stderr_lines:
output_match_mode: substring
match_order: none
timeout: 30
-->
```bash
cd ./order-processor
dapr run --app-id order-processor --components-path ../../../components/ --app-protocol grpc --dapr-grpc-port 3500 -- node index.js
```
<!-- END_STEP -->

View File

@ -0,0 +1,2 @@
include ../../../docker.mk
include ../../../validate.mk

View File

@ -0,0 +1,42 @@
import { CommunicationProtocolEnum, DaprClient } from "@dapr/dapr";
// JS SDK does not support Configuration API over HTTP protocol yet
const protocol = CommunicationProtocolEnum.GRPC;
const host = process.env.DAPR_HOST ?? "localhost";
const port = process.env.DAPR_GRPC_PORT ?? 3500;
const DAPR_CONFIGURATION_STORE = "configstore";
const CONFIGURATION_ITEMS = ["orderId1", "orderId2"];
async function main() {
const client = new DaprClient(host, port, protocol);
// Get config items from the config store
try {
const config = await client.configuration.get(DAPR_CONFIGURATION_STORE, CONFIGURATION_ITEMS);
Object.keys(config.items).forEach((key) => {
console.log("Configuration for " + key + ":", JSON.stringify(config.items[key]));
});
} catch (error) {
console.log("Could not get config item, err:" + error);
process.exit(1);
}
// Subscribe to config updates
try {
const stream = await client.configuration.subscribeWithKeys(
DAPR_CONFIGURATION_STORE,
CONFIGURATION_ITEMS,
(config) => {
console.log("Configuration update", JSON.stringify(config.items));
}
);
// Exit app after 20 seconds
setTimeout(() => {
process.exit(0);
}, 20000);
} catch (error) {
console.log("Error subscribing to config updates, err:" + error);
process.exit(1);
}
}
main().catch((e) => console.error(e));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
{
"name": "order-processor",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node ."
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@dapr/dapr": "^2.5.0"
},
"devDependencies": {
"eslint": "^8.8.0",
"eslint-plugin-react": "^7.28.0"
}
}