GithubHelp home page GithubHelp logo

It is possible to cache image and using the 'if-modified-since' keep synchronization with the server about react-native-cached-image HOT 4 CLOSED

kfiroo avatar kfiroo commented on June 4, 2024
It is possible to cache image and using the 'if-modified-since' keep synchronization with the server

from react-native-cached-image.

Comments (4)

Micjoyce avatar Micjoyce commented on June 4, 2024 1

@kfiroo Thank you for your advice

from react-native-cached-image.

kfiroo avatar kfiroo commented on June 4, 2024

@Micjoyce Hey,
Looks like you have 2 separate issues here.

  1. You would need to clear the currently cached image for the user avatar url, otherwise a request would not be made to your server and the local image would be used.
  2. You need to let your server know that it needs to return a new image data and not a 304.

Actually you only need to solve one of them to get the functionality you want.
If you let the client manage the cache, the server can always return a fresh image and you can count on the client to not make unnecessary requests.
If you let the server manage the cache you can use a normal Image and manage the last modified somewhere in your client data store.

I would go with the first approach, of letting the clients manage the cache, so there isn't really a need to send the last modified timestamp.

However, you still need to know the avatar has changed so you could clear the cached image.
Not sure how your app works, but if you give me more info I'd be happy to help :)

from react-native-cached-image.

Micjoyce avatar Micjoyce commented on June 4, 2024

@kfiroo
Very thank you for your reply.

there is my backend server processing flow and code.

121

// example: http://www.mywebsiteserver.com/avatar/username.jpg

return WebApp.connectHandlers.use('/avatar/', Meteor.bindEnvironment(function(req, res /*, next*/) {
    const params = {
      username: decodeURIComponent(req.url.replace(/^\//, '').replace(/\?.*$/, ''))
    };

    let username = params.username.replace(/\.jpg$/, '').replace(/^@/, '');

    if (_.isEmpty(params.username)) {
      res.writeHead(403);
      res.write('Forbidden');
      res.end();
      return;
    }

    // get file from gridfs by username + filetype
    let file = SeerlineFileAvatarInstance.getFileWithReadStream(encodeURIComponent(`${ username }.jpg`));
    res.setHeader('Content-Disposition', 'inline');

    // if user not set avatar file, we return a default one
    if (!file) {
      res.setHeader('Content-Type', 'image/jpeg');
      res.setHeader('Cache-Control', 'public, max-age=0');
      res.setHeader('Expires', '-1');
      res.setHeader('Last-Modified', 'Thu, 01 Jan 2015 00:00:00 GMT');

      const reqModifiedHeader = req.headers['if-modified-since'];

      if (reqModifiedHeader) {
        if (reqModifiedHeader === 'Thu, 01 Jan 2015 00:00:00 GMT') {
          res.writeHead(304);
          res.end();
          return;
        }
      }

      let lastLetterCode = Number(username.slice(-1).charCodeAt().toString().slice(-1)) % 6;
      if (isNaN(lastLetterCode) || lastLetterCode === 0) {
        lastLetterCode = 1;
      }
      // get a default avatar, before we had seted
      file = SeerlineFileAvatarInstance.getFileWithReadStream(encodeURIComponent(`${lastLetterCode}.png`));
      file.readStream.pipe(res);
      res.end();

      return;
    }

    // if client has cached and request with ['if-modified-since']
    // we will compare with server save time
    // if equal return 304 status code
    const reqModifiedHeader = req.headers['if-modified-since'];
    if (reqModifiedHeader) {
      if (reqModifiedHeader === (file.uploadDate && file.uploadDate.toUTCString())) {
        res.setHeader('Last-Modified', reqModifiedHeader);
        res.writeHead(304);
        res.end();
        return;
      }
    }
    // ready return file data
    res.setHeader('Cache-Control', 'public, max-age=0');
    res.setHeader('Expires', '-1');
    res.setHeader('Last-Modified', (file.uploadDate && file.uploadDate.toUTCString()) || new Date().toUTCString());
    res.setHeader('Content-Length', file.length);

    if (file.contentType) {
      res.setHeader('Content-Type', file.contentType);
    } else {
      file.readStream.once('data', function(chunk) {
        const fileType = getFileType(chunk);
        if (fileType) {
          return res.setHeader('Content-Type', fileType.mime);
        } else {
          return res.setHeader('Content-Type', 'image/jpeg');
        }
      });
    }
    file.readStream.pipe(res);
  }));
});

from react-native-cached-image.

kfiroo avatar kfiroo commented on June 4, 2024

@Micjoyce Hey, as I said before, if you use this module (or any other) for client side caching, the if-modified-since header is not needed. The client would not send any requests to the server if it has a cached version.

I guess you server code might be serving other platforms (such as a web platform) so I wouldn't change it, but I wouldn't worry about it in your RN app.

The only thing you need to take care of is clearing the cache when the user changes his profile picture so that the cache would be updated.

from react-native-cached-image.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.