Created
July 5, 2023 03:55
-
-
Save pejalo/1ff198d5105fbbd9eeceb63b72ab301c to your computer and use it in GitHub Desktop.
Submit nodejs request to Sendy to subscribe email address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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