wkr-util
Version:
Utility library for wkr project.
79 lines (65 loc) • 3.07 kB
JavaScript
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
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 = _objectSpread(_objectSpread({
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
};
;