|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import { AmplifyClassV6 } from '@aws-amplify/core'; |
| 5 | +import { StorageAction } from '@aws-amplify/core/internals/utils'; |
| 6 | + |
| 7 | +import { RemoveObjectsInput, RemoveObjectsOutput } from '../../types'; |
| 8 | +import { |
| 9 | + calculateContentMd5, |
| 10 | + resolveS3ConfigAndInput, |
| 11 | + validateBucketOwnerID, |
| 12 | +} from '../../utils'; |
| 13 | +import { deleteObjects } from '../../utils/client/s3data'; |
| 14 | +import { getStorageUserAgentValue } from '../../utils/userAgent'; |
| 15 | +import { logger } from '../../../../utils'; |
| 16 | + |
| 17 | +export const removeObjects = async ( |
| 18 | + amplify: AmplifyClassV6, |
| 19 | + input: RemoveObjectsInput, |
| 20 | +): Promise<RemoveObjectsOutput> => { |
| 21 | + // @ts-expect-error input type |
| 22 | + const { s3Config, bucket } = await resolveS3ConfigAndInput(amplify, input); |
| 23 | + |
| 24 | + validateBucketOwnerID(input.options?.expectedBucketOwner); |
| 25 | + |
| 26 | + if (!input.paths || input.paths.length === 0) { |
| 27 | + throw new Error('At least one path must be provided'); |
| 28 | + } |
| 29 | + |
| 30 | + if (input.paths.length > 1000) { |
| 31 | + throw new Error('Cannot delete more than 1000 objects in a single request'); |
| 32 | + } |
| 33 | + |
| 34 | + logger.debug( |
| 35 | + `removing ${input.paths.length} objects from bucket "${bucket}"`, |
| 36 | + ); |
| 37 | + |
| 38 | + // Build XML body for MD5 calculation |
| 39 | + const objects = input.paths |
| 40 | + .map(path => `<Object><Key>${path}</Key></Object>`) |
| 41 | + .join(''); |
| 42 | + const xmlBody = `<?xml version="1.0" encoding="UTF-8"?> |
| 43 | +<Delete xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> |
| 44 | + <Quiet>false</Quiet> |
| 45 | + ${objects} |
| 46 | +</Delete>`; |
| 47 | + |
| 48 | + // Calculate Content-MD5 (required for DeleteObjects) |
| 49 | + const contentMd5 = await calculateContentMd5(xmlBody); |
| 50 | + |
| 51 | + const result = await deleteObjects( |
| 52 | + { |
| 53 | + ...s3Config, |
| 54 | + userAgentValue: getStorageUserAgentValue(StorageAction.Remove), |
| 55 | + }, |
| 56 | + { |
| 57 | + Bucket: bucket, |
| 58 | + Delete: { |
| 59 | + Objects: input.paths.map(path => ({ Key: path })), |
| 60 | + Quiet: false, |
| 61 | + }, |
| 62 | + ExpectedBucketOwner: input.options?.expectedBucketOwner, |
| 63 | + ContentMD5: contentMd5, |
| 64 | + }, |
| 65 | + ); |
| 66 | + |
| 67 | + return { |
| 68 | + deleted: result.Deleted?.map(item => ({ path: item.Key! })) || [], |
| 69 | + errors: |
| 70 | + result.Errors?.map(error => ({ |
| 71 | + path: error.Key!, |
| 72 | + code: error.Code!, |
| 73 | + message: error.Message!, |
| 74 | + })) || [], |
| 75 | + }; |
| 76 | +}; |
0 commit comments