Skip to content

Commit 8b2083a

Browse files
niallzatoNiall Brennanalanjcharles
authored
Support Regional endpoints returned via the CDN (#721)
* feat: add support for endpoint returned via the cdn * feat: add support for endpoint returned via the cdn * feat: add support for endpoint returned via the cdn * feat: add support for endpoint returned via the cdn * fix: fix e2e tests, update endpoints in constants * fix: remove console.log from mock server Co-authored-by: Niall Brennan <[email protected]> Co-authored-by: Alan Charles <[email protected]>
1 parent 6a0f9e4 commit 8b2083a

File tree

6 files changed

+54
-39
lines changed

6 files changed

+54
-39
lines changed

packages/core/src/__tests__/api.test.ts

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import {
2-
Config,
32
Context,
43
EventType,
54
SegmentAPIIntegrations,
@@ -8,7 +7,6 @@ import {
87
} from '../types';
98
import { uploadEvents } from '../api';
109
import * as context from '../context';
11-
import { batchApi } from '../constants';
1210

1311
describe('#sendEvents', () => {
1412
beforeEach(() => {
@@ -28,7 +26,7 @@ describe('#sendEvents', () => {
2826
.mockReturnValue('2001-01-01T00:00:00.000Z');
2927
});
3028

31-
async function sendAnEventPer(config: Config, toUrl: string) {
29+
async function sendAnEventPer(writeKey: string, toUrl: RequestInfo) {
3230
const mockResponse = Promise.resolve('MANOS');
3331
// @ts-ignore
3432
global.fetch = jest.fn(() => Promise.resolve(mockResponse));
@@ -59,7 +57,8 @@ describe('#sendEvents', () => {
5957
};
6058

6159
await uploadEvents({
62-
config,
60+
writeKey,
61+
url: toUrl,
6362
events: [event],
6463
});
6564

@@ -78,19 +77,16 @@ describe('#sendEvents', () => {
7877
}
7978

8079
it('sends an event', async () => {
81-
const toSegmentBatchApi = batchApi;
82-
const config = {
83-
writeKey: 'SEGMENT_KEY',
84-
};
85-
await sendAnEventPer(config, toSegmentBatchApi);
80+
const toSegmentBatchApi = 'https://api.segment.io/v1.b';
81+
const writeKey = 'SEGMENT_KEY';
82+
83+
await sendAnEventPer(writeKey, toSegmentBatchApi);
8684
});
8785

8886
it('sends an event to proxy', async () => {
8987
const toProxyUrl = 'https://myprox.io/b';
90-
const config = {
91-
writeKey: 'SEGMENT_KEY',
92-
proxy: toProxyUrl,
93-
};
94-
await sendAnEventPer(config, toProxyUrl);
88+
const writeKey = 'SEGMENT_KEY';
89+
90+
await sendAnEventPer(writeKey, toProxyUrl);
9591
});
9692
});

packages/core/src/api.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
1-
import type { Config, SegmentEvent } from './types';
1+
import type { SegmentEvent } from './types';
22
import { Base64 } from 'js-base64';
3-
import { batchApi } from './constants';
43

54
export const uploadEvents = async ({
6-
config,
5+
writeKey,
6+
url,
77
events,
88
}: {
9-
config: Config;
9+
writeKey: String;
10+
url: RequestInfo;
1011
events: SegmentEvent[];
1112
}) => {
12-
const requestUrl = config.proxy || batchApi;
13-
return await fetch(requestUrl, {
13+
return await fetch(url, {
1414
method: 'POST',
1515
body: JSON.stringify({
1616
batch: events,
1717
sentAt: new Date().toISOString(),
18-
writeKey: config.writeKey,
18+
writeKey: writeKey,
1919
}),
2020
headers: {
21-
'Authorization': `Basic ${Base64.encode(`${config.writeKey}:`)}`,
21+
'Authorization': `Basic ${Base64.encode(`${writeKey}:`)}`,
2222
'Content-Type': 'text/plain',
2323
},
2424
});

packages/core/src/constants.e2e.mock.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,15 @@
11
import { Platform } from 'react-native';
22
import type { Config } from '.';
33

4-
export const batchApi = Platform.select({
5-
ios: 'http://localhost:9091/events',
6-
android: 'http://10.0.2.2:9091/events',
7-
});
8-
94
export const settingsCDN = Platform.select({
105
ios: 'http://localhost:9091/settings',
116
android: 'http://10.0.2.2:9091/settings',
127
});
138

14-
export const defaultApiHost = 'api.segment.io/v1';
9+
export const defaultApiHost = Platform.select({
10+
ios: 'http://localhost:9091/events',
11+
android: 'http://10.0.2.2:9091/events',
12+
});
1513

1614
export const defaultConfig: Config = {
1715
writeKey: '',

packages/core/src/constants.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import type { Config } from './types';
22

3-
export const batchApi = 'https://api.segment.io/v1/b';
4-
export const defaultApiHost = 'api.segment.io/v1';
3+
export const defaultApiHost = 'https://api.segment.io/v1/b';
54

65
export const settingsCDN = 'https://cdn-settings.segment.com/v1/projects';
76

packages/core/src/plugins/SegmentDestination.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { uploadEvents } from '../api';
55
import type { SegmentClient } from '../analytics';
66
import { DestinationMetadataEnrichment } from './DestinationMetadataEnrichment';
77
import { QueueFlushingPlugin } from './QueueFlushingPlugin';
8+
import { defaultApiHost } from '../constants';
89
import { checkResponseForErrors, translateHTTPError } from '../errors';
910

1011
const MAX_EVENTS_PER_BATCH = 100;
@@ -29,12 +30,14 @@ export class SegmentDestination extends DestinationPlugin {
2930

3031
let sentEvents: SegmentEvent[] = [];
3132
let numFailedEvents = 0;
33+
const config = this.analytics?.getConfig();
3234

3335
await Promise.all(
3436
chunkedEvents.map(async (batch: SegmentEvent[]) => {
3537
try {
3638
const res = await uploadEvents({
37-
config: this.analytics?.getConfig()!,
39+
writeKey: config!.writeKey,
40+
url: this.getEndpoint(),
3841
events: batch,
3942
});
4043
checkResponseForErrors(res);
@@ -64,6 +67,29 @@ export class SegmentDestination extends DestinationPlugin {
6467

6568
private readonly queuePlugin = new QueueFlushingPlugin(this.sendEvents);
6669

70+
getEndpoint(): RequestInfo {
71+
const config = this.analytics?.getConfig();
72+
const settings = this.analytics?.settings.get();
73+
let api;
74+
let requestUrl;
75+
76+
if (
77+
settings !== undefined &&
78+
Object.keys(settings).includes(SEGMENT_DESTINATION_KEY)
79+
) {
80+
const segmentInfo = settings[SEGMENT_DESTINATION_KEY] as Record<
81+
string,
82+
any
83+
>;
84+
if (segmentInfo.apiHost !== undefined && segmentInfo.apiHost !== null) {
85+
api = `https://${segmentInfo.apiHost}/b`;
86+
}
87+
}
88+
89+
requestUrl = config?.proxy ?? api ?? defaultApiHost;
90+
return requestUrl;
91+
}
92+
6793
configure(analytics: SegmentClient): void {
6894
super.configure(analytics);
6995

packages/core/src/plugins/__tests__/SegmentDestination.test.ts

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -245,19 +245,15 @@ describe('SegmentDestination', () => {
245245

246246
expect(sendEventsSpy).toHaveBeenCalledTimes(2);
247247
expect(sendEventsSpy).toHaveBeenCalledWith({
248-
config: {
249-
maxBatchSize: 2,
250-
writeKey: '123-456',
251-
},
248+
writeKey: '123-456',
249+
url: 'https://api.segment.io/v1/b',
252250
events: events.slice(0, 2).map((e) => ({
253251
...e,
254252
})),
255253
});
256254
expect(sendEventsSpy).toHaveBeenCalledWith({
257-
config: {
258-
maxBatchSize: 2,
259-
writeKey: '123-456',
260-
},
255+
writeKey: '123-456',
256+
url: 'https://api.segment.io/v1/b',
261257
events: events.slice(2, 4).map((e) => ({
262258
...e,
263259
})),

0 commit comments

Comments
 (0)