-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathipdata.test.ts
More file actions
405 lines (357 loc) · 14.1 KB
/
ipdata.test.ts
File metadata and controls
405 lines (357 loc) · 14.1 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import IPData, { EU_BASE_URL, LookupResponse } from './ipdata';
const TEST_API_KEY = 'test-api-key';
const TEST_IP = '1.1.1.1';
const DEFAULT_IP_KEY = 'DEFAULT_IP';
const MOCK_IP1_DATA = {
ip: '1.1.1.1',
is_eu: false,
city: 'Los Angeles',
region: 'California',
region_code: 'CA',
country_name: 'United States',
country_code: 'US',
continent_name: 'North America',
continent_code: 'NA',
latitude: 34.0522,
longitude: -118.2437,
postal: '90001',
calling_code: '1',
flag: 'https://ipdata.co/flags/us.png',
emoji_flag: '\u{1F1FA}\u{1F1F8}',
emoji_unicode: 'U+1F1FA U+1F1F8',
carrier: { name: 'Cloudflare', mcc: '', mnc: '' },
asn: { asn: 'AS13335', name: 'Cloudflare, Inc.', domain: 'cloudflare.com', route: '1.1.1.0/24', type: 'hosting' },
company: { name: 'Cloudflare, Inc.', domain: 'cloudflare.com', network: '1.1.1.0/24', type: 'hosting' },
languages: [{ name: 'English', native: 'English', code: 'en' }],
currency: { name: 'US Dollar', code: 'USD', symbol: '$', native: '$', plural: 'US dollars' },
time_zone: {
name: 'America/Los_Angeles',
abbr: 'PST',
offset: '-0800',
is_dst: false,
current_time: '2024-01-01T00:00:00-08:00',
},
threat: {
is_tor: false,
is_proxy: false,
is_anonymous: false,
is_known_attacker: false,
is_known_abuser: false,
is_threat: false,
is_bogon: false,
is_icloud_relay: false,
is_datacenter: true,
blocklists: [],
},
count: 0,
};
const MOCK_IP2_DATA = {
...MOCK_IP1_DATA,
ip: '8.8.8.8',
is_eu: true,
city: 'Mountain View',
};
const MOCK_IP3_DATA = {
...MOCK_IP1_DATA,
ip: '1.0.0.1',
city: 'South Brisbane',
};
const MOCK_DEFAULT_IP_DATA = {
...MOCK_IP1_DATA,
ip: '203.0.113.1',
};
function mockFetchResponse(data: unknown, status = 200) {
return Promise.resolve({
ok: status >= 200 && status < 300,
status,
json: () => Promise.resolve(data),
});
}
const mockFetch = jest.fn() as jest.Mock;
global.fetch = mockFetch;
function keyBy(items: LookupResponse[]): Record<string, LookupResponse> {
return items.reduce<Record<string, LookupResponse>>((acc, item) => {
acc[item.ip] = item;
return acc;
}, {});
}
describe('constructor()', () => {
it('should throw an error if an apiKey is not provided', () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
expect(() => new IPData()).toThrow('An API key is required.');
});
it('should set the apiKey', () => {
const ipdata = new IPData(TEST_API_KEY);
expect(ipdata.apiKey).toEqual(TEST_API_KEY);
});
it('should configure the cache by default', () => {
const ipdata = new IPData(TEST_API_KEY);
expect(ipdata.cache.max).toBe(4096);
expect(ipdata.cache.ttl).toEqual(1000 * 60 * 60 * 24);
});
it('should configure the cache', () => {
const max = 1;
const ttl = 1000;
const ipdata = new IPData(TEST_API_KEY, { max, ttl });
expect(ipdata.cache.max).toEqual(max);
expect(ipdata.cache.ttl).toEqual(ttl);
});
it('should use the default base URL', () => {
const ipdata = new IPData(TEST_API_KEY);
expect(ipdata.baseUrl).toBe('https://api.ipdata.co/');
});
it('should accept a custom base URL', () => {
const ipdata = new IPData(TEST_API_KEY, undefined, EU_BASE_URL);
expect(ipdata.baseUrl).toBe('https://eu-api.ipdata.co/');
});
});
describe('lookup()', () => {
const ipdata = new IPData(TEST_API_KEY);
afterEach(() => {
ipdata.cache.clear();
mockFetch.mockReset();
});
describe('default IP address', () => {
it('should return information', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_DEFAULT_IP_DATA));
const info = await ipdata.lookup();
expect(info).toHaveProperty('ip');
expect(info).toHaveProperty('status');
});
it('should return information when null is provided', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_DEFAULT_IP_DATA));
const info = await ipdata.lookup(undefined);
expect(info).toHaveProperty('ip');
expect(info).toHaveProperty('status');
});
it('should return information when undefined is provided', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_DEFAULT_IP_DATA));
const info = await ipdata.lookup(undefined);
expect(info).toHaveProperty('ip');
expect(info).toHaveProperty('status');
});
it('should cache the information', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_DEFAULT_IP_DATA));
await ipdata.lookup();
const info = ipdata.cache.get(DEFAULT_IP_KEY);
expect(info).toHaveProperty('ip');
expect(info).toHaveProperty('status');
});
it('should not cache the information', async () => {
const customIPData = new IPData(TEST_API_KEY, { ttl: 1 });
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_DEFAULT_IP_DATA));
await customIPData.lookup();
const info = ipdata.cache.get(DEFAULT_IP_KEY);
expect(info).toBeUndefined();
});
});
describe('custom IP address', () => {
it('should throw an error if the ip address is invalid', async () => {
const badIP = '1.1.11';
await expect(ipdata.lookup(badIP)).rejects.toThrow(`${badIP} is an invalid IP address.`);
});
it('should return information', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_IP1_DATA));
const info = await ipdata.lookup(TEST_IP);
expect(info).toHaveProperty('ip', TEST_IP);
expect(info).toHaveProperty('status');
});
it('should cache the information', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_IP1_DATA));
await ipdata.lookup(TEST_IP);
const info = ipdata.cache.get(TEST_IP);
expect(info).toHaveProperty('ip', TEST_IP);
expect(info).toHaveProperty('status');
});
it('should not cache the information', async () => {
const customIPData = new IPData(TEST_API_KEY, { ttl: 1 });
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_IP1_DATA));
await customIPData.lookup(TEST_IP);
const info = ipdata.cache.get(TEST_IP);
expect(info).toBeUndefined();
});
});
it('should throw an error if a selectField and fields is provided', async () => {
await expect(ipdata.lookup(undefined, 'field', ['field'])).rejects.toThrow(
'The selectField and fields parameters cannot be used at the same time.',
);
});
describe('selectField', () => {
it('should throw an error for an invlaid field', async () => {
const field = 'field';
await expect(ipdata.lookup(undefined, field)).rejects.toThrow(`${field} is not a valid field.`);
});
it('should return a response with only the field', async () => {
const field = 'is_eu';
mockFetch.mockReturnValueOnce(mockFetchResponse(false));
const info = await ipdata.lookup(undefined, field);
expect(info).toHaveProperty(field, false);
expect(info).toHaveProperty('status');
});
});
describe('fields', () => {
it('should throw an error for an invlaid field', async () => {
const field = 'field';
const fields = [field];
await expect(ipdata.lookup(undefined, undefined, fields)).rejects.toThrow(`${field} is not a valid field.`);
});
it('should return a response with only the field', async () => {
const field1 = 'ip';
const field2 = 'is_eu';
const fields = [field1, field2];
mockFetch.mockReturnValueOnce(mockFetchResponse({ ip: TEST_IP, is_eu: false }));
const info = await ipdata.lookup(TEST_IP, undefined, fields);
expect(info).toHaveProperty(field1, TEST_IP);
expect(info).toHaveProperty(field2, false);
expect(info).toHaveProperty('status');
});
});
describe('company field', () => {
it('should accept company as a valid select field', async () => {
const companyData = {
name: 'Cloudflare, Inc.',
domain: 'cloudflare.com',
network: '1.1.1.0/24',
type: 'hosting',
};
mockFetch.mockReturnValueOnce(mockFetchResponse(companyData));
const info = await ipdata.lookup(TEST_IP, 'company');
expect(info).toHaveProperty('company');
expect(info).toHaveProperty('status');
});
it('should accept company in fields array', async () => {
const fields = ['ip', 'company'];
mockFetch.mockReturnValueOnce(mockFetchResponse({ ip: TEST_IP, company: MOCK_IP1_DATA.company }));
const info = await ipdata.lookup(TEST_IP, undefined, fields);
expect(info).toHaveProperty('ip', TEST_IP);
expect(info).toHaveProperty('status');
});
});
describe('named params', () => {
it('should return information with no params', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_DEFAULT_IP_DATA));
const info = await ipdata.lookup({});
expect(info).toHaveProperty('ip');
expect(info).toHaveProperty('status');
});
it('should return information with ip param', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_IP1_DATA));
const info = await ipdata.lookup({ ip: TEST_IP });
expect(info).toHaveProperty('ip', TEST_IP);
expect(info).toHaveProperty('status');
});
it('should return a selectField response', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(false));
const info = await ipdata.lookup({ selectField: 'is_eu' });
expect(info).toHaveProperty('is_eu', false);
expect(info).toHaveProperty('status');
});
it('should return a fields response', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse({ ip: TEST_IP, is_eu: false }));
const info = await ipdata.lookup({ ip: TEST_IP, fields: ['ip', 'is_eu'] });
expect(info).toHaveProperty('ip', TEST_IP);
expect(info).toHaveProperty('is_eu', false);
expect(info).toHaveProperty('status');
});
it('should throw if selectField and fields are both provided', async () => {
await expect(ipdata.lookup({ selectField: 'ip', fields: ['ip'] })).rejects.toThrow(
'The selectField and fields parameters cannot be used at the same time.',
);
});
});
describe('new API fields', () => {
it('should return threat object with new fields', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_IP1_DATA));
const info = await ipdata.lookup(TEST_IP);
expect(info).toHaveProperty('threat');
expect(info.threat).toHaveProperty('is_icloud_relay');
expect(info.threat).toHaveProperty('is_datacenter');
expect(info.threat).toHaveProperty('blocklists');
});
it('should return languages with code field', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_IP1_DATA));
const info = await ipdata.lookup(TEST_IP);
expect(info.languages.length).toBeGreaterThan(0);
expect(info.languages[0]).toHaveProperty('code');
});
});
});
describe('bulkLookup()', () => {
const ipdata = new IPData(TEST_API_KEY);
const IP1 = TEST_IP;
const IP2 = '8.8.8.8';
afterEach(() => {
ipdata.cache.clear();
mockFetch.mockReset();
});
it('should throw an error if less than 2 ip addresses are provided', async () => {
const ips = [IP1];
await expect(ipdata.bulkLookup(ips)).rejects.toThrow('Bulk Lookup requires more than 1 IP Address in the payload.');
});
it('should throw an error if an ip address is invalid', async () => {
const badIP = '1.1.11';
const ips = [badIP, IP2];
await expect(ipdata.bulkLookup(ips)).rejects.toThrow(`${badIP} is an invalid IP address.`);
});
it('should return info for the ip addresses', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse([MOCK_IP1_DATA, MOCK_IP2_DATA]));
const result = await ipdata.bulkLookup([IP1, IP2]);
const info = keyBy(result);
expect(info[IP1]).toHaveProperty('ip', IP1);
expect(info[IP1]).toHaveProperty('status');
expect(info[IP2]).toHaveProperty('ip', IP2);
expect(info[IP2]).toHaveProperty('status');
});
it('should cache the info', async () => {
mockFetch.mockReturnValueOnce(mockFetchResponse([MOCK_IP1_DATA, MOCK_IP2_DATA]));
await ipdata.bulkLookup([IP1, IP2]);
const ip1Info = ipdata.cache.get(IP1);
const ip2Info = ipdata.cache.get(IP2);
expect(ip1Info).toHaveProperty('ip', IP1);
expect(ip1Info).toHaveProperty('status');
expect(ip2Info).toHaveProperty('ip', IP2);
expect(ip2Info).toHaveProperty('status');
});
it('should use existing cached ips and merge ones that do not exist', async () => {
const IP3 = '1.0.0.1';
mockFetch.mockReturnValueOnce(mockFetchResponse(MOCK_IP1_DATA));
await ipdata.lookup(IP1);
expect(ipdata.cache.get(IP1)).toBeDefined();
mockFetch.mockReturnValueOnce(mockFetchResponse([MOCK_IP2_DATA, MOCK_IP3_DATA]));
const result = await ipdata.bulkLookup([IP1, IP2, IP3]);
const info = keyBy(result);
expect(info[IP1]).toHaveProperty('ip', IP1);
expect(info[IP1]).toHaveProperty('status');
expect(info[IP2]).toHaveProperty('ip', IP2);
expect(info[IP2]).toHaveProperty('status');
expect(info[IP3]).toHaveProperty('ip', IP3);
expect(info[IP3]).toHaveProperty('status');
});
describe('fields', () => {
it('should throw an error for an invlaid field', async () => {
const field = 'field';
const fields = [field];
await expect(ipdata.bulkLookup([IP1, IP2], fields)).rejects.toThrow(`${field} is not a valid field.`);
});
it('should return a response with only the field', async () => {
const field1 = 'ip';
const field2 = 'is_eu';
const fields = [field1, field2];
mockFetch.mockReturnValueOnce(
mockFetchResponse([
{ ip: IP1, is_eu: false },
{ ip: IP2, is_eu: true },
]),
);
const result = await ipdata.bulkLookup([IP1, IP2], fields);
const info = keyBy(result);
expect(info[IP1]).toHaveProperty(field1, IP1);
expect(info[IP1]).toHaveProperty(field2, false);
expect(info[IP1]).toHaveProperty('status');
expect(info[IP2]).toHaveProperty(field1, IP2);
expect(info[IP2]).toHaveProperty(field2, true);
expect(info[IP2]).toHaveProperty('status');
});
});
});