0.1.0 • Published 4 years ago

react-native-async-cache v0.1.0

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

react-native-async-cache

Getting started

$ npm install react-native-async-cache --save

Mostly automatic installation

$ react-native link react-native-async-cache

API

Promise select(options)

The only method need to know, return a promise resolves an object containing url. If the file downloaded, resolve the url as local path, otherwise resolve the request given.

  • Request Options
OptionOptionalTypeDescription
urlNOStringthe network resource url
headersYESMap<String,String>http request headers
subDirYESStringname of directory where the file save to
extensionYESStringfile extension (e.g ''.jpg" or "jpg")
idYESStringfile unique identification, advance usage
dataYESStringbinary custom data
dataTypeYESStringtype of custom data, "text", "base64" or "base64Url"
signYESStringfile identification obfuscation
  • Result
ParamTypeDescription
successBooleanwhether the file is cached
urlStringthe url from given request or the file path prefix with file:// that been cached
statusCodeIntegerit's nonzero and nonnull if request failed
messageStringthe failure description
  • Usage example
import React from "react";
import RNAsyncCache from 'react-native-async-cache';

export default class extends React.Component
{
    componentDidMount(){
        RNAsyncCache.select({
            url: "https://static.zerochan.net/Kouyafu.full.2927619.jpg"
        }).then((res) => {
            const {url, statusCode, message} = res;
            this.setState(
                {img: url, statusCode, message}
            );
        });
    }

    // Component initial state

    state = {
        img:"",
        statusCode: 0,
        message:""
    };


    // Component render

    render()
    {
        const {img, statusCode, message} = this.state;

        if(statusCode || message){
            // request failed
            return <Text>{statusCode} {message}</Text>;
        }

    	return img ? <Text>Loading...</Text>: <Image source={{uri: img}}/>;
    }
}

Promise trash(options)

Empty the cache directory.

  • Request Options
OptionOptionalTypeDescription
subDirYESStringname of directory be emptied

Promise accessible(options)

Try to check http status code of the url is 200 OK.

  • Request Options
OptionOptionalTypeDescription
urlNOStringnetwork resource url
statusCodeLeftYESIntegermin valid status code
statusCodeRightYESIntegermax valid status code
accessibleMethodYESStringhttp method, default "HEAD"
headersYESMap<String,String>request headers
  • Result
ParamTypeDescription
accessibleBooleanwhether the file is cached
statusCodeStringhttp status code or -1 if runtime exception occurred
messageStringdescription of failure
sizeNumbertotal bytes of resource, may be -1 if server not support Content-Length
urlStringrequest url
import React from "react";
import RNAsyncCache from 'react-native-async-cache';
import {Image, Text} from "react-native";

export default class extends React.Component {
    state = {
        error:""
    };

    render(){
        const {error} = this.state;
        const img = "https://i.pximg.net/img-master/img/2020/04/04/00/10/00/80545109_p0_master1200.jpg";

        return error ? (<Text>{error}</Text>) : <Image source={{uri:img}} onError={()=>{
            RNAsyncCache.accessible({
                url:img
            }).then(({statusCode, message})=>{
                this.setState({
                    error: statusCode + "\n" + message
                });
            });
        }} />
    }
}

Promise check(options)

Confirm whether the cache file exists.

  • Request Options
OptionOptionalType
urlNOString
subDirYESString
extensionYESString
  • Result
ParamTypeDescription
pathStringnot empty if the file exists
existsBooleanwhether the file exists
urlStringrequest url

Promise remove(options)

Delete the cache file specified.

  • Request Options
OptionOptionalType
urlNOString
subDirYESString
extensionYESString
  • Result
ParamTypeDescription
successStringwhether the file was deleted successfully
pathBooleanpath of the file be deleted, it's not empty if successfully removed
urlStringrequest url

Promise download(options, onProgress)

Cache a file manually.

  • Request Options
OptionOptionalType
urlNOString
subDirYESString
extensionYESString
headersYESMap<String,String>request headers
  • onProgress Callback
ParamTypeDescription
progressNumberless than 1, always 0 if total is -1
totalBoolean-1 if server not support Content-Length
currentStringbytes of written
urlStringrequest url
  • Result
ParamTypeDescription
sizeNumberthe size of the file been downloaded
pathBooleanpath of the file
urlStringrequest url

void post(options)

delegate a background download task or create a cache with url and exists data.

  • Request Options
OptionOptionalType
urlNOString
headersYESMap<String,String>
subDirYESString
extensionYESString
headersYESMap<String,String>request headers
dataYESStringcustom data
dataTypeYESString"text", bianary use "base64" or "base64Url"

Cache Component

OptionOptionalTypeDescription
ComponentNOComponentrender component with url
PendingComponentYESComponentrender component during select() execution
mapToRequestOptionsYESFunctionmap component props to request options
mapToComponentPropertiesYESFunctionmap select() result to component props
sourcePropertyYESStringname of the component property, default 'source'
invokeOnComponentErrorPropertyYESStringname of the callback function invoked on load error
invokeOnComponentLoadPropertyYESStringname of the callback function invoked on load success
sourceMapperYESFunctionmap url to local path
onSourceMappedYESFunctioninvoked on url accepted
onRequestErrorYESFunctioninvoked on url has been checked not accessible
cacheValidatorYESFunctionconfirm the cache is valid, usually not need it

Usage

import {CacheComponent} from 'react-native-async-cache';
import {Image,View} from 'react-native';

const CacheImage =  CacheComponent(
    {
        Component: Image,
        PendingComponent: Image,
        invokeOnComponentErrorProperty: 'onError',
        invokeOnComponentLoadProperty: 'onLoad',
        mapToRequestOptions: () => {
            return {
                subDir: 'images'
            };
        },
        mapToComponentProperties: (props) => {
            return {
                source: typeof props.source === 'number' ? props.source : {uri: props.source},
                errorMessage: (props.statusCode || props.message) ? props.statusCode + ' ' + (props.message || '') : null
            };
        }
    }
);

// render component

export default class extends React.Component
{
    render(){
        return (
            <View style={{flex: 1, alignItems: "center"}}>
                <CacheImage source={"https://static.zerochan.net/Kouyafu.full.2792022.jpg"} 				
					style={{
                        width : Dimensions.get("window").width - 30,
                        height : Dimensions.get("window").height
                    }}
                />
            </View>
        );
    }
}

CacheStoreComponent

create a CacheComponent with a memory store to reduce select() calls.

import {CacheStoreComponent} from 'react-native-async-cache';
import {Text,View,Image} from "react-native";

const CacheStoreImage =  CacheStoreComponent(
    {
        Component: Image,
        PendingComponent: ()=>{
            return <View><Text>Loading...</Text></View>;
        },
        invokeOnComponentErrorProperty: 'onError',
        invokeOnComponentLoadProperty: 'onLoad',
        mapToRequestOptions: () => {
            return {
                subDir: 'images'
            };
        },
        mapToComponentProperties: (props) => {
            return {
                source: typeof props.source === 'number' ? props.source : {uri: props.source},
                errorMessage: (props.statusCode || props.message) ? props.statusCode + ' ' + (props.message || '') : null
            };
        }
    }
);

// render component

export default ()=>{
    return (
        <View style={{flex: 1, alignItems: "center"}}>
           <CacheStoreImage source={"https://static.zerochan.net/Fuji.Choko.full.2920380.jpg"} style={{
               width : Dimensions.get("window").width - 30,
               height : Dimensions.get("window").height
           }}/>
       </View>
    );
}
  • Custom StoreProvider Example
import {CacheStoreComponent, StoreProvider} from 'react-native-async-cache';
import AsyncStorage from 'react-native-async-storage';

// extend default StoreProvider

class PersistenceStoreProvider extends StoreProvider {
    access_time = 0;

    constructor(props) {
        super(props);
        AsyncStorage.getItem('caches').then(str=>{
            this.caches=JSON.parse(str);
        });
    }
    
    get(url){
        ++this.access_time;
        if(this.access_time > 100){
            this.access_time = 0;
            this.serialize();
        }
        return super.get(url);
    } 

    
    serialize(){
        // call it at the right time
        AsyncStorage.setItem('caches',JSON.stringify(caches));
    }
    
    clear(){
        // optional, call it when local file not found
        this.caches = [];
        AsyncStorage.setItem('caches',JSON.stringify([]));
    }
}

// create CacheStoreComponent

export default CacheStoreComponent({ 
    store: new PersistenceStoreProvider(),
    // ...
});
  • Optional cache validator
// improt fs from "react-native-fs";

// config
const config = {
    store: new PersistenceStoreProvider(),
    // ...
    cacheValidator:(cache,callback)=>{
        if(cache && !cache.local){
            callback(cache);
        }
        else {
            fs.exists(cache).then(exists=>{
               callback(exists ? cache : null);
               if(!exists)
               {
                    config.store.clear();
               }
            });    
        }       
    }
}

export default CacheStoreComponent(config);
  • Advanced usage, StoreProvider interface
interface StoreProvider {
    get(url: string): string;

    set(url: string, local: string): void;

    error(url: string, code: number, message: string): void
}
Callback MethodDescription
getreturn nullable cache file path with url
setassociate local path to url
errorinvoked if resource is inaccessible
0.1.0

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago