@sdflc/backend-helpers 1.0.142 → 1.0.144
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/build/BaseGateway.d.ts +7 -0
- package/build/BaseGateway.js +52 -1
- package/build/esm/BaseGateway.d.ts +7 -0
- package/build/esm/BaseGateway.js +52 -1
- package/build/esm/gateways/HubSpotGw.d.ts +46 -0
- package/build/esm/gateways/HubSpotGw.js +181 -0
- package/build/esm/gateways/MailchimpGw.d.ts +57 -0
- package/build/esm/gateways/MailchimpGw.js +187 -0
- package/build/esm/gateways/index.d.ts +2 -0
- package/build/esm/gateways/index.js +2 -0
- package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +11 -0
- package/build/gateways/HubSpotGw.d.ts +46 -0
- package/build/gateways/HubSpotGw.js +184 -0
- package/build/gateways/MailchimpGw.d.ts +57 -0
- package/build/gateways/MailchimpGw.js +192 -0
- package/build/gateways/index.d.ts +2 -0
- package/build/gateways/index.js +2 -0
- package/build/interfaces/BaseGatewayPropsInterface.d.ts +11 -0
- package/package.json +2 -2
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MailchimpGw = exports.mailchimpSubscriberHash = exports.mailchimpDataCenterOf = exports.MAILCHIMP_TAG_MAX = exports.MAILCHIMP_NOTE_MAX = exports.MAILCHIMP_STATUSES_IF_NEW = void 0;
|
|
4
|
+
// ./src/gateways/MailchimpGw.ts
|
|
5
|
+
//
|
|
6
|
+
// Mailchimp's Marketing API (https://mailchimp.com/developer/marketing/api/) — the calls that put a person into a host's
|
|
7
|
+
// audience: a member added or updated by email, tags on it, a note on it, and the audiences to choose from.
|
|
8
|
+
//
|
|
9
|
+
// const mailchimp = new MailchimpGw().configure({ apiKey });
|
|
10
|
+
// await mailchimp.upsertMember(audienceId, { email, mergeFields: { FNAME: 'Ann' }, statusIfNew: 'transactional' });
|
|
11
|
+
// await mailchimp.addTags(audienceId, email, ['Volunteers']);
|
|
12
|
+
// await mailchimp.addNote(audienceId, email, 'Signed up to volunteer at …');
|
|
13
|
+
//
|
|
14
|
+
// The API key ends with its data centre (`…-us21`), which names the server: https://us21.api.mailchimp.com/3.0.
|
|
15
|
+
//
|
|
16
|
+
// ⚠ The key IS the credential — it (and the Basic header made of it) is scrubbed out of every error.
|
|
17
|
+
// ⚠ An existing member's subscription is never changed: only `status_if_new` is sent, which Mailchimp applies to a NEW
|
|
18
|
+
// member. Someone who unsubscribed stays unsubscribed.
|
|
19
|
+
// ⚠ At most 10 connections at once per Mailchimp user — callers send one member at a time.
|
|
20
|
+
const crypto_1 = require("crypto");
|
|
21
|
+
const buffer_1 = require("buffer");
|
|
22
|
+
const api_helpers_1 = require("@sdflc/api-helpers");
|
|
23
|
+
const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
|
|
24
|
+
exports.MAILCHIMP_STATUSES_IF_NEW = ['transactional', 'pending', 'subscribed'];
|
|
25
|
+
/** Mailchimp's own limit on a note. */
|
|
26
|
+
exports.MAILCHIMP_NOTE_MAX = 1000;
|
|
27
|
+
/** A tag's name, at most (Mailchimp's limit). */
|
|
28
|
+
exports.MAILCHIMP_TAG_MAX = 100;
|
|
29
|
+
const text = (value) => String(value ?? '').trim();
|
|
30
|
+
/** The data centre at the end of an API key (`us21`), or null. Pure. */
|
|
31
|
+
const mailchimpDataCenterOf = (apiKey) => {
|
|
32
|
+
const match = /^[0-9a-f]{32}-([a-z]{2,4}\d{1,3})$/i.exec(text(apiKey));
|
|
33
|
+
return match ? match[1].toLowerCase() : null;
|
|
34
|
+
};
|
|
35
|
+
exports.mailchimpDataCenterOf = mailchimpDataCenterOf;
|
|
36
|
+
/** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
|
|
37
|
+
const mailchimpSubscriberHash = (email) => (0, crypto_1.createHash)('md5').update(text(email).toLowerCase()).digest('hex');
|
|
38
|
+
exports.mailchimpSubscriberHash = mailchimpSubscriberHash;
|
|
39
|
+
class MailchimpGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
|
|
40
|
+
constructor(props) {
|
|
41
|
+
super(props);
|
|
42
|
+
}
|
|
43
|
+
validateSettings(settings) {
|
|
44
|
+
return (0, exports.mailchimpDataCenterOf)(settings.apiKey) ? [] : ['the API key is missing or not a Mailchimp one (…-us21)'];
|
|
45
|
+
}
|
|
46
|
+
secretValues() {
|
|
47
|
+
const key = text(this.settings.apiKey);
|
|
48
|
+
return [key, buffer_1.Buffer.from(`anystring:${key}`).toString('base64')];
|
|
49
|
+
}
|
|
50
|
+
/** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
|
|
51
|
+
errorMessageOf(reply) {
|
|
52
|
+
const body = reply.body;
|
|
53
|
+
if (body && typeof body === 'object') {
|
|
54
|
+
const fields = Array.isArray(body.errors)
|
|
55
|
+
? body.errors.map((e) => [e?.field, e?.message].filter(Boolean).join(' ')).join('; ')
|
|
56
|
+
: '';
|
|
57
|
+
return [body.title, body.detail, fields].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
|
|
58
|
+
}
|
|
59
|
+
return super.errorMessageOf(reply);
|
|
60
|
+
}
|
|
61
|
+
call(method, path, json) {
|
|
62
|
+
const key = text(this.settings.apiKey);
|
|
63
|
+
return this.requestWithRetries({
|
|
64
|
+
url: `https://${(0, exports.mailchimpDataCenterOf)(key)}.api.mailchimp.com/3.0${path}`,
|
|
65
|
+
method,
|
|
66
|
+
headers: {
|
|
67
|
+
Authorization: `Basic ${buffer_1.Buffer.from(`anystring:${key}`).toString('base64')}`,
|
|
68
|
+
Accept: 'application/json',
|
|
69
|
+
},
|
|
70
|
+
...(json === undefined ? {} : { json }),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** An audience id may only be letters and digits — it goes into the path. */
|
|
74
|
+
badAudience(audienceId) {
|
|
75
|
+
return /^[A-Za-z0-9]{1,32}$/.test(text(audienceId))
|
|
76
|
+
? null
|
|
77
|
+
: api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The audience id is not one');
|
|
78
|
+
}
|
|
79
|
+
memberPath(audienceId, email) {
|
|
80
|
+
return `/lists/${text(audienceId)}/members/${(0, exports.mailchimpSubscriberHash)(email)}`;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
|
|
84
|
+
* subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
|
|
85
|
+
* `{ memberId, status }`. Never throws.
|
|
86
|
+
*/
|
|
87
|
+
async upsertMember(audienceId, member) {
|
|
88
|
+
if (!this.isConfigured()) {
|
|
89
|
+
return this.notConfigured();
|
|
90
|
+
}
|
|
91
|
+
const email = text(member?.email).toLowerCase();
|
|
92
|
+
const bad = this.badAudience(audienceId);
|
|
93
|
+
if (bad) {
|
|
94
|
+
return bad;
|
|
95
|
+
}
|
|
96
|
+
if (!email.includes('@')) {
|
|
97
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The member has no email');
|
|
98
|
+
}
|
|
99
|
+
const statusIfNew = exports.MAILCHIMP_STATUSES_IF_NEW.includes(member.statusIfNew)
|
|
100
|
+
? member.statusIfNew
|
|
101
|
+
: 'transactional';
|
|
102
|
+
const mergeFields = {};
|
|
103
|
+
for (const [tag, value] of Object.entries(member.mergeFields ?? {})) {
|
|
104
|
+
if (/^[A-Z0-9_]{1,10}$/.test(tag) && text(value)) {
|
|
105
|
+
mergeFields[tag] = text(value);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const result = await this.call('PUT', `${this.memberPath(audienceId, email)}?skip_merge_validation=true`, {
|
|
109
|
+
email_address: email,
|
|
110
|
+
status_if_new: statusIfNew,
|
|
111
|
+
...(Object.keys(mergeFields).length ? { merge_fields: mergeFields } : {}),
|
|
112
|
+
});
|
|
113
|
+
if (result.didFail()) {
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
const body = result.getDataFirst()?.body ?? {};
|
|
117
|
+
return api_helpers_1.OpResult.ok([
|
|
118
|
+
{ memberId: body.id ? String(body.id) : (0, exports.mailchimpSubscriberHash)(email), status: body.status ?? null },
|
|
119
|
+
]);
|
|
120
|
+
}
|
|
121
|
+
/** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
|
|
122
|
+
async addTags(audienceId, email, tags) {
|
|
123
|
+
if (!this.isConfigured()) {
|
|
124
|
+
return this.notConfigured();
|
|
125
|
+
}
|
|
126
|
+
const bad = this.badAudience(audienceId);
|
|
127
|
+
const names = Array.from(new Set((tags ?? []).map((t) => text(t).slice(0, exports.MAILCHIMP_TAG_MAX)).filter(Boolean)));
|
|
128
|
+
if (bad) {
|
|
129
|
+
return bad;
|
|
130
|
+
}
|
|
131
|
+
if (!text(email).includes('@') || names.length === 0) {
|
|
132
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and at least one tag are needed');
|
|
133
|
+
}
|
|
134
|
+
const result = await this.call('POST', `${this.memberPath(audienceId, email)}/tags`, {
|
|
135
|
+
tags: names.map((name) => ({ name, status: 'active' })),
|
|
136
|
+
});
|
|
137
|
+
return result.didFail() ? result : api_helpers_1.OpResult.ok([{ tags: names }]);
|
|
138
|
+
}
|
|
139
|
+
/** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
|
|
140
|
+
async addNote(audienceId, email, note) {
|
|
141
|
+
if (!this.isConfigured()) {
|
|
142
|
+
return this.notConfigured();
|
|
143
|
+
}
|
|
144
|
+
const bad = this.badAudience(audienceId);
|
|
145
|
+
if (bad) {
|
|
146
|
+
return bad;
|
|
147
|
+
}
|
|
148
|
+
if (!text(email).includes('@') || !text(note)) {
|
|
149
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and the note are needed');
|
|
150
|
+
}
|
|
151
|
+
const result = await this.call('POST', `${this.memberPath(audienceId, email)}/notes`, {
|
|
152
|
+
note: String(note).slice(0, exports.MAILCHIMP_NOTE_MAX),
|
|
153
|
+
});
|
|
154
|
+
return result.didFail() ? result : api_helpers_1.OpResult.ok([{ noteId: result.getDataFirst()?.body?.id ?? null }]);
|
|
155
|
+
}
|
|
156
|
+
/** The account's audiences (at most 1,000), by name. Never throws. */
|
|
157
|
+
async listAudiences() {
|
|
158
|
+
if (!this.isConfigured()) {
|
|
159
|
+
return this.notConfigured();
|
|
160
|
+
}
|
|
161
|
+
const result = await this.call('GET', '/lists?count=1000&fields=lists.id,lists.name,lists.stats.member_count');
|
|
162
|
+
if (result.didFail()) {
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
const audiences = (result.getDataFirst()?.body?.lists ?? [])
|
|
166
|
+
.map((l) => ({
|
|
167
|
+
id: String(l?.id ?? ''),
|
|
168
|
+
name: text(l?.name) || String(l?.id ?? ''),
|
|
169
|
+
memberCount: l?.stats?.member_count ?? null,
|
|
170
|
+
}))
|
|
171
|
+
.filter((l) => !!l.id)
|
|
172
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
173
|
+
return api_helpers_1.OpResult.ok(audiences);
|
|
174
|
+
}
|
|
175
|
+
/** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
|
|
176
|
+
async getAudience(audienceId) {
|
|
177
|
+
if (!this.isConfigured()) {
|
|
178
|
+
return this.notConfigured();
|
|
179
|
+
}
|
|
180
|
+
const bad = this.badAudience(audienceId);
|
|
181
|
+
if (bad) {
|
|
182
|
+
return bad;
|
|
183
|
+
}
|
|
184
|
+
const result = await this.call('GET', `/lists/${text(audienceId)}?fields=id,name`);
|
|
185
|
+
if (result.didFail()) {
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
188
|
+
const body = result.getDataFirst()?.body ?? {};
|
|
189
|
+
return api_helpers_1.OpResult.ok([{ id: String(body.id ?? audienceId), name: text(body.name) || String(audienceId) }]);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
exports.MailchimpGw = MailchimpGw;
|
package/build/gateways/index.js
CHANGED
|
@@ -21,5 +21,7 @@ __exportStar(require("./TelegramGw"), exports);
|
|
|
21
21
|
__exportStar(require("./TwilioGw"), exports);
|
|
22
22
|
__exportStar(require("./SlackWebhookGw"), exports);
|
|
23
23
|
__exportStar(require("./DiscordWebhookGw"), exports);
|
|
24
|
+
__exportStar(require("./HubSpotGw"), exports);
|
|
25
|
+
__exportStar(require("./MailchimpGw"), exports);
|
|
24
26
|
__exportStar(require("./HttpWebhookGw"), exports);
|
|
25
27
|
__exportStar(require("./guardedFetch"), exports);
|
|
@@ -74,6 +74,17 @@ export interface BaseGatewayPropsInterface extends CacheInterface {
|
|
|
74
74
|
*/
|
|
75
75
|
localizationForField?: string;
|
|
76
76
|
defaultSorting?: SortItemInterface[];
|
|
77
|
+
/**
|
|
78
|
+
* The column `list()` adds as the LAST sort term whenever it applies a limit, so rows that tie on the caller's sort
|
|
79
|
+
* come back in the same order on every page. Defaults to the id field, qualified with the table's own name
|
|
80
|
+
* (`getListTieBreaker()`). `false` turns it off — for a list query it would break (one that groups, selects
|
|
81
|
+
* DISTINCT, or reads the table under an alias). A string names a different unique column.
|
|
82
|
+
*
|
|
83
|
+
* ⚠ Without it, Postgres does not promise the same order of tied rows from one LIMIT/OFFSET to the next: page 2 can
|
|
84
|
+
* repeat a row from page 1 and skip another for good — rows created together (one bulk insert = one created_at) or a
|
|
85
|
+
* shared `order_no` / name tie all the time. (SQL Server also refuses OFFSET/FETCH — page 2 — with no ORDER BY.)
|
|
86
|
+
*/
|
|
87
|
+
listTieBreaker?: string | false;
|
|
77
88
|
/**
|
|
78
89
|
* Field to apply keyword (ILIKE) search against when filterParams.keyword is set.
|
|
79
90
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdflc/backend-helpers",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.144",
|
|
4
4
|
"description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"exports": {
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"lint": "ESLINT_USE_FLAT_CONFIG=true eslint .",
|
|
21
21
|
"test": "echo No Tests Available Yet",
|
|
22
22
|
"testToDo": "jest --config jest.config.ts",
|
|
23
|
-
"prove": "node scripts/proveCreateId.cjs && node scripts/proveGateways.cjs && node scripts/proveEmergencyAlerter.cjs",
|
|
23
|
+
"prove": "node scripts/proveCreateId.cjs && node scripts/proveGateways.cjs && node scripts/proveEmergencyAlerter.cjs && node scripts/proveListOrder.cjs",
|
|
24
24
|
"format": "prettier --write \"src/**/*.ts\"",
|
|
25
25
|
"prepare": "husky",
|
|
26
26
|
"prepare1": "husky install",
|