|
1 | 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
2 | 2 | // SPDX-License-Identifier: Apache-2.0 |
3 | 3 |
|
4 | | -import { fileURLToPath } from "url"; |
5 | | - |
6 | 4 | // snippet-start:[s3.JavaScript.buckets.deleteBucketV3] |
7 | | -import { DeleteBucketCommand, S3Client } from "@aws-sdk/client-s3"; |
8 | | - |
9 | | -const client = new S3Client({}); |
| 5 | +import { |
| 6 | + DeleteBucketCommand, |
| 7 | + S3Client, |
| 8 | + S3ServiceException, |
| 9 | +} from "@aws-sdk/client-s3"; |
10 | 10 |
|
11 | | -// Delete a bucket. |
12 | | -export const main = async () => { |
| 11 | +/** |
| 12 | + * Delete an Amazon S3 bucket. |
| 13 | + * @param {{ bucketName: string }} |
| 14 | + */ |
| 15 | +export const main = async ({ bucketName }) => { |
| 16 | + const client = new S3Client({}); |
13 | 17 | const command = new DeleteBucketCommand({ |
14 | | - Bucket: "test-bucket", |
| 18 | + Bucket: bucketName, |
15 | 19 | }); |
16 | 20 |
|
17 | 21 | try { |
18 | | - const response = await client.send(command); |
19 | | - console.log(response); |
20 | | - } catch (err) { |
21 | | - console.error(err); |
| 22 | + await client.send(command); |
| 23 | + console.log(`Bucket was deleted.`); |
| 24 | + } catch (caught) { |
| 25 | + if ( |
| 26 | + caught instanceof S3ServiceException && |
| 27 | + caught.name === "NoSuchBucket" |
| 28 | + ) { |
| 29 | + console.error( |
| 30 | + `Error from S3 while deleting bucket. The bucket doesn't exist.`, |
| 31 | + ); |
| 32 | + } else if (caught instanceof S3ServiceException) { |
| 33 | + console.error( |
| 34 | + `Error from S3 while deleting the bucket. ${caught.name}: ${caught.message}`, |
| 35 | + ); |
| 36 | + } else { |
| 37 | + throw caught; |
| 38 | + } |
22 | 39 | } |
23 | 40 | }; |
24 | 41 | // snippet-end:[s3.JavaScript.buckets.deleteBucketV3] |
25 | 42 |
|
26 | | -// Invoke main function if this file was run directly. |
27 | | -if (process.argv[1] === fileURLToPath(import.meta.url)) { |
28 | | - main(); |
| 43 | +// Call function if run directly |
| 44 | +import { parseArgs } from "util"; |
| 45 | +import { |
| 46 | + isMain, |
| 47 | + validateArgs, |
| 48 | +} from "@aws-doc-sdk-examples/lib/utils/util-node.js"; |
| 49 | + |
| 50 | +const loadArgs = () => { |
| 51 | + const options = { |
| 52 | + bucketName: { |
| 53 | + type: "string", |
| 54 | + required: true, |
| 55 | + }, |
| 56 | + }; |
| 57 | + const results = parseArgs({ options }); |
| 58 | + const { errors } = validateArgs({ options }, results); |
| 59 | + return { errors, results }; |
| 60 | +}; |
| 61 | + |
| 62 | +if (isMain(import.meta.url)) { |
| 63 | + const { errors, results } = loadArgs(); |
| 64 | + if (!errors) { |
| 65 | + main(results.values); |
| 66 | + } else { |
| 67 | + console.error(errors.join("\n")); |
| 68 | + } |
29 | 69 | } |
0 commit comments