9

I have implemented the functionality to upload files related to an entry.

For example I have a collection type Articles, which has the field photos.

When uploading a file, I can specify the collection, the entry of the collection and the filed to add the media data to.

Now I want to implement the same for deleting a file.

How would I implement this. As far as I know there is no similar method where I delete a media item and it automatically removes the associated entry of my photos field. So I would do it in multiple steps:

  1. Fetch the Articles Entry where I want to remove an item of the photos field.
  2. Update the Articles Entry with a PUT Request, where I remove an entry of the photos field.
  3. Remove the associated Upload with a DELETE Request.

However does this not allow data race conditions between set 1 and 2? How can I make sure that step 2 updates the latest Entry and there are no updates to the Entry after I have fetched it in step 1?

Jonas
  • 7,089
  • 15
  • 49
  • 110

1 Answers1

0

You will have to modify the delete service for that specific API.

Check pass a hint to the backend if you want to delete the associate file or the file id or something, and then check if that "hint" exists when the delete service runs, if so, delete the file

const file = await strapi.plugins['upload'].services.upload.fetch({ id });
await strapi.plugins['upload'].services.upload.remove(file);

This is the example from Strapi Docs:

async delete(entityId, params) {
  // some logic here
  const result = await super.delete(entityId, params);
  // some more logic

  return result;
}

More can you read about here: https://docs.strapi.io/dev-docs/backend-customization/services#extending-core-services

Andrei
  • 49
  • 8