-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
60 lines (47 loc) · 1.73 KB
/
index.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';
const denodeify = require('denodeify');
const fs = require('fs');
const writeFile = denodeify(fs.writeFile);
const request = require('superagent');
function ImageOptim() {
if ('undefined' === typeof Promise) {
throw Error("ES6 Promise support required.\nPlease use a modern version of nodejs or a polyfill");
}
this._baseURL = 'https://imageoptim.com/mozjpeg';
}
ImageOptim.prototype.compress = function(options) {
return new ImageOptimOptionsBuilder(this._baseURL, options);
}
module.exports = ImageOptim;
function ImageOptimOptionsBuilder(baseURL, options) {
this._baseURL = baseURL;
}
ImageOptimOptionsBuilder.prototype.file = function(path) {
if ('string' !== typeof path) throw Error("Source path must be a string");
this._srcFilePath = path;
return this;
};
ImageOptimOptionsBuilder.prototype.save = function(path) {
if ('string' !== typeof path) throw Error("Destination path must be a string");
this._destFilePath = path;
return this;
};
ImageOptimOptionsBuilder.prototype.then = function(resolve, reject) {
return this.end().then(resolve, reject);
};
ImageOptimOptionsBuilder.prototype.end = function() {
if (this._result) return this._result;
const dest = this._destFilePath;
const src = this._srcFilePath;
if (!src) return Promise.reject(Error("Source file path not specified, please use .file()"));
return Promise.resolve(request.post(this._baseURL)
.field('quality', 'medium')
.field('chroma_quality', 'auto')
.attach('file', src))
.then(function(res) {
if (!dest) {
return res.body;
}
return writeFile(dest, res.body);
});
};