wkr-util
Version:
Utility library for wkr project.
65 lines (56 loc) • 2.07 kB
JavaScript
const fetch = require('node-fetch')
const {responseData} = require('./index')
const ResponseError = require('./errors/ResponseError')
const {compose, liftA, split, isObject} = require('@cullylarson/f')
// takes an object ({email, name}), a string ("me@example.com"), or a string("My Name <me@example.com>") and returns
// an object ({email, name?})
const parseEmail = addr => {
if(isObject(addr)) return addr
if(addr.indexOf('<') === -1) return {email: addr}
return compose(
parts => ({
name: parts[0].trim(),
email: parts[1].replace('>', '').trim(),
}),
split('<'),
)(addr)
}
// send an email using Sendgrid
// from: can be a string or an object. If object, can be: {from: string, replyTo: string}
// tos: can be a string or an array[string]. If an array, will send multiple emails, one to each address in the list (this will not send one email to multiple recipients).
const send = (apiKey, apiSendUrl, templateId, from, tos, data) => {
tos = liftA(tos).filter(Boolean)
const fromStr = isObject(from)
? from.from
: from
const replyTo = isObject(from) && from.replyTo
? {reply_to: parseEmail(from.replyTo)}
: {}
const query = {
from: parseEmail(fromStr),
...replyTo,
personalizations: tos.map(toAddress => ({
to: [{email: toAddress}],
dynamic_template_data: data,
})),
template_id: templateId,
}
return fetch(apiSendUrl, {
method: 'post',
body: JSON.stringify(query),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
})
.then(responseData)
.then(({response, data}) => {
if(!response.ok || (data.errors && data.errors.length)) {
throw new ResponseError(response.status, data, `Failed to send email. Got status: ${response.status}. Response: ${JSON.stringify(data)}`)
}
})
}
module.exports = {
parseEmail,
send,
}