forked from WebThingsIO/webthing-node-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
54 lines (47 loc) · 1.09 KB
/
server.js
File metadata and controls
54 lines (47 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import express from 'express';
/** @typedef {import('./thing.js').default} Thing */
class ThingServer {
/**
* Construct the Thing Server.
*
* @param {Thing} thing The Thing to serve.
*/
constructor(thing) {
this.thing = thing;
this.app = express();
this.server = null;
this.app.get('/', (request, response) => {
response.json(this.thing.getThingDescription());
});
this.app.get('/properties/:name', async (request, response) => {
const name = request.params.name;
let value;
try {
value = await this.thing.readProperty(name);
} catch {
response.status(404).send();
return;
}
response.status(200).json(value);
});
}
/**
* Start the Thing Server.
*
* @param {number} port The TCP port number to listen on.
*/
start(port) {
this.server = this.app.listen(port, () => {
console.log(`Web Thing being served on port ${port}`);
});
}
/**
* Stop the Thing Server.
*/
stop() {
if (this.server) {
this.server.close();
}
}
}
export default ThingServer;