MailChimpClient.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { fetchJson, fetchNothing } from '@overleaf/fetch-utils'
  2. class MailChimpClient {
  3. constructor(apiKey) {
  4. this.apiKey = apiKey
  5. this.dc = apiKey.split('-')[1]
  6. this.baseUrl = `https://${this.dc}.api.mailchimp.com/3.0/`
  7. this.fetchOptions = {
  8. method: 'GET',
  9. basicAuth: {
  10. user: 'any',
  11. password: this.apiKey,
  12. },
  13. }
  14. }
  15. async request(path, options) {
  16. try {
  17. const requestUrl = `${this.baseUrl}${path}`
  18. if (options.method === 'GET') {
  19. return await fetchJson(requestUrl, options)
  20. }
  21. await fetchNothing(requestUrl, options)
  22. } catch (err) {
  23. // if there's a json body in the response, expose it in the error (for compatibility with node-mailchimp)
  24. const errorBody = err.body ? JSON.parse(err.body) : {}
  25. const errWithBody = Object.assign(err, errorBody)
  26. throw errWithBody
  27. }
  28. }
  29. async get(path) {
  30. return await this.request(path, this.fetchOptions)
  31. }
  32. async put(path, body) {
  33. const options = Object.assign({}, this.fetchOptions)
  34. options.method = 'PUT'
  35. options.json = body
  36. return await this.request(path, options)
  37. }
  38. async post(path, body) {
  39. const options = Object.assign({}, this.fetchOptions)
  40. options.method = 'POST'
  41. options.json = body
  42. return await this.request(path, options)
  43. }
  44. async delete(path) {
  45. const options = Object.assign({}, this.fetchOptions)
  46. options.method = 'DELETE'
  47. return await this.request(path, options)
  48. }
  49. async patch(path, body) {
  50. const options = Object.assign({}, this.fetchOptions)
  51. options.method = 'PATCH'
  52. options.json = body
  53. return await this.request(path, options)
  54. }
  55. }
  56. export default MailChimpClient