emil-petras / strapi-blurhash

A plugin for Strapi CMS that generates blurhash for your uploaded images
https://www.npmjs.com/package/strapi-blurhash
20 stars 16 forks source link

Does not generate hash when updating file #1

Closed tefkah closed 1 year ago

tefkah commented 1 year ago

Hi! Thanks for the package, works like a charm when uploading new images!

I noticed however that when, say, updating the title of an image, the hash would not get updated. this is because the beforeUpdateData looks like this.

{
  name: 'Marcel.jfif',
  alternativeText: "Marcel's face",
  caption: '',
  folder: undefined,
  folderPath: undefined,
  updatedBy: 3,
  updatedAt: 2023-01-26T12:45:07.219Z
}

I get that that may be the indented behavior, but I wanted a way to easily generate hashes for existing images without having to reupload everything.

For anyone like me, replace the code in bootstrap.js with the following and run patch-package for that result. If the image is newly created/uploaded, it will work as usual. If not, it will get the full data from the db, check if there already is a hash for it, and if not generate one.

'use strict';

module.exports = ({ strapi }) => {

  const generateBlurhash = async (event) => {
    const { data, where } = event.params;

    if ((data.mime && data.mime.startsWith('image/'))) {
      data.blurhash = await strapi.plugin('strapi-blurhash').service('blurhash').generateBlurhash(data.url);
    }

    const fullData = await strapi.db.query('plugin::upload.file').findOne({
      select: ['url', 'blurhash', 'name', 'mime'],
      where
    })

    if ((fullData.mime && fullData.mime.startsWith('image/')) && !fullData.blurhash) {
      data.blurhash = await strapi.plugin('strapi-blurhash').service('blurhash').generateBlurhash(fullData.url);
    }
  };

  strapi.db.lifecycles.subscribe({
    models: ['plugin::upload.file'],
    beforeCreate: generateBlurhash,
    beforeUpdate: generateBlurhash,
  });
};
emil-petras commented 1 year ago

Great idea. I've added you as a contributor. Create a pull request to the main branch. Just make sure to tag it to v1.1.

I would just like to make one small change to your idea. Make it configurable. So that this check can be enabled/disabled in the config file.

Contact me if you have any issues.

cortopy commented 1 year ago

What happened to this? Was it merged anywhere?

trijpstra-fourlights commented 1 year ago

@cortopy I was using this workaround using patch-package. Saw your response, so I figured I could also just create a PR using the solution provided by @tefkah.