Skip to content

Commit f49b956

Browse files
committed
first commit
0 parents  commit f49b956

File tree

8 files changed

+137
-0
lines changed

8 files changed

+137
-0
lines changed

.gitignore

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
.DS_Store
2+
*.log
3+
node_modules/
4+
yarn.lock
5+
package-lock.json
6+
tests/
7+
.env

README.md

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Mercure Hub: getting started
2+
3+
![Screenshot](./screenshot.png)
4+
5+
First you have to create a Mercure Hub service on Stackhero.
6+
7+
In Stackhero's configuration, allow "anonymous subscribers" to let the client connect to topics without authentication.
8+
9+
10+
## Back end
11+
12+
Fill the configuration informations in `backend/.env-example` and rename the file to `.env`.
13+
Then start the server with `npm run start`.
14+
15+
16+
## Front end
17+
18+
In `frontend/susbcriber.html`, fill the `endpoint` (domain name of Stackhero's service).
19+
20+
Then open the file `susbcriber.html` in your browser.
21+
22+
The back end code will send datas every seconds to the Mercure Hub, on a the topic `/books/1`.
23+
The frond end will listen datas from the topic `/books/1` and display them.
24+
25+
26+
Congratulations, you have a Mercure Hub up and running! 🎉

backend/.env-example

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
MERCURE_SERVER=XXXXX.stackhero-network.com
2+
MERCURE_PUBLISHER_JWT_KEY=XXXXXXXXXXXXXXX

backend/app.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
require('dotenv').config()
2+
const jwt = require('jsonwebtoken');
3+
const request = require('request-promise-native');
4+
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
5+
6+
if (!process.env.MERCURE_PUBLISHER_JWT_KEY) {
7+
throw Error('You should first fill the .env-example file and the rename it to .env');
8+
}
9+
10+
console.log('You should open the file subscriber.html to see the datas being dispatched.');
11+
12+
const endpoint = process.env.MERCURE_SERVER;
13+
const publisherJwtKey = process.env.MERCURE_PUBLISHER_JWT_KEY;
14+
15+
(async () => {
16+
while (true) {
17+
// Defining the topic where we want to dispatch the new data
18+
const topic = `https://${endpoint}` + '/books/1';
19+
20+
// Defining a random stock count and prepare the data
21+
const stockCount = Math.floor(Math.random() * (100 - 1) + 1);
22+
const data = { topic, stockCount, available: true };
23+
24+
25+
// Generating the bearer (JWT)
26+
const bearer = jwt.sign(
27+
{ mercure: { publish: [ topic ] } },
28+
publisherJwtKey,
29+
{ expiresIn: 60 } // Bearer expiring in one minute
30+
);
31+
32+
33+
// Sending the datas to Mercure Hub that will dispatch them to clients
34+
console.log(`Sending datas: ${JSON.stringify(data)}`);
35+
await request.post(
36+
{
37+
url: `https://${endpoint}/hub`,
38+
auth: { bearer },
39+
form: { topic, data: JSON.stringify(data) },
40+
agentOptions: { rejectUnauthorized: false } // Just for debug, should always be set to true or commented!
41+
}
42+
);
43+
44+
await delay(1000);
45+
}
46+
})().catch(error => {
47+
console.error('');
48+
console.error('🐞 An error occurred!');
49+
console.error(error);
50+
process.exit(1);
51+
});

backend/package.json

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "code-examples",
3+
"version": "1.0.0",
4+
"main": "app.js",
5+
"license": "MIT",
6+
"dependencies": {
7+
"dotenv": "^6.2.0",
8+
"jsonwebtoken": "^8.4.0",
9+
"request": "^2.88.0",
10+
"request-promise-native": "^1.0.5"
11+
},
12+
"scripts": {
13+
"start": "node app.js"
14+
}
15+
}

frontend/book.jpg

347 KB
Loading

frontend/subscriber.html

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<html>
2+
<head>
3+
<title>Mercure Hub subscriber example on Stackhero.io</title>
4+
</head>
5+
<body>
6+
<div id="main" style="font-size: 30px; text-align: center;">Connection...</div>
7+
8+
<script type="application/javascript">
9+
const endpoint = 'XXXXXX.stackhero-network.com'; // PUT YOUR SERVER URL
10+
11+
const url = new URL('https://' + endpoint + '/hub');
12+
const main = document.getElementById('main');
13+
14+
// Add topics to listen to
15+
url.searchParams.append('topic', `https://${endpoint}` + '/users/1234');
16+
url.searchParams.append('topic', `https://${endpoint}` + '/books/1');
17+
18+
// Start SSE
19+
const eventSource = new EventSource(url);
20+
21+
eventSource.onerror = e => {
22+
console.error(e);
23+
main.innerHTML = 'Error when connecting to Mercure Hub ' + endpoint + '. Did you allowed anonymous subscribers on Stackhero\'s console?';
24+
}
25+
26+
eventSource.onopen = () => main.innerHTML = 'Waiting for datas... You should start the Node.js script (npm run start)';
27+
28+
// The callback will be called every time an update is published
29+
eventSource.onmessage = e => {
30+
const data = JSON.parse(e.data);
31+
console.log(data);
32+
main.innerHTML = '<img src="book.jpg" style="height: 200px"><br /><br />Current stock: ' + data.stockCount + ' books';
33+
}
34+
</script>
35+
</body>
36+
</html>

screenshot.png

594 KB
Loading

0 commit comments

Comments
 (0)