[Features] Caching images to files (base64 to .jpg)

PHOTO EMBED

Mon Mar 07 2022 16:14:39 GMT+0000 (Coordinated Universal Time)

Saved by @luxylone

import RNFS  from 'react-native-fs';
import { FAMOUS_WOMAN } from '../constants/famousWomenTypes';
import { PLACE } from '../constants/placesType';


 var filePath = RNFS.CachesDirectoryPath

export const fileExists = (data: any, type: FAMOUS_WOMAN | PLACE) => {
   
    type === FAMOUS_WOMAN ? filePath = `${RNFS.CachesDirectoryPath}/${data.firstName}${data.id}.jpg`
    : filePath = `${RNFS.CachesDirectoryPath}/${data.name}${data.id}.jpg`;

    console.log(filePath);
    
    RNFS.exists(filePath)
    .then(success => {
        if (success) {
            readFile(filePath);
        } else {
            writeFile(data, type);
        }
    })
    .catch(err => {
        console.log(err.message, err.code);
    });
}


const readFile = (filePath: any) => {
    RNFS.readFile(filePath, 'base64')
        .then(content => {
            // Do what you need if the file exists
            console.log('File exists');
            
        })
        .catch(err => {
            console.log(err.message, err.code);
    });
};

 const writeFile = (data: any, type:  FAMOUS_WOMAN | PLACE) => {
     let imageData;
     let imagePath;
     if (type === FAMOUS_WOMAN)
     {
         imageData = data.profilePicture;
         imagePath = `${RNFS.CachesDirectoryPath}/${data.firstName}${data.id}.jpg`;
     }else
     {
        imageData = data.picture;
        imagePath = `${RNFS.CachesDirectoryPath}/${data.name}${data.id}.jpg`;
     }
    
    
    RNFS.writeFile(imagePath, imageData, 'base64')
        .then(() => console.log('Image converted to jpg and saved at ' + imagePath));
 };
content_copyCOPY