UNPKG

2.16 kBJavaScriptView Raw
1const https = require('https');
2const path = require('path');
3const winston = require('winston');
4
5// winston/logging configuration
6const tsFormat = () => new Date().toLocaleTimeString();
7const logger = new winston.Logger({
8 transports: [
9 // colorize the output to the console
10 new winston.transports.Console({
11 timestamp: tsFormat,
12 colorize: true,
13 }),
14 ],
15});
16
17class EdgeCastPurge {
18 /**
19 * constructor
20 * @param {string} token - the api token
21 * @param {string} customerId - the customer id
22 */
23 constructor(token, customerId) {
24 this.token = token;
25 this.customerId = customerId;
26 this.endpoint = path.join('/v2', 'mcc', 'customers', customerId, 'edge', 'purge');
27
28 this.headers = {
29 Authorization: `tok: ${token}`,
30 Accept: 'application/json',
31 'Content-Type': 'application/json',
32 };
33 }
34
35 /**
36 * purge
37 * @param {array} purge list - resources to purge
38 */
39 purge(toPurge) {
40 const purgeList = typeof toPurge === 'string' ? [toPurge] : toPurge;
41
42 return Promise.all(purgeList.map(resourceURL => this.purgeRsource(resourceURL)));
43 }
44
45 purgeRsource(resourceURL) {
46 return new Promise((resolve, reject) => {
47 const postData = {
48 MediaPath: resourceURL,
49 MediaType: '3',
50 };
51
52 const chunk = [];
53 const req = https.request(
54 {
55 method: 'PUT',
56 hostname: 'api.edgecast.com',
57 port: 443,
58 path: this.endpoint,
59 headers: this.headers,
60 },
61 // prettier-ignore
62 (res) => {
63 res.on('data', (d) => {
64 chunk.push(d);
65 });
66 res.on('end', () => {
67 const endData = chunk.join();
68 if (res.statusCode >= 200 && res.statusCode < 300) {
69 logger.info(`purged: ${resourceURL}`);
70 return resolve(endData);
71 }
72 logger.error(`error purging: ${resourceURL}; err=${endData.Message || endData.toString()}`);
73 return reject(endData);
74 });
75 },
76 );
77 req.write(JSON.stringify(postData));
78 req.end();
79 });
80 }
81}
82
83module.exports = EdgeCastPurge;