Skip to content

Instantly share code, notes, and snippets.

@olegpolyakov
Created April 7, 2020 10:20
Show Gist options
  • Save olegpolyakov/2d31d6d4e069a0e36903b5bb20593adb to your computer and use it in GitHub Desktop.
Save olegpolyakov/2d31d6d4e069a0e36903b5bb20593adb to your computer and use it in GitHub Desktop.
MailerLite Node.js Client
const http = require('request');
const MAILERLITE_API_URL = 'http://api.mailerlite.com/api/v2';
module.exports = MAILERLITE_API_KEY => {
return {
subscribers: {
get(id) {
return request({
method: 'get',
url: id ? `/subscribers/${id}` : '/subscribers'
}).catch(error => {
if (error.code === 123) {
return null;
} else {
throw error;
}
});
},
create(data) {
return request({
method: 'post',
url: '/subscribers',
body: data,
json: true
});
},
update(id, data) {
return request({
method: 'put',
url: `/subscribers/${id}`,
body: data,
json: true
});
},
search(query) {
return request({
method: 'get',
url: `/subscribers/search?query=${query}`
});
}
}
};
function request({ method, url, headers = {}, ...rest }) {
return new Promise((resolve, reject) => {
http[method](`${MAILERLITE_API_URL}${url}`, {
headers: {
'X-MailerLite-ApiKey': MAILERLITE_API_KEY,
...headers
},
...rest
}, (error, response, body) => {
if (error) {
reject(error);
} else if (response.statusCode !== 200 && response.statusCode !== 201 && response.statusCode !== 204) {
const response = JSON.parse(body);
reject(response.error);
} else {
resolve(JSON.parse(body));
}
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment