Skip to content

Instantly share code, notes, and snippets.

@pejalo
Created July 5, 2023 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pejalo/1ff198d5105fbbd9eeceb63b72ab301c to your computer and use it in GitHub Desktop.
Save pejalo/1ff198d5105fbbd9eeceb63b72ab301c to your computer and use it in GitHub Desktop.
Submit nodejs request to Sendy to subscribe email address
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
module.exports = {
subscribe: async (emailAddress) => {
const {
SENDY_API_KEY: apiKey,
SENDY_LIST_ID: listId,
SENDY_SUBSCRIBE_URL: url,
} = process.env;
const body = {
api_key: apiKey,
email: emailAddress,
list: listId,
boolean: 'true',
};
const response = await fetch(url, {
method: "POST",
body: new URLSearchParams(body), // needed for below Content-Type
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
if (response.status !== 200) throw new Error(`${url} responded with status ${response.status}`);
const text = await response.text();
if (text === 'Invalid email address.') throw new Error(`email address invalid: ${emailAddress}`);
const successTexts = ['Already subscribed.', '1', 'true'];
if (!successTexts.includes(text)) throw new Error(`${url} responded with text ${text}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment