forked from pavel-ignatiev/serverless-domain-manager
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.ts
774 lines (683 loc) · 28.8 KB
/
index.ts
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
"use strict";
import chalk from "chalk";
import DomainInfo = require("./DomainInfo");
import { ServerlessInstance, ServerlessOptions } from "./types";
const certStatuses = ["PENDING_VALIDATION", "ISSUED", "INACTIVE"];
class ServerlessCustomDomain {
// AWS SDK resources
public apigateway: any;
public apigatewayv2: any;
public route53: any;
public acm: any;
public acmRegion: string;
public cloudformation: any;
// Serverless specific properties
public serverless: ServerlessInstance;
public options: ServerlessOptions;
public commands: object;
public hooks: object;
// Domain Manager specific properties
public domains: Map<string, any>;
constructor(serverless: ServerlessInstance, options: ServerlessOptions) {
this.serverless = serverless;
this.options = options;
this.commands = {
create_domain: {
lifecycleEvents: [
"create",
"initialize",
],
usage: "Creates a domain using the domain name defined in the serverless file",
},
delete_domain: {
lifecycleEvents: [
"delete",
"initialize",
],
usage: "Deletes a domain using the domain name defined in the serverless file",
},
};
this.hooks = {
"after:deploy:deploy": this.hookWrapper.bind(this, this.propogateMappings),
"after:info:info": this.hookWrapper.bind(this, this.domainSummary),
"before:remove:remove": this.hookWrapper.bind(this, this.removeMappings),
"create_domain:create": this.hookWrapper.bind(this, this.createDomains),
"delete_domain:delete": this.hookWrapper.bind(this, this.deleteDomains),
};
}
/**
* Wrapper for lifecycle function, initializes variables and checks if enabled.
* @param lifecycleFunc lifecycle function that actually does desired action
*/
public async hookWrapper(lifecycleFunc: any) {
this.initializeDomainManager();
if (this.domains.size === 0) {
const msg = "No domains are enabled. To use Domain Manager pass 'enabled: true' in your serverless.yaml";
this.domainManagerLog(msg);
}
return await lifecycleFunc.call(this);
}
/**
* Lifecycle function to create a domain
* Wraps creating a domain and resource record set
*/
public async createDomains(): Promise<void> {
const iterator = this.domains.entries();
const results = new Map();
let domain = iterator.next();
while (!domain.done) {
const domainInfo = domain.value[1];
try {
await this.getAliasInfo(domainInfo);
} catch (err) {
if (err.code === "NotFoundException") {
const msg = `Domain ${domainInfo.domainName} not found. Creating...`;
this.logIfDebug(msg);
}
}
try {
if (!domainInfo.aliasTarget) {
if (!domainInfo.certificateArn) {
await this.getCertArn(domainInfo);
}
await this.createCustomDomain(domainInfo);
await this.changeResourceRecordSet("UPSERT", domainInfo);
const msg = `${domainInfo.domainName} was created. Could take up to 40 minutes to be initialized.`;
results.set(domain.value[0], msg);
domain = iterator.next();
} else {
const msg = `Domain ${domainInfo.domainName} already exists. Skipping...`;
results.set(domain.value[0], msg);
domain = iterator.next();
}
} catch (err) {
if (err.code === "TooManyRequestsException") {
this.logIfDebug("Too many requests. Retrying in 5s.");
await this.sleep(5000);
}
}
}
[...results.values()].forEach((msg) => {
this.domainManagerLog(msg);
});
}
/**
* Lifecycle function to delete a domain
* Wraps deleting a domain and resource record set
*/
public async deleteDomains(): Promise<void> {
const iterator = this.domains.entries();
const results = new Map();
let domain = iterator.next();
while (!domain.done) {
const domainInfo = domain.value[1];
try {
await this.getAliasInfo(domainInfo);
await this.deleteCustomDomain(domainInfo);
await this.changeResourceRecordSet("DELETE", domainInfo);
const msg = `Domain ${domainInfo.domainName} was deleted.`;
results.set(domain.value[0], msg);
domain = iterator.next();
} catch (err) {
switch (err.code) {
case "NotFoundException":
this.domainManagerLog(`Couldn't find ${domainInfo.domainName}. Skipping delete...`);
domain = iterator.next();
break;
case "TooManyRequestsException":
this.logIfDebug("Too many requests. Retrying in 5s.");
await this.sleep(5000);
break;
default:
this.logIfDebug(err);
const msg = `Unable to delete ${domainInfo.domainName}. SLS_DEBUG=* for more info.`;
this.domainManagerLog(msg);
results.set(domain.value[0], err);
domain = iterator.next();
}
}
}
results.forEach((msg) => {
this.domainManagerLog(msg);
});
}
/**
* Lifecycle function to setup API mappings for HTTP and websocket endpoints
*/
// FIXME: edit to handle going from a valued apiMappingKey to an empty key
public async propogateMappings(): Promise<void> {
const iterator = this.domains.entries();
const successful = new Map();
let domain = iterator.next();
while (!domain.done) {
const domainInfo = domain.value[1];
try {
if (domainInfo.enabled) {
const apiId = await this.getApiId(domainInfo);
const mapping = await this.getMapping(apiId, domainInfo);
if (!mapping) {
await this.createApiMapping(apiId, domainInfo);
domain = iterator.next();
this.addOutputs(domainInfo);
successful.set(domainInfo, "successful");
continue;
}
if (mapping.apiMappingKey !== domainInfo.basePath) {
await this.updateApiMapping(mapping.apiMappingId, domainInfo, apiId);
domain = iterator.next();
this.addOutputs(domainInfo);
successful.set(domainInfo, "successful");
continue;
} else {
this.logIfDebug(`Path for ${domainInfo.domainName} is already current. Skipping...`);
domain = iterator.next();
}
}
} catch (err) {
this.logIfDebug(err.message);
domain = iterator.next();
}
}
if (successful.size > 0) {
await this.domainSummary();
}
}
/**
* Lifecycle function to print domain summary
* Wraps printing of all domain manager related info
*/
public async domainSummary(): Promise<void> {
const iterator = this.domains.entries();
const results = new Map();
let domain = iterator.next();
while (!domain.done) {
const domainInfo = domain.value[1];
if (domainInfo.createRoute53Record !== false) {
try {
await this.getAliasInfo(domainInfo);
results.set(domain.value[0], {
aliasHostedZoneId: domainInfo.aliasHostedZoneId,
aliasTarget: domainInfo.aliasTarget,
domainName: domainInfo.domainName,
websocket: domainInfo.websocket,
});
domain = iterator.next();
} catch (err) {
const msg = `Unable to print Serverless Domain Manager Summary for ${domainInfo.domainName}`;
this.domainManagerLog(err);
results.set(domain.value[0], msg);
domain = iterator.next();
}
}
}
const sorted = [...results.values()].sort();
this.printDomainSummary(sorted);
}
/**
* Initializes DomainInfo class with domain specific variables, and
* SDK APIs if and only if there are enabled domains. Otherwise will
* return undefined.
*/
public initializeDomainManager(): void {
if (typeof this.serverless.service.custom === "undefined") {
throw new Error("serverless-domain-manager: Plugin configuration is missing.");
} else if (typeof this.serverless.service.custom.customDomain === "undefined") {
throw new Error("serverless-domain-manager: Plugin configuration is missing.");
}
this.domains = new Map();
this.serverless.service.custom.customDomain
.map((customDomain) => {
const domain = new DomainInfo(customDomain, this.serverless, this.options);
if (!domain.enabled) {
const msg = `Domain generation for ${domain.domainName} has been disabled. Skipping...`;
this.domainManagerLog(msg);
return;
}
this.domains.set(domain.domainName, domain);
});
if (this.domains.size > 0) {
let credentials;
credentials = this.serverless.providers.aws.getCredentials();
this.apigateway = new this.serverless.providers.aws.sdk.APIGateway(credentials);
this.apigatewayv2 = new this.serverless.providers.aws.sdk.ApiGatewayV2(credentials);
this.route53 = new this.serverless.providers.aws.sdk.Route53(credentials);
this.cloudformation = new this.serverless.providers.aws.sdk.CloudFormation(credentials);
this.acm = new this.serverless.providers.aws.sdk.ACM(credentials);
}
}
/**
* Gets Certificate ARN that most closely matches domain name OR given Cert ARN if provided
*/
public async getCertArn(domain: DomainInfo): Promise<string> {
if (domain.certificateArn) {
this.domainManagerLog(`Selected specific certificateArn ${domain.certificateArn}`);
return;
}
let certificateArn; // The arn of the choosen certificate
let certificateName = domain.certificateName; // The certificate name
let certData;
try {
if (domain.isRegional()) {
this.acmRegion = this.serverless.providers.aws.getRegion();
this.acm.config.update({region: this.acmRegion});
certData = await this.acm.listCertificates({ CertificateStatuses: certStatuses }).promise();
} else {
this.acm.config.update({region: "us-east-1"});
certData = await this.acm.listCertificates({ CertificateStatuses: certStatuses }).promise();
}
// The more specific name will be the longest
let nameLength = 0;
const certificates = certData.CertificateSummaryList;
// Checks if a certificate name is given
if (certificateName != null) {
const foundCertificate = certificates
.find((certificate) => (certificate.DomainName === certificateName));
if (foundCertificate != null) {
certificateArn = foundCertificate.CertificateArn;
}
} else {
certificateName = domain.domainName;
certificates.forEach((certificate) => {
let certificateListName = certificate.DomainName;
// Looks for wild card and takes it out when checking
if (certificateListName[0] === "*") {
certificateListName = certificateListName.substr(1);
}
// Looks to see if the name in the list is within the given domain
// Also checks if the name is more specific than previous ones
if (certificateName.includes(certificateListName)
&& certificateListName.length > nameLength) {
nameLength = certificateListName.length;
certificateArn = certificate.CertificateArn;
}
});
}
} catch (err) {
this.logIfDebug(err);
throw Error(`Error: Could not list certificates in Certificate Manager.\n${err}`);
}
if (certificateArn == null) {
throw Error(`Error: Could not find the certificate ${certificateName}.`);
}
domain.certificateArn = certificateArn;
}
/**
* Gets domain info as DomainInfo object if domain exists, otherwise returns false
*/
public async getAliasInfo(domain: DomainInfo) {
try {
const domainInfo = await this.apigatewayv2.getDomainName({ DomainName: domain.domainName }).promise();
domain.SetApiGatewayRespV2(domainInfo);
this.domains.set(domain.domainName, domain);
} catch (err) {
if (err.code === "NotFoundException") {
throw err;
}
throw new Error(`Error: Unable to fetch information about ${domain.domainName}`);
}
}
/**
* Creates Custom Domain Name through API Gateway
* @param certificateArn: Certificate ARN to use for custom domain
*/
public async createCustomDomain(domain: DomainInfo) {
let createdDomain = {};
try {
if (!domain.websocket) {
// Set up parameters
const params = {
certificateArn: domain.certificateArn,
domainName: domain.domainName,
endpointConfiguration: {
types: [domain.endpointType],
},
regionalCertificateArn: domain.certificateArn,
};
if (!domain.isRegional()) {
params.regionalCertificateArn = undefined;
} else {
params.certificateArn = undefined;
}
createdDomain = await this.apigateway.createDomainName(params).promise();
domain.SetApiGatewayRespV1(createdDomain);
this.domains.set(domain.domainName, domain);
} else {
const params = {
DomainName: domain.domainName,
DomainNameConfigurations: [
{
CertificateArn: domain.certificateArn,
EndpointType: domain.endpointType,
},
],
};
createdDomain = await this.apigatewayv2.createDomainName(params).promise();
domain.SetApiGatewayRespV2(createdDomain);
this.domains.set(domain.domainName, domain);
}
} catch (err) {
if (err.code === "TooManyRequestsException") {
throw err;
}
throw new Error(`Error: Failed to create custom domain ${domain.domainName}\n`);
}
}
/**
* Delete Custom Domain Name through API Gateway
*/
public async deleteCustomDomain(domain: DomainInfo): Promise<void> {
const params = {
DomainName: domain.domainName,
};
// Make API call
try {
await this.apigatewayv2.deleteDomainName(params).promise();
} catch (err) {
if (err.code === "TooManyRequestsException") {
throw err;
}
throw new Error(`Error: Failed to delete custom domain ${domain.domainName}\n`);
}
}
/**
* Change A Alias record through Route53 based on given action
* @param action: String descriptor of change to be made. Valid actions are ['UPSERT', 'DELETE']
* @param domain: DomainInfo object containing info about custom domain
*/
public async changeResourceRecordSet(action: string, domain: DomainInfo): Promise<void> {
if (action !== "UPSERT" && action !== "DELETE") {
throw new Error(`Error: Invalid action "${action}" when changing Route53 Record.
Action must be either UPSERT or DELETE.\n`);
}
if (domain.createRoute53Record !== undefined && domain.createRoute53Record === false) {
this.domainManagerLog("Skipping creation of Route53 record.");
return;
}
// Set up parameters
const route53HostedZoneId = await this.getRoute53HostedZoneId(domain);
const Changes = ["A", "AAAA"].map((Type) => ({
Action: action,
ResourceRecordSet: {
AliasTarget: {
DNSName: domain.aliasTarget,
EvaluateTargetHealth: false,
HostedZoneId: domain.aliasHostedZoneId,
},
Name: domain.domainName,
Type,
},
}));
const params = {
ChangeBatch: {
Changes,
Comment: "Record created by serverless-domain-manager",
},
HostedZoneId: route53HostedZoneId,
};
// Make API call
try {
await this.route53.changeResourceRecordSets(params).promise();
} catch (err) {
this.logIfDebug(err);
throw new Error(`Error: Failed to ${action} A Alias for ${domain.domainName}\n`);
}
}
/**
* Gets Route53 HostedZoneId from user or from AWS
*/
public async getRoute53HostedZoneId(domain: DomainInfo): Promise<string> {
if (domain.hostedZoneId) {
this.domainManagerLog(`Selected specific hostedZoneId ${domain.hostedZoneId}`);
return domain.hostedZoneId;
}
const filterZone = domain.hostedZonePrivate !== undefined;
if (filterZone && domain.hostedZonePrivate) {
this.domainManagerLog("Filtering to only private zones.");
} else if (filterZone && !domain.hostedZonePrivate) {
this.domainManagerLog("Filtering to only public zones.");
}
let hostedZoneData;
const givenDomainNameReverse = domain.domainName.split(".").reverse();
try {
hostedZoneData = await this.route53.listHostedZones({}).promise();
const targetHostedZone = hostedZoneData.HostedZones
.filter((hostedZone) => {
let hostedZoneName;
if (hostedZone.Name.endsWith(".")) {
hostedZoneName = hostedZone.Name.slice(0, -1);
} else {
hostedZoneName = hostedZone.Name;
}
if (!filterZone || domain.hostedZonePrivate === hostedZone.Config.PrivateZone) {
const hostedZoneNameReverse = hostedZoneName.split(".").reverse();
if (givenDomainNameReverse.length === 1
|| (givenDomainNameReverse.length >= hostedZoneNameReverse.length)) {
for (let i = 0; i < hostedZoneNameReverse.length; i += 1) {
if (givenDomainNameReverse[i] !== hostedZoneNameReverse[i]) {
return false;
}
}
return true;
}
}
return false;
})
.sort((zone1, zone2) => zone2.Name.length - zone1.Name.length)
.shift();
if (targetHostedZone) {
const hostedZoneId = targetHostedZone.Id;
// Extracts the hostzone Id
const startPos = hostedZoneId.indexOf("e/") + 2;
const endPos = hostedZoneId.length;
return hostedZoneId.substring(startPos, endPos);
}
} catch (err) {
this.logIfDebug(err);
throw new Error(`Error: Unable to list hosted zones in Route53.\n${err}`);
}
throw new Error(`Error: Could not find hosted zone "${domain.domainName}"`);
}
public async getMapping(ApiId: string, domain: DomainInfo): Promise<any> {
const params = {
DomainName: domain.domainName,
};
let mappingInfo;
let apiMappingId;
let apiMappingKey;
try {
mappingInfo = await this.apigatewayv2.getApiMappings(params).promise();
} catch (err) {
this.logIfDebug(err);
if (err.code === "NotFoundException") {
throw err;
}
throw new Error(`Error: Unable to get mappings for ${domain.domainName}`);
}
if (mappingInfo.Items !== undefined && mappingInfo.Items instanceof Array) {
for (const m of mappingInfo.Items) {
if (m.ApiId === ApiId) {
apiMappingId = m.ApiMappingId;
apiMappingKey = m.ApiMappingKey;
break;
}
}
}
return apiMappingId ? {apiMappingId, apiMappingKey} : undefined;
}
/**
* Creates basepath mapping
*/
public async createApiMapping(apiId: string, domain: DomainInfo): Promise<void> {
const params = {
ApiId: apiId,
ApiMappingKey: domain.basePath,
DomainName: domain.domainName,
Stage: domain.stage,
};
try {
await this.apigatewayv2.createApiMapping(params).promise();
this.domainManagerLog(`Created API mapping for ${domain.domainName}.`);
} catch (err) {
throw new Error(`${err}`);
}
}
/**
* Updates basepath mapping
*/
public async updateApiMapping(oldMappingId: string, domain: DomainInfo, apiId: string): Promise<void> {
const params = {
ApiId: apiId,
ApiMappingId: oldMappingId,
ApiMappingKey: domain.basePath,
DomainName: domain.domainName,
Stage: domain.stage,
};
// Make API call
try {
await this.apigatewayv2.updateApiMapping(params).promise();
this.domainManagerLog(`Updated API mapping for ${domain.domainName}`);
} catch (err) {
this.logIfDebug(err);
throw new Error(`Error: Unable to update mapping for ${domain.domainName}.\n`);
}
}
/**
* Gets rest API id from CloudFormation stack
*/
public async getApiId(domain: DomainInfo): Promise<string> {
const provider = this.serverless.service.provider;
if (!domain.websocket && provider.apiGateway && provider.apiGateway.restApiId) {
const restApiId = provider.apiGateway.restApiId;
const msg = `Mapping ${domain.domainName} to existing API ${restApiId}.`;
this.domainManagerLog(msg);
return provider.apiGateway.restApiId;
} else if (domain.websocket && provider.apiGateway && provider.apiGateway.websocketApiId) {
const websocketApiId = provider.apiGateway.websocketApiId;
const msg = `Mapping ${domain.domainName} to existing API ${websocketApiId}.`;
this.domainManagerLog(msg);
return provider.apiGateway.websocketApiId;
}
const stackName = provider.stackName || `${this.serverless.service.service}-${domain.stage}`;
const params = {
LogicalResourceId: "",
StackName: stackName,
};
if (!domain.websocket) {
params.LogicalResourceId = "ApiGatewayRestApi";
} else {
params.LogicalResourceId = "WebsocketsApi";
}
let response;
try {
response = await this.cloudformation.describeStackResource(params).promise();
} catch (err) {
this.logIfDebug(err);
throw new Error(`Error: Failed to find CloudFormation resources for ${domain.domainName}\n`);
}
const apiID = response.StackResourceDetail.PhysicalResourceId;
if (!apiID) {
const conditional = !domain.websocket ? "RestApiId" : "WebsocketApiId";
throw new Error(`Error: No ${conditional} associated with CloudFormation stack ${stackName}`);
}
return apiID;
}
/**
* Deletes basepath mapping
*/
public async deleteMapping(apiMappingId: string, domain: DomainInfo): Promise<void> {
const params = {
ApiMappingId: apiMappingId,
DomainName: domain.domainName,
};
// Make API call
try {
await this.apigatewayv2.deleteApiMapping(params).promise();
this.domainManagerLog(`Removed mapping for ${domain.domainName}.`);
} catch (err) {
this.logIfDebug(err);
this.domainManagerLog(`Unable to remove mapping for ${domain.domainName}.`);
}
}
/**
* Adds the domain name and distribution domain name to the CloudFormation outputs
*/
public addOutputs(domainInfo: DomainInfo): void {
const service = this.serverless.service;
if (!service.provider.compiledCloudFormationTemplate.Outputs) {
service.provider.compiledCloudFormationTemplate.Outputs = {};
}
service.provider.compiledCloudFormationTemplate.Outputs.aliasTarget = {
Value: domainInfo.aliasTarget,
};
if (domainInfo.aliasHostedZoneId) {
service.provider.compiledCloudFormationTemplate.Outputs.aliasHostedZoneId = {
Value: domainInfo.aliasHostedZoneId,
};
}
}
/**
* Logs message if SLS_DEBUG is set
* @param message message to be printed
*/
public logIfDebug(message: any): void {
if (process.env.SLS_DEBUG) {
this.serverless.cli.log(message, "Domain Manager");
}
}
/**
* Logs domain manager specific messages
* @param message message to be printed
*/
public domainManagerLog(message: any) {
this.serverless.cli.log(message, "Domain Manager");
}
/**
* Lifecycle function to remove API mappings for HTTP and websocket endpoints
*/
public async removeMappings(): Promise<void> {
const iterator = this.domains.entries();
let domain = iterator.next();
while (!domain.done) {
const domainInfo = domain.value[1];
try {
if (domainInfo.enabled) {
const apiId = await this.getApiId(domainInfo);
const currentMapping = await this.getMapping(apiId, domainInfo);
await this.deleteMapping(currentMapping, domainInfo);
domain = iterator.next();
}
} catch (err) {
switch (err.code) {
case "NotFoundException":
this.logIfDebug(`Mappings for domain ${domainInfo} not found. Skipping...`);
break;
default:
this.logIfDebug(err);
const msg = `Unable to remove mapping for ${domainInfo.domainName}. SLS_DEBUG=* for more info.`;
this.domainManagerLog(msg);
}
domain = iterator.next();
}
}
}
/**
* Prints out a summary of all domain manager related info
*/
private printDomainSummary(print: any): void {
this.serverless.cli.consoleLog(chalk.yellow.underline("Serverless Domain Manager Summary"));
print.forEach((v) => {
if (typeof v === "object") {
const apiType = !v.websocket ? "REST" : "Websocket";
this.serverless.cli.consoleLog(chalk.yellow(`${v.domainName} (${apiType}):`));
this.serverless.cli.consoleLog(` Target Domain: ${v.aliasTarget}`);
this.serverless.cli.consoleLog(` Hosted Zone Id: ${v.aliasHostedZoneId}`);
} else {
this.serverless.cli.consoleLog(print);
}
});
}
private sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
export = ServerlessCustomDomain;