-
Notifications
You must be signed in to change notification settings - Fork 0
/
broccoli-thumbor-writer.js
75 lines (60 loc) · 2.2 KB
/
broccoli-thumbor-writer.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
'use strict';
const ThumborUrlBuilder = require('thumbor-url-builder');
const { ensureDirSync } = require('fs-extra');
const Plugin = require('broccoli-plugin');
const { join } = require('path');
class ThumborImageComposerPlugin extends Plugin {
constructor(inputNodes, options = {}, metaData, ui) {
super(inputNodes, options);
this.thumborOptions = options;
this.metaData = metaData;
this.ui = ui;
}
build() {
let sourcePath = this.inputPaths[0];
let destinationPath = join(this.outputPath, '/');
ensureDirSync(destinationPath);
// TODO:: This is a hacky fix for 1-level deep folder. Figure out a stable solution
// for deep-nested folders for images.
let folders = this.input.readdirSync(sourcePath);
let filesPromise = [];
let files = [];
folders.forEach((folder) => {
files = this.input.readdirSync(folder);
files
.forEach((file) => {
let folderedFile = `${folder}/${file}`;
filesPromise.push(
this.constructMeta(folderedFile).then(([filePathKey, meta]) => {
this.metaData[filePathKey] = meta;
})
);
});
Promise.all(filesPromise).then(() => {
this.output.writeFileSync('thumbor-asset-manifest.json', JSON.stringify(this.metaData));
});
});
}
constructMeta(file) {
const thumborURL = new ThumborUrlBuilder(process.env.THUMBOR_SECRET_KEY, this.thumborOptions.host);
const sizesToConvert = this.thumborOptions.sizes;
let meta = {};
let filePath = join(this.thumborOptions.rootURL, this.thumborOptions.sourceDir, file);
let fullFilePath = `${this.thumborOptions.assetPrepend}${filePath}`;
let currentGeneratedURL;
sizesToConvert.forEach((size) => {
if (this.thumborOptions.enabled) {
currentGeneratedURL = thumborURL
.setImagePath(fullFilePath)
.resize(size, 0)
.smartCrop(true)
.buildUrl();
} else {
currentGeneratedURL = filePath;
}
meta[size] = currentGeneratedURL; // Adds the first key generated to the meta.
});
return Promise.resolve([file, meta]);
}
}
module.exports = ThumborImageComposerPlugin;