-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathbasic.js
332 lines (294 loc) · 9.94 KB
/
basic.js
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { fileURLToPath } from "node:url";
// snippet-start:[javascript.v3.support.scenarios.basic]
import {
AddAttachmentsToSetCommand,
AddCommunicationToCaseCommand,
CreateCaseCommand,
DescribeAttachmentCommand,
DescribeCasesCommand,
DescribeCommunicationsCommand,
DescribeServicesCommand,
DescribeSeverityLevelsCommand,
ResolveCaseCommand,
SupportClient,
} from "@aws-sdk/client-support";
import * as inquirer from "@inquirer/prompts";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
const wrapText = (text, char = "=") => {
const rule = char.repeat(80);
return `${rule}\n ${text}\n${rule}\n`;
};
const client = new SupportClient({ region: "us-east-1" });
// Verify that the account has a Support plan.
export const verifyAccount = async () => {
const command = new DescribeServicesCommand({});
try {
await client.send(command);
} catch (err) {
if (err.name === "SubscriptionRequiredException") {
throw new Error(
"You must be subscribed to the AWS Support plan to use this feature.",
);
}
throw err;
}
};
/**
* Select a service from the list returned from DescribeServices.
*/
export const getService = async () => {
const { services } = await client.send(new DescribeServicesCommand({}));
const selectedService = await inquirer.select({
message:
"Select a service. Your support case will be created for this service. The list of services is truncated for readability.",
choices: services.slice(0, 10).map((s) => ({ name: s.name, value: s })),
});
return selectedService;
};
/**
* @param {{ categories: import('@aws-sdk/client-support').Category[]}} service
*/
export const getCategory = async (service) => {
const selectedCategory = await inquirer.select({
message: "Select a category.",
choices: service.categories.map((c) => ({ name: c.name, value: c })),
});
return selectedCategory;
};
// Get the available severity levels for the account.
export const getSeverityLevel = async () => {
const command = new DescribeSeverityLevelsCommand({});
const { severityLevels } = await client.send(command);
const selectedSeverityLevel = await inquirer.select({
message: "Select a severity level.",
choices: severityLevels.map((s) => ({ name: s.name, value: s })),
});
return selectedSeverityLevel;
};
/**
* Create a new support case
* @param {{
* selectedService: import('@aws-sdk/client-support').Service
* selectedCategory: import('@aws-sdk/client-support').Category
* selectedSeverityLevel: import('@aws-sdk/client-support').SeverityLevel
* }} selections
* @returns
*/
export const createCase = async ({
selectedService,
selectedCategory,
selectedSeverityLevel,
}) => {
const command = new CreateCaseCommand({
subject: "IGNORE: Test case",
communicationBody: "This is a test. Please ignore.",
serviceCode: selectedService.code,
categoryCode: selectedCategory.code,
severityCode: selectedSeverityLevel.code,
});
const { caseId } = await client.send(command);
return caseId;
};
// Get a list of open support cases created today.
export const getTodaysOpenCases = async () => {
const d = new Date();
const startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate());
const command = new DescribeCasesCommand({
includeCommunications: false,
afterTime: startOfToday.toISOString(),
});
const { cases } = await client.send(command);
if (cases.length === 0) {
throw new Error(
"Unexpected number of cases. Expected more than 0 open cases.",
);
}
return cases;
};
// Create an attachment set.
export const createAttachmentSet = async () => {
const command = new AddAttachmentsToSetCommand({
attachments: [
{
fileName: "example.txt",
data: new TextEncoder().encode("some example text"),
},
],
});
const { attachmentSetId } = await client.send(command);
return attachmentSetId;
};
export const linkAttachmentSetToCase = async (attachmentSetId, caseId) => {
const command = new AddCommunicationToCaseCommand({
attachmentSetId,
caseId,
communicationBody: "Adding attachment set to case.",
});
await client.send(command);
};
// Get all communications for a support case.
export const getCommunications = async (caseId) => {
const command = new DescribeCommunicationsCommand({
caseId,
});
const { communications } = await client.send(command);
return communications;
};
/**
* @param {import('@aws-sdk/client-support').Communication[]} communications
*/
export const getFirstAttachment = (communications) => {
const firstCommWithAttachment = communications.find(
(c) => c.attachmentSet.length > 0,
);
return firstCommWithAttachment?.attachmentSet[0].attachmentId;
};
// Get an attachment.
export const getAttachment = async (attachmentId) => {
const command = new DescribeAttachmentCommand({
attachmentId,
});
const { attachment } = await client.send(command);
return attachment;
};
// Resolve the case matching the given case ID.
export const resolveCase = async (caseId) => {
const shouldResolve = await inquirer.confirm({
message: `Do you want to resolve ${caseId}?`,
});
if (shouldResolve) {
const command = new ResolveCaseCommand({
caseId: caseId,
});
await client.send(command);
return true;
}
return false;
};
/**
* Find a specific case in the list of provided cases by case ID.
* If the case is not found, and the results are paginated, continue
* paging through the results.
* @param {{
* caseId: string,
* cases: import('@aws-sdk/client-support').CaseDetails[]
* nextToken: string
* }} options
* @returns
*/
export const findCase = async ({ caseId, cases, nextToken }) => {
const foundCase = cases.find((c) => c.caseId === caseId);
if (foundCase) {
return foundCase;
}
if (nextToken) {
const response = await client.send(
new DescribeCasesCommand({
nextToken,
includeResolvedCases: true,
}),
);
return findCase({
caseId,
cases: response.cases,
nextToken: response.nextToken,
});
}
throw new Error(`${caseId} not found.`);
};
// Get all cases created today.
export const getTodaysResolvedCases = async (caseIdToWaitFor) => {
const d = new Date("2023-01-18");
const startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate());
const command = new DescribeCasesCommand({
includeCommunications: false,
afterTime: startOfToday.toISOString(),
includeResolvedCases: true,
});
const { cases, nextToken } = await client.send(command);
await findCase({ cases, caseId: caseIdToWaitFor, nextToken });
return cases.filter((c) => c.status === "resolved");
};
const main = async () => {
let caseId;
try {
console.log(wrapText("Welcome to the AWS Support basic usage scenario."));
// Verify that the account is subscribed to support.
await verifyAccount();
// Provided a truncated list of services and prompt the user to select one.
const selectedService = await getService();
// Provided the categories for the selected service and prompt the user to select one.
const selectedCategory = await getCategory(selectedService);
// Provide the severity available severity levels for the account and prompt the user to select one.
const selectedSeverityLevel = await getSeverityLevel();
// Create a support case.
console.log("\nCreating a support case.");
caseId = await createCase({
selectedService,
selectedCategory,
selectedSeverityLevel,
});
console.log(`Support case created: ${caseId}`);
// Display a list of open support cases created today.
const todaysOpenCases = await retry(
{ intervalInMs: 1000, maxRetries: 15 },
getTodaysOpenCases,
);
console.log(
`\nOpen support cases created today: ${todaysOpenCases.length}`,
);
console.log(todaysOpenCases.map((c) => `${c.caseId}`).join("\n"));
// Create an attachment set.
console.log("\nCreating an attachment set.");
const attachmentSetId = await createAttachmentSet();
console.log(`Attachment set created: ${attachmentSetId}`);
// Add the attachment set to the support case.
console.log(`\nAdding attachment set to ${caseId}`);
await linkAttachmentSetToCase(attachmentSetId, caseId);
console.log(`Attachment set added to ${caseId}`);
// List the communications for a support case.
console.log(`\nListing communications for ${caseId}`);
const communications = await getCommunications(caseId);
console.log(
communications
.map(
(c) =>
`Communication created on ${c.timeCreated}. Has ${c.attachmentSet.length} attachments.`,
)
.join("\n"),
);
// Describe the first attachment.
console.log(`\nDescribing attachment ${attachmentSetId}`);
const attachmentId = getFirstAttachment(communications);
const attachment = await getAttachment(attachmentId);
console.log(
`Attachment is the file '${
attachment.fileName
}' with data: \n${new TextDecoder().decode(attachment.data)}`,
);
// Confirm that the support case should be resolved.
const isResolved = await resolveCase(caseId);
if (isResolved) {
// List the resolved cases and include the one previously created.
// Resolved cases can take a while to appear.
console.log(
"\nWaiting for case status to be marked as resolved. This can take some time.",
);
const resolvedCases = await retry(
{ intervalInMs: 20000, maxRetries: 15 },
() => getTodaysResolvedCases(caseId),
);
console.log("Resolved cases:");
console.log(resolvedCases.map((c) => c.caseId).join("\n"));
}
} catch (err) {
console.error(err);
}
};
// snippet-end:[javascript.v3.support.scenarios.basic]
// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main();
}