forked from mozilla/ping-centre
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ping-centre.js
59 lines (52 loc) · 1.51 KB
/
ping-centre.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
"use strict";
require("isomorphic-fetch");
const commonSchema = require("./schemas/commonSchema");
const Joi = require("joi-browser");
const uuid = require("uuid");
const config = require("./config");
class PingCentre {
constructor(topic, clientID, pingEndpoint) {
if (!topic) {
throw new Error("Must specify topic.");
}
this._topic = topic;
this._clientID = clientID || uuid();
this._pingEndpoint = pingEndpoint || config.endpoint;
const schema = require(`./schemas/${topic}`);
this._schema = schema || commonSchema;
}
validate(payload) {
return new Promise((resolve, reject) => {
Joi.validate(payload, this._schema, (err, value) => {
if (err) {
reject(new Error(`Invalid payload ${JSON.stringify(value)}: ${err}.`));
} else {
resolve(value);
}
});
});
}
sendPing(data, validate = true) {
const payload = Object.assign({
topic: this._topic,
client_id: this._clientID
}, data);
let validatePromise = Promise.resolve();
if (validate) {
validatePromise = this.validate(payload);
}
return validatePromise.then(() => {
return fetch(this._pingEndpoint, {method: "POST", body: payload}).then(response => {
if (!response.ok) {
throw new Error(`Ping failure with response code: ${response.status}`);
} else {
return response;
}
});
}).catch(e => {
console.error(e.message);
throw e;
});
}
}
module.exports = PingCentre;