This repository has been archived by the owner on Apr 3, 2019. It is now read-only.
/
marketing-email-client.js
77 lines (63 loc) · 2.08 KB
/
marketing-email-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* A client to talk to the basket marketing email server
*/
'use strict';
define([
'lib/xhr',
'lib/marketing-email-errors'
], function (xhr, MarketingEmailErrors) {
function MarketingEmailClient(options) {
options = options || {};
var self = this;
self._xhr = options.xhr || xhr;
self._baseUrl = options.baseUrl;
self._preferencesUrl = options.preferencesUrl;
}
MarketingEmailClient.prototype = {
_request: function (method, endpoint, accessToken, data) {
var url = this._baseUrl + endpoint;
return this._xhr.oauthAjax({
url: url,
type: method,
accessToken: accessToken,
data: data
})
.fail(function (xhr) {
var respJSON = xhr.responseJSON;
if (respJSON && ! ('errno' in respJSON) && respJSON.code) {
// the basket API returns code instead of errno. Convert.
respJSON.errno = respJSON.code;
}
throw MarketingEmailErrors.normalizeXHRError(xhr);
});
},
fetch: function (accessToken) {
var self = this;
return this._request('get', '/lookup-user', accessToken)
.then(function (response) {
// TODO
// I would prefer to place this into the MarketingEmailPrefs model
// but doing so required passing around the preferencesUrl to lots of
// irrelevant classes.
if (response.token) {
response.preferencesUrl = self._preferencesUrl + response.token;
}
return response;
});
},
optIn: function (accessToken, newsletterId) {
return this._request('post', '/subscribe', accessToken, {
newsletters: newsletterId
});
},
optOut: function (accessToken, newsletterId) {
return this._request('post', '/unsubscribe', accessToken, {
newsletters: newsletterId
});
}
};
return MarketingEmailClient;
});