This repository was archived by the owner on May 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMapcreator.js
More file actions
653 lines (576 loc) · 15.8 KB
/
Copy pathMapcreator.js
File metadata and controls
653 lines (576 loc) · 15.8 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
/*
* BSD 3-Clause License
*
* Copyright (c) 2020, Mapcreator
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import ky from 'ky-universal';
import { Enum } from './enums';
import DummyFlow from './oauth/DummyFlow';
import OAuth from './oauth/OAuth';
import OAuthToken from './oauth/OAuthToken';
import GeoResourceProxy from './proxy/GeoResourceProxy';
import ResourceProxy from './proxy/ResourceProxy';
import SimpleResourceProxy from './proxy/SimpleResourceProxy';
import {
Choropleth,
Color,
Contract,
Dimension,
DimensionSet,
Faq,
Feature,
Font,
FontFamily,
Highlight,
InsetMap,
Job,
JobShare,
JobType,
Language,
Layer,
Mapstyle,
MapstyleSet,
Notification,
Organisation,
Permission,
Role,
Svg,
SvgSet,
Tag,
TagType,
User,
VectorHighlight,
VectorChoropleth,
} from './resources';
import ResourceBase from './resources/base/ResourceBase';
import Injectable from './traits/Injectable';
import { fnv32b } from './utils/hash';
import Logger from './utils/Logger';
import { isParentOf, mix } from './utils/reflection';
import { delay, makeCancelable, wrapKyCancelable } from './utils/helpers';
import ValidationError from './errors/ValidationError';
import ApiError from './errors/ApiError';
import { wrapKyPrefixUrl } from './utils/requests';
import EventEmitter from 'events';
/**
* Base API class
*
* @mixes Injectable
* @extends EventEmitter
* @fires Mapcreator#error
*/
export default class Mapcreator extends mix(EventEmitter, Injectable) {
/**
* @param {OAuth|string} auth - Authentication flow
* @param {string} host - Remote API host
*/
constructor (auth = new DummyFlow(), host = process.env.HOST) {
super();
if (typeof auth === 'string') {
const token = auth;
auth = new DummyFlow();
auth.token = new OAuthToken(token, 'Bearer', new Date('2100-01-01T01:00:00'), ['*']);
}
this.auth = auth;
this.host = host;
this._logger = new Logger(process.env.LOG_LEVEL);
this.wrapKy(wrapKyCancelable);
this.wrapKy(wrapKyPrefixUrl, `${this.host}/${this.version}`);
}
/**
* Get api version
* @returns {string} - Api version
* @constant
*/
get version () {
return 'v1';
}
/**
* Get authentication provider instance
* @returns {OAuth} - OAuth instance
*/
get auth () {
return this._auth;
}
/**
* Get logger instance
* @returns {Logger} - Logger instance
*/
get logger () {
return this._logger;
}
/**
* Set authentication provider instance
* @param {OAuth} value -- OAuth instance
*/
set auth (value) {
if (!isParentOf(OAuth, value)) {
throw new TypeError('auth must be an instance of OAuth');
}
this._auth = value;
}
/**
* Test if the client is authenticated with the api and has a valid token
* @returns {boolean} - If the client is authenticated with the api
*/
get authenticated () {
return this.auth.authenticated;
}
/**
* The current host
* @returns {string} - The current host
*/
get host () {
return this._host;
}
/**
* The remote host
* @param {string} value - A valid url
*/
set host (value) {
value = value.replace(/\/+$/, '');
this._host = value;
this.auth.host = value;
}
get url () {
return `${this.host}/${this.version}`;
}
/**
* Saves the session token so that it can be recovered at a later time. The wrapper can
* find the token most of the time if the name parameter is left blank.
* @param {string?} name - name of the token
*/
saveToken (name) {
this.auth.token.save(name);
}
/**
* Authenticate with the api using the authentication method provided.
* @returns {Promise<Mapcreator>} - Current instance
* @throws {OAuthError}
* @throws {ApiError} - If the api returns errors
*/
async authenticate () {
await this.auth.authenticate();
return this;
}
/**
* Mapcreator ky instance
* This ky instance takes care of the API communication. It has the following responsibilities:
* - Send authenticated requests to the API
* - Transform errors returned from the API into ApiError and ValidationError if possible
* - Wait when the rate limiter responds with a 429 and retry later
* - Prefix urls with the api domain if needed
* @returns {function}
* @see {@link https://github.com/sindresorhus/ky}
*/
get ky () {
if (this._ky) {
return this._ky;
}
const hooks = {
beforeRequest: [
request => {
if (this.authenticated) {
request.headers.set('Authorization', this.auth.token.toString());
}
},
],
afterResponse: [
// 429 response
async (request, _options, response) => {
if (response.status !== 429) {
return response;
}
const resetDelay = (response.headers.get('x-ratelimit-reset') * 1000) || 500;
await delay(resetDelay);
return this._ky(request);
},
// transform errors
async (request, options, response) => {
if (response.status < 400 || response.status >= 600) {
return response;
}
const data = await response.json();
const params = { data, request, options, response };
if (data.error['validation_errors']) {
throw new ValidationError(params);
}
const error = new ApiError(params);
if (error.type === 'AuthenticationException') {
/**
* Critical api errors (AuthenticationException)
*
* @event Mapcreator#error
* @type {ApiError}
*/
this.emit('error', error);
}
throw error;
},
],
};
this._ky = ky.create({
timeout: 30000, // 30 seconds
// throwHttpErrors: false, // This is done through a custom hook
// redirect: 'error',
retry: 0,
headers: {
'Accept': 'application/json',
'X-No-CDN-Redirect': 'true',
},
hooks,
});
return this._ky;
}
wrapKy (wrapper, ...args) {
this._ky = wrapper(this.ky, ...args);
const requestMethods = [
'get', 'post', 'put',
'patch', 'head', 'delete',
];
for (const method of requestMethods) {
this._ky[method] = (input, options) => this._ky(input, { ...options, method });
}
}
/**
* Static proxy generation
* @param {string|Class} Target - Constructor or url
* @param {Class?} Constructor - Constructor for a resource that the results should be cast to
* @returns {ResourceProxy} - A proxy for accessing the resource
* @example
* api.static('/custom/resource/path/{id}/').get(123);
*
* @example
* class FooBar extends ResourceBase {
* static get resourceName() {
* return 'custom';
* }
* }
*
* api.static(FooBar)
* .get(1)
* .then(console.log);
*
* api.static('/foo-bar-custom', FooBar).lister();
*/
static (Target, Constructor = ResourceBase) {
if (typeof Target === 'string') {
const path = Target;
const name = Constructor.name || 'AnonymousResource';
Target = class AnonymousResource extends Constructor {
static get resourceName () {
return Object.getPrototypeOf(this).resourceName || 'anonymous';
}
static get resourcePath () {
return path;
}
};
Object.defineProperty(Target, 'name', {
value: `${name}_${fnv32b(path)}`,
});
}
if (isParentOf(ResourceBase, Target)) {
return new ResourceProxy(this, Target);
}
throw new TypeError('Expected Target to be of type string and Constructor to be a ResourceBase constructor');
}
/**
* Choropleth accessor
* @see {@link Choropleth}
* @returns {GeoResourceProxy} - A proxy for accessing the resource
*/
get choropleths () {
return new GeoResourceProxy(this, Choropleth);
}
/**
* VectorChoropleth accessor
* @see {@link VectorChoropleth}
* @returns {GeoResourceProxy} - A proxy for accessing the resource
*/
get vectorChoropleths () {
return new GeoResourceProxy(this, VectorChoropleth);
}
/**
* Color accessor
* @see {@link Color}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get colors () {
return this.static(Color);
}
/**
* Tag accessor
* @see {@link Tag}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get tags () {
return this.static(Tag);
}
/**
* Tag accessor
* @see {@link Tag}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get tagTypes () {
return this.static(TagType);
}
/**
* Contract accessor
* @see {@link Contract}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get contracts () {
return this.static(Contract);
}
/**
* Dimension accessor
* @see {@link Dimension}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get dimensions () {
return this.static(Dimension);
}
/**
* Dimension set accessor
* @see {@link DimensionSet}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get dimensionSets () {
return this.static(DimensionSet);
}
/**
* Faq accessor
* @see {@link Faq}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get faqs () {
return this.static(Faq);
}
/**
* Feature accessor
* @see {@link Feature}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get features () {
return this.static(Feature);
}
/**
* Featured jobs accessor
* @see {@link Job}
* @returns {SimpleResourceProxy} - A proxy for accessing the resource
*/
get featuredMaps () {
return new SimpleResourceProxy(this, Job, '/jobs/featured');
}
/**
* Font accessor
* @see {@link Font}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get fonts () {
return this.static(Font);
}
/**
* FontFamily accessor
* @see {@link FontFamily}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get fontFamilies () {
return this.static(FontFamily);
}
/**
* Highlight accessor
* @see {@link Highlight}
* @returns {GeoResourceProxy} - A proxy for accessing the resource
*/
get highlights () {
return new GeoResourceProxy(this, Highlight);
}
/**
* VectorHighlight accessor
* @see {@link VectorHighlight}
* @returns {GeoResourceProxy} - A proxy for accessing the resource
*/
get vectorHighlights () {
return new GeoResourceProxy(this, VectorHighlight);
}
/**
* InsetMap accessor
* @see {@link InsetMap}
* @returns {GeoResourceProxy} - A proxy for accessing the resource
*/
get insetMaps () {
return new GeoResourceProxy(this, InsetMap);
}
/**
* Job accessor
* @see {@link Job}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get jobs () {
return this.static(Job);
}
/**
* JobShare accessor
* @see {@link JobShare}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get jobShares () {
return this.static(JobShare);
}
/**
* JobType accessor
* @see {@link JobType}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get jobTypes () {
return this.static(JobType);
}
/**
* Language accessor
* @see {@link Language}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get languages () {
return this.static(Language);
}
/**
* Layer accessor
* @see {@link Layer}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get layers () {
return this.static(Layer);
}
/**
* Mapstyle accessor
* @see {@link Mapstyle}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get mapstyles () {
return this.static(Mapstyle);
}
/**
* MapstyleSet accessor
* @see {@link MapstyleSet}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get mapstyleSets () {
return this.static(MapstyleSet);
}
/**
* Notification accessor
* @see {@link Notification}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get notifications () {
return this.static(Notification);
}
/**
* Organisation accessor
* @see {@link Organisation}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get organisations () {
return this.static(Organisation);
}
/**
* Permission accessor
* @see {@link Permission}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get permissions () {
return this.static(Permission);
}
/**
* Role accessor
* @see {@link Role}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get roles () {
return this.static(Role);
}
/**
* Svg accessor
* @see {@link Svg}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get svgs () {
return this.static(Svg);
}
/**
* SvgSet accessor
* @see {@link SvgSet}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get svgSets () {
return this.static(SvgSet);
}
/**
* User accessor
* @see {@link User}
* @returns {ResourceProxy} - A proxy for accessing the resource
*/
get users () {
return this.static(User);
}
/**
* Get SVG set types
* @see {@link SvgSet}
* @returns {CancelablePromise<Enum>} - Contains all the possible SVG set types
* @throws {ApiError} - If the api returns errors
*/
getSvgSetTypes () {
return makeCancelable(async signal => {
const { data } = await this.ky.get('svgs/sets/types', { signal }).json();
return new Enum(data, true);
});
}
/**
* Get font styles
* @see {@link Font}
* @returns {CancelablePromise<Enum>} - Contains all the possible font styles
* @throws {ApiError} - If the api returns errors
*/
getFontStyles () {
return makeCancelable(async signal => {
const { data } = await this.ky.get('fonts/styles', { signal }).json();
return new Enum(data, true);
});
}
/**
* Forget the current session
* This will clean up any stored OAuth states stored using {@link StateContainer} and any OAuth tokens stored
* @returns {CancelablePromise}
* @throws {ApiError} - If the api returns errors
*/
logout () {
return this.auth.logout();
}
}