Skip to content

Commit

Permalink
Add solutions for introductory NodeJS
Browse files Browse the repository at this point in the history
  • Loading branch information
graduta committed Nov 21, 2023
1 parent 3572fdf commit 1910f8f
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
30 changes: 29 additions & 1 deletion 0-Introductory-Exercises/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,29 @@
// Your code goes here
// Your code goes here

const {HttpServer, WebSocket, WebSocketMessage, Log} = require('@aliceo2/web-ui');

const logger = new Log('workshop-2023');

const http = new HttpServer({
port: 8080
}, {
expiration: '60s'
});

http.addStaticPath('public');

http.get('/hello-world', (_, res) => {
res.status(200).json({message: 'Hello World!'});
}, {public: true});

http.get('/hello-private', (_, res) => {
res.status(200).json({message: 'Hi, there'})
});

const ws = new WebSocket(http);

ws.bind('hello', (message) => {
console.log('Server received:', message);
logger.info('test')
return new WebSocketMessage().setCommand('hello-back').setPayload("hello back");
});
6 changes: 6 additions & 0 deletions 0-Introductory-Exercises/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<html>
<body>
<h1> Hello World!</h1>
</body>
<script src="./index.js" type="module"></script>
</html>
17 changes: 17 additions & 0 deletions 0-Introductory-Exercises/public/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Little hack to get token from URL
const url = new URL(window.location);
const token = url.searchParams.get('token');

// Connect to WebSocket
let webSocketConnector = new WebSocket('ws://localhost:8080?token=' + token);

// Send message when connection open
webSocketConnector.onopen = function () {
console.log('Connected');
webSocketConnector.send('{"command":"hello", "payload":"hello, world!", "token": "' + token + '"}');
};
// Send message when connection open
webSocketConnector.onmessage = function (message) {
console.log(message)
};

0 comments on commit 1910f8f

Please sign in to comment.