trackmyd-bot/src/api.js

128 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-02-20 15:51:31 +01:00
const fetch = require('node-fetch');
2020-05-12 23:40:49 +02:00
const { api } = require('../config.json');
2019-02-22 17:18:43 +01:00
const logger = require('./logger');
2019-02-20 15:51:31 +01:00
const devicesPath = `${api.baseURL}${api.paths.devices}`;
2019-02-22 17:18:43 +01:00
function getDevicesAPI() {
2019-02-20 15:51:31 +01:00
const init = {
method: 'GET',
headers: api.headers,
};
return fetch(devicesPath, init);
}
2019-02-22 17:18:43 +01:00
function getDevices() {
return getDevicesAPI()
.then((res) => {
if (res.status === 404) {
throw new Error('DevicesNotFound');
} else if (!res.ok) {
throw new Error(res);
}
return res.json();
})
.then(json => json)
.catch((err) => {
logger.logError(err);
2019-03-04 20:07:46 +01:00
throw err;
2019-02-22 17:18:43 +01:00
});
}
function getInfoDeviceAPI(name) {
2019-02-20 15:51:31 +01:00
const init = {
method: 'GET',
headers: api.headers,
};
const path = `${devicesPath}?name=${name}`;
return fetch(path, init);
}
2019-02-22 17:18:43 +01:00
function getInfoDevice(deviceId) {
return getInfoDeviceAPI(deviceId)
.then((res) => {
if (res.status === 404) {
throw new Error('DevicesNotFound');
} else if (!res.ok) {
throw new Error(res);
}
return res.json();
})
2019-02-23 23:21:39 +01:00
.then((json) => {
if (!Object.prototype.hasOwnProperty.call(json, 'position')) {
throw new Error('PositionNotFound');
}
return json;
})
2019-02-22 17:18:43 +01:00
.catch((err) => {
logger.logError(err);
2019-03-04 20:07:46 +01:00
throw err;
2019-02-22 17:18:43 +01:00
});
}
function addDeviceAPI(name) {
2019-02-20 15:51:31 +01:00
const body = {
name,
};
const init = {
method: 'POST',
headers: api.headers,
body: JSON.stringify(body),
};
return fetch(devicesPath, init);
}
2019-02-22 17:18:43 +01:00
function addDevice(name) {
return addDeviceAPI(name)
.then((res) => {
if (!res.ok) {
throw new Error(res);
}
return res.json();
})
.then(json => json)
.catch((err) => {
logger.logError(err);
2019-03-04 20:07:46 +01:00
throw err;
2019-02-22 17:18:43 +01:00
});
}
function removeDeviceAPI(id) {
2019-02-20 15:51:31 +01:00
const init = {
method: 'DELETE',
headers: api.headers,
};
const path = `${devicesPath}${id}`;
return fetch(path, init);
}
2019-02-22 17:18:43 +01:00
function removeDevice(deviceId) {
return removeDeviceAPI(deviceId)
.then((res) => {
if (!res.ok) {
throw new Error(res);
}
return res.status;
})
.then(json => json)
.catch((err) => {
logger.logError(err);
2019-03-04 20:07:46 +01:00
throw err;
2019-02-22 17:18:43 +01:00
});
}
2019-02-20 15:51:31 +01:00
module.exports.getDevices = getDevices;
module.exports.getInfoDevice = getInfoDevice;
module.exports.addDevice = addDevice;
module.exports.removeDevice = removeDevice;