@666666/messagejs
Version:
A message sending util
88 lines (87 loc) • 2.31 kB
JavaScript
import got from 'got';
import { URL } from 'url';
import { assignIn } from 'lodash-es';
class Bark {
barkConfig = {
serverUrl: ''
};
baseUrl = '';
getBaseUrl(deviceKey, path) {
const baseUrl = new URL(deviceKey + path, this.baseUrl);
return baseUrl.toString();
}
constructor(config) {
if (!config.serverUrl) {
throw Error('serverUrl is required!');
}
this.baseUrl = config.serverUrl;
assignIn(this.barkConfig, config);
}
/**
* push
*/
async push(option) {
const pushList = [];
const currentDeviceKeys = option.deviceKey || this.barkConfig.defaultPushOption?.deviceKey;
if (!currentDeviceKeys) {
throw Error('deviceKey is required!');
}
const { title, body } = option;
if (!title || !body) {
throw Error('title and body is required!');
}
const deviceKeys = currentDeviceKeys.split(',');
deviceKeys.forEach((deviceKey) => {
const url = this.getBaseUrl(deviceKey, '');
pushList.push(got.post(url, {
json: assignIn(this.barkConfig.defaultPushOption, option),
}));
});
try {
const res = await Promise.all(pushList);
return res.map((d) => {
return JSON.parse(d.body);
});
}
catch (error) {
return Promise.reject(error);
}
}
/**
* info
*/
async info() {
try {
const res = await got(`${this.barkConfig.serverUrl}/info`);
return JSON.parse(res.body);
}
catch (error) {
return Promise.reject(error);
}
}
/**
* ping
*/
async ping() {
try {
const res = await got(`${this.barkConfig.serverUrl}/ping`);
return JSON.parse(res.body);
}
catch (error) {
return Promise.reject(error);
}
}
/**
* healthz
*/
async healthz() {
try {
const res = await got(`${this.barkConfig.serverUrl}/healthz`);
return res.body;
}
catch (error) {
return Promise.reject(error);
}
}
}
export default Bark;