forked from ThamosIO/gulp-template-mandrill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgulp-template-mandrill.js
77 lines (68 loc) · 2.35 KB
/
gulp-template-mandrill.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
var through = require('through2'),
mandrillApi = require('mandrill-api'),
gutil = require('gulp-util'),
fs = require('fs'),
path = require('path'),
html2txt = require('html-to-text');
PluginError = gutil.PluginError;
const PLUGIN_NAME = 'gulp-template-mandrill';
function gulpTemplateMandrill(opts) {
if(!opts) {
throw new PluginError(PLUGIN_NAME, 'Missing options for ' + PLUGIN_NAME);
}
if(!opts.key) {
throw new PluginError(PLUGIN_NAME, 'Missing mandrill api key for ' +
PLUGIN_NAME);
}
// If no path for JSON is set, use the same as the html files
var mandrill = new mandrillApi.Mandrill(opts.key);
return through.obj(function (file, encoding, callback) {
var params = {},
templateUnknown = false;
if(file.isNull()) {
return callback(null, file);
}
if(file.isBuffer()) {
try {
var fpath = file.path.replace('html', 'json');
var JSONpath = opts.JSONpath ?
path.join(opts.JSONpath, path.basename(fpath)) : fpath;
params = JSON.parse(fs.readFileSync(JSONpath));
} catch (e) {
throw new PluginError(PLUGIN_NAME, e.name + ' - ' + e.message + '\n' +
PLUGIN_NAME + ': You should have a .json file for every .html file.');
}
// set html and txt from file
params.code = file.contents.toString();
params.text = new Buffer(
html2txt.fromString(file.contents.toString())
).toString();
// send to api via mandrill-api
mandrill.templates.update(
params,
function (result) {
gutil.log('Updated template:', result.slug);
callback(null, file);
},
function (e) {
// If the template doesn't exist, add it
if(e.name === 'Unknown_Template') {
mandrill.templates.add(
params,
function (result) {
gutil.log('New template:', result.slug);
callback(null, file);
},
function (e) {
throw new PluginError(PLUGIN_NAME, 'Mandrill error occurred: ' + e.name + ' - ' + e.message);
}
);
} else {
throw new PluginError(PLUGIN_NAME, 'Mandrill error occurred: ' + e.name + ' - ' + e.message);
}
}
);
}
});
}
module.exports = gulpTemplateMandrill;