0

I completed file upload now I want to fetch file from mongodb using graphql. I have tried to fetch chunks of file and then merge it but it not worked as I expected.
So how to fetch entire file from mongodb inside graphql Query?

Cheris Patel
  • 56
  • 1
  • 4
  • 1
    if `.toString('base64')` then just a string ... suitable for small files only, very ineffective ... return urls and separate endpoint[-s] to return binary content – xadm Apr 11 '21 at 18:40
  • @xadm But In my case It's return type would be string so how should I execute that query to grep string I mean `getImage(fileId: $fileId)` so which field should i have to grep in query body – Cheris Patel Apr 11 '21 at 19:00
  • 1
    just define return type as string ... nothing required on query, it can return simple type directly ... but maybe you want to return filename, type and data64 separately - https://stackoverflow.com/a/65655180/6124657 - define some type with string props ... I doubt this resolver returns data properly, promise required to return data from stream – xadm Apr 11 '21 at 20:00
  • @xadm I have tried By returning img string but its give null. I guess graphql query does not wait untill eventlistener end executed so its gives null. Any solution for this ? – Cheris Patel Apr 12 '21 at 10:13
  • 1
    I wrote earlier ... wrap into promise ... like https://stackoverflow.com/a/52976521/6124657 (or some parts from https://stackoverflow.com/a/60158660/6124657) ... await it, return (resolve(img)) value ... just search for some s3/await/buffer terms – xadm Apr 12 '21 at 11:52
  • @xadm I was totally forgot about promise... You are amazing :). You just made my day. **Thank You Thank You Very Much....** You can write answer so others can find easily and I'll sure accept it. – Cheris Patel Apr 12 '21 at 16:25
  • 1
    just post an answer, your working/tested solution ... I only helped you to gather the required knowledge – xadm Apr 12 '21 at 17:47

1 Answers1

0

Here i'm returning bas64 as string of image which is not preferable for larger file size

const downloadFile = async (fileId) => {
  const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
    bucketName: 'files',
  });
  return new Promise((resolve, reject) => {
    // temporary variable to hold image
    var data = [];

    // create the download stream
    const readstream = bucket.openDownloadStream(new ObjectID(fileId));
    readstream.on('data', function (chunk) {
      data.push(chunk);
    });
    readstream.on('error', async (error) => {
      reject(error);
    });
    readstream.on('end', async () => {
      let bufferBase64 = Buffer.concat(data);
      const img = bufferBase64.toString('base64');
      resolve(img);
    });
  });
};

And this is query for fetching image

async getImage(_, { fileId }) {
  try {
    const img = await downloadFile(fileId);
    return img;
  } catch (error) {
    throw new Error(error);
  }
},
Cheris Patel
  • 56
  • 1
  • 4