-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcard-size.js
88 lines (76 loc) · 2.6 KB
/
card-size.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
// card_size.js
//
// An object for calculating the total size of an adaptive card
/*jshint esversion: 6 */ // Help out our linter
const when = require('when');
const request = require('request-promise');
const traverse = require('traverse');
class CardSize {
/**
* Size Object
*
* Returned by the caculateRoughCardSize method
*
* @instance
* @namespace size
* @property {int} jsonSize - Size of the card JSON in bytes.
* @property {object} images - An arry of objects that include the image's url and size
* @property {object} imageErrors - An arry of objects that include the url of images which could not be fetched
* @property {int} totalSize - Sum of the JSON and image size
*/
/**
* calculate the size of a card object along with the
* size of any downloaded images
*
* @function calculateRoughCardSize
* @param {object} card - the Adaptive Card object to calculate
* @return {Promise.<size>} - object with details about the size of the card
*/
async calculateRoughCardSize(card) {
if ((card === null) || (typeof card !== 'object') ||
(!card.type) || (card.type.toLowerCase() != "adaptivecard") ||
(!card.body) || (typeof card.body != 'object') ||
(!card.body.length)) {
return when.reject(new TypeError(`CardSize.calculate(): invalid card type`));
}
let size = {
jsonSize: JSON.stringify(card).length,
images: [],
imageErrors: []
};
size.total = size.jsonSize;
let imageSizePromises = [];
traverse(card.body).map((x) => {
if ((typeof x === 'object') && ('type' in x) &&
((x.type.toLowerCase() === 'image') ||
(x.type.toLowerCase() === 'backgroundimage'))) {
console.log(x.url);
imageSizePromises.push(request.head(x.url).then((res) => {
if (res['content-length'] !== undefined) {
let imgSize = parseInt(res['content-length']);
size.images.push({url: x.url, size: imgSize});
size.total += imgSize;
} else {
throw new Error(`Could not determine size for ${x.url}`);
}
}).catch((e) => {
size.imageErrors.push({url: x.url, error: e.message});
}));
}
}, size, imageSizePromises);
return when.all(imageSizePromises).then(() => {
return when(size);
});
}
}
module.exports = CardSize;
// Test Module In Place
/*
let cardSize = new CardSize();
let card = require('./res/design/agenda.json');
cardSize.calculateRoughCardSize(card).then((sizeInfo) => {
console.log(sizeInfo);
}).catch((e) => {
console.error(`lookup failed: ${e.message}`);
});
*/