1
1
import type { Media , Product } from "@/payload-types" ;
2
2
import type { AfterDeleteHook } from "node_modules/payload/dist/collections/config/types" ;
3
- import type { BasePayload } from "payload" ;
4
3
5
4
import { isExpandedDoc } from "@/utils/is-expended-doc" ;
6
5
7
6
export const deleteMedia : AfterDeleteHook < Product > = async ( { doc, req } ) => {
8
7
const { payload } = req ;
9
-
10
8
req . payload . logger . debug ( `Starting to delete media for product: ${ doc . id } ` ) ;
11
9
10
+ const mediaMap = new Map < string , Media > ( ) ;
11
+
12
12
for ( const variant of doc . variants ) {
13
13
if ( ! variant . gallery ) {
14
14
req . payload . logger . debug ( `Skipping variant - no gallery found` ) ;
@@ -17,29 +17,50 @@ export const deleteMedia: AfterDeleteHook<Product> = async ({ doc, req }) => {
17
17
18
18
req . payload . logger . debug ( `Processing gallery deletion for variant` ) ;
19
19
20
- await deleteGalleryImages ( variant . gallery , payload ) ;
20
+ for ( const image of variant . gallery ) {
21
+ if ( isExpandedDoc < Media > ( image ) ) {
22
+ if ( ! mediaMap . has ( image . filename ) ) {
23
+ mediaMap . set ( image . filename , image ) ;
24
+ } else {
25
+ req . payload . logger . debug (
26
+ `Duplicate filename detected, skipping: ${ image . filename } `
27
+ ) ;
28
+ }
29
+ } else {
30
+ req . payload . logger . debug ( `Skipping image - not expanded` ) ;
31
+ }
32
+ }
21
33
}
22
- } ;
23
34
24
- async function deleteGalleryImages (
25
- gallery : ( Media | number ) [ ] ,
26
- payload : BasePayload
27
- ) {
28
- payload . logger . debug ( `Deleting gallery images, count: ${ gallery . length } ` ) ;
35
+ const uniqueImages = Array . from ( mediaMap . values ( ) ) ;
29
36
30
- for ( const image of gallery ) {
31
- if ( ! isExpandedDoc < Media > ( image ) ) {
32
- payload . logger . debug ( `Skipping image - no access to filename` ) ;
33
- continue ;
34
- }
35
- payload . logger . debug ( `Deleting media with filename: ${ image . filename } ` ) ;
36
- await payload . delete ( {
37
- collection : "media" ,
38
- where : {
39
- filename : {
40
- equals : image . filename ,
41
- } ,
42
- } ,
43
- } ) ;
44
- }
45
- }
37
+ req . payload . logger . debug (
38
+ `Deleting ${ uniqueImages . length } unique media files`
39
+ ) ;
40
+
41
+ const deletionResults = await Promise . allSettled (
42
+ uniqueImages . map ( ( image ) =>
43
+ payload
44
+ . delete ( {
45
+ id : image . id ,
46
+ collection : "media" ,
47
+ req,
48
+ } )
49
+ . then ( ( ) => {
50
+ payload . logger . debug (
51
+ `Successfully deleted: ${ image . filename } `
52
+ ) ;
53
+ } )
54
+ . catch ( ( error ) => {
55
+ payload . logger . error (
56
+ `Failed to delete: ${ image . filename } ` ,
57
+ error
58
+ ) ;
59
+ } )
60
+ )
61
+ ) ;
62
+
63
+ req . payload . logger . debug (
64
+ `Deletion results: ${ JSON . stringify ( deletionResults ) } `
65
+ ) ;
66
+ } ;
0 commit comments