-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (46 loc) · 1.37 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
require('dotenv').config()
const { readFile: _readFile } = require('fs')
const { join } = require('path')
const compile = require('mjml')
const { load } = require('cheerio')
const sendgrid = require('@sendgrid/client')
sendgrid.setApiKey(process.env.SENDGRID_API_KEY)
const emails = Object.entries(require('./emails.json'))
const readFile = path =>
new Promise((resolve, reject) => {
_readFile(path, 'utf8', (error, data) => {
error ? reject(error) : resolve(data)
})
})
const getDefaultVersionId = async templateId => {
const [{ body }] = await sendgrid.request({
method: 'GET',
url: `/v3/templates/${templateId}`
})
const version = body.versions
.find(({ name }) => name === 'default')
if (version)
return version.id
throw new Error(`Unable to find the default version for template ${templateId}`)
}
if (require.main === module) {
let i = 0
Promise.all(emails.map(async ([name, id]) => {
const path = join(__dirname, 'src', `${name}.mjml`)
const { html } = compile(await readFile(path), {
validationLevel: 'strict',
minify: true,
filePath: path
})
await sendgrid.request({
method: 'PATCH',
url: `/v3/templates/${id}/versions/${await getDefaultVersionId(id)}`,
body: {
subject: load(html)('title').text(),
html_content: html,
active: 1
}
})
console.log(`Uploaded ${name} (${++i}/${emails.length})`)
}))
}