-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
transformer.js
44 lines (40 loc) · 1.29 KB
/
transformer.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
'use strict';
/* eslint-disable no-restricted-syntax, no-param-reassign */
const sharp = require('sharp');
const entries = require('object.entries');
module.exports = transformer;
function transformer(options, size) {
let imageStream = sharp();
for (const [key, value] of entries(options)) {
if (value) {
imageStream = resolveImageStream(key, value, size, imageStream);
}
}
return imageStream;
}
const objectHasOwnProperty = (source, prop) => Object.prototype.hasOwnProperty.call(source, prop);
const hasProp = (value) => typeof value === 'object' && objectHasOwnProperty(value, 'type');
const isObject = (obj) => typeof obj === 'object' && obj !== null;
const validateFormat = (value) => {
if (hasProp(value)) {
return value.type;
}
return value;
};
const validateValue = (value) => {
if (typeof value === 'boolean') {
return null;
}
return value;
};
const resolveImageStream = (key, value, size, imageStream) => {
if (key === 'resize' && isObject(size)) {
imageStream = imageStream.resize(size.width, size.height, size.option);
} else if (key === 'toFormat') {
imageStream = imageStream.toFormat(validateFormat(value), value.options);
} else {
const valid = validateValue(value);
imageStream = imageStream[key](valid);
}
return imageStream;
};