Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GraphQL removing files #5292

Closed
nezzard opened this issue Feb 21, 2020 · 2 comments · Fixed by #7937
Closed

GraphQL removing files #5292

nezzard opened this issue Feb 21, 2020 · 2 comments · Fixed by #7937
Labels
good first issue Good for newcomers issue: feature request Issue suggesting a new feature severity: low If the issue only affects a very niche base of users and an easily implemented workaround can solve

Comments

@nezzard
Copy link

nezzard commented Feb 21, 2020

Hi, it would be very good if it were possible to delete previously uploaded files through GraphQL.

Now we are developing an online store, when adding goods, the manager can upload thumbnails to the goods, I need to give the opportunity to delete previously uploaded thumbnails through GraphQL.

Everything is built on Apollo nuxt, I would not want to use it to remove axios thumbnails.

@alexandrebodin alexandrebodin added good first issue Good for newcomers severity: low If the issue only affects a very niche base of users and an easily implemented workaround can solve issue: feature request Issue suggesting a new feature labels Feb 21, 2020
@alexandrebodin
Copy link
Member

Hi @nezzard It sure would be cool to support it. This would be fairly straight forward to implement.

If you feel like opening a PR don't hesitate to reach out on slack ;)

@nitronapp
Copy link

nitronapp commented Mar 5, 2020

You can create a custom upload mutation and in resolver check for the previous file and delete it before uploading the new one. Example:

const path = require('path');
const _ = require('lodash');
const crypto = require('crypto');
const toArray = require('stream-to-array');
const uuid = require('uuid/v4');

function niceHash(buffer) {
  return crypto
    .createHash('sha256')
    .update(buffer)
    .digest('base64')
    .replace(/=/g, '')
    .replace(/\//g, '-')
    .replace(/\+/, '_');
}

module.exports = {
    mutation: `
        customUpload(refId: ID, ref: String, field: String, source: String, file: Upload!): UploadFile!
    `,
    resolver: {
        Mutation: {
          customUpload: {
            description: 'Upload one file',
            plugin: 'upload',
            resolverOf: 'Upload.upload',
            resolver: async (obj, { file: upload, ...fields }) => {
              const file = await formatFile(upload, fields);
    
              const config = await strapi
                .store({
                  environment: strapi.config.environment,
                  type: 'plugin',
                  name: 'upload',
                }).get({ key: 'provider' });
               
              //Here we do our check for previous file and delete if available
              const result = await strapi.query(fields.ref).findOne({id: fields.refId});
              if(result[fields.field]) {
                const deleteResult = await strapi.query('file', 'upload').delete({ id: result[fields.field].id });
              }

              //Continue uploading
              const uploadedFiles = await strapi.plugins.upload.services.upload.upload(
                [file],
                config
              );

              // Return response.
              return uploadedFiles.length === 1 ? uploadedFiles[0] : uploadedFiles;
            },
          }
        }
    }
}

const formatFile = async (upload, fields) => {
    const { filename, mimetype, createReadStream } = await upload;
  
    const stream = createReadStream();
  
    const parts = await toArray(stream);
    const buffers = parts.map(part =>
      _.isBuffer(part) ? part : Buffer.from(part)
    );
  
    const buffer = Buffer.concat(buffers);
  
    const { refId, ref, source, field } = fields;
    
    const fileData = {
      name: filename,
      sha256: niceHash(buffer),
      hash: uuid().replace(/-/g, ''),
      ext: path.extname(filename),
      buffer,
      mime: mimetype,
      size: (buffer.length / 1000).toFixed(2),
    };
 
    // Add details to the file to be able to create the relationships.
    if (refId && ref && field) {
      fileData.related = [
        {
          refId,
          ref,
          source,
          field,
        },
      ];
    }
  
    return fileData;
  };

francois2metz added a commit to francois2metz/strapi that referenced this issue Sep 17, 2020
Signed-off-by: François de Metz <francois@2metz.fr>
francois2metz added a commit to francois2metz/strapi that referenced this issue Sep 22, 2020
Signed-off-by: François de Metz <francois@2metz.fr>
francois2metz added a commit to francois2metz/strapi that referenced this issue Sep 29, 2020
Signed-off-by: François de Metz <francois@2metz.fr>
francois2metz added a commit to francois2metz/strapi that referenced this issue Oct 2, 2020
Signed-off-by: François de Metz <francois@2metz.fr>
alexandrebodin pushed a commit that referenced this issue Oct 5, 2020
* Implement deleteFile graphql mutation (#5292).

Signed-off-by: François de Metz <francois@2metz.fr>

* Test if the file exist before removing it.

Signed-off-by: François de Metz <francois@2metz.fr>

* Fix a typo.

Signed-off-by: François de Metz <francois@2metz.fr>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers issue: feature request Issue suggesting a new feature severity: low If the issue only affects a very niche base of users and an easily implemented workaround can solve
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants