forked from openhab/openhab-alexa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.js
103 lines (91 loc) · 2.83 KB
/
rest.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Copyright (c) 2014-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
var https = require('https');
var config = require('./config');
var logger = require('./log');
/**
* Returns all items
*/
function getItems(token, success, failure) {
return getItem(token, null, success, failure);
}
/**
* Returns a single item
*/
function getItem(token, itemName, success, failure) {
var options = httpItemOptions(token, itemName);
https.get(options, function (response) {
var body = '';
response.on('data', function (data) {
body += data.toString('utf-8');
});
response.on('end', function () {
if (response.statusCode != 200) {
failure({
message: 'Error response ' + response.statusCode
});
logger.info('getItem failed for path: ' + options.path +
' code: ' + response.statusCode + ' body: ' + body);
return;
}
var resp = JSON.parse(body);
success(resp);
});
response.on('error', function (e) {
failure(e);
});
})
.end();
}
/**
* POST a command to a item
**/
function postItemCommand(token, itemName, value, success, failure) {
var options = httpItemOptions(token, itemName, 'POST', value.length);
var req = https.request(options, function (response) {
var body = '';
if (response.statusCode == 200 || response.statusCode == 201) {
success(response);
} else {
failure({
message: 'Error response ' + response.statusCode
});
}
response.on('error', function (e) {
failure(e);
});
});
req.write(value);
req.end();
}
/**
* Returns a http option object sutiable for item commands
*/
function httpItemOptions(token, itemname, method, length) {
var options = {
hostname: config.host,
port: config.port,
path: config.path + (itemname || ''),
method: method || 'GET',
headers: {}
};
if (config.userpass) {
options.auth = config.userpass;
} else {
options.headers['Authorization'] = 'Bearer ' + token;
}
if (method === 'POST' || method === 'PUT') {
options.headers['Content-Type'] = 'text/plain';
options.headers['Content-Length'] = length;
}
return options;
}
module.exports.getItems = getItems;
module.exports.getItem = getItem;
module.exports.postItemCommand = postItemCommand;