datavan, which provide more features
Deprecated and please migrate toHTTP API Accessor for React with auto-reactive-cache and middlewares. Restful React reactive cache for any async calls, http fetching, or memory store accesses.
Features
-
auto-reactive-cache
- API results are cached and auto prune
- AutoRunner(function) auto watch and re-run when related caches changed
- reget.get() is synchronized function, which get cache and trigger http fetch as a side effect
-
middlewares
- koa middleware like
- can use middlewares to convert data, as ORM or distribute to diff cache keys
- also work for synchronized access or localStorage or memory
How It works?
reget is simple key-value cache. During data getting, reget will call a list of middlewares if cache is missing or too old. Result from middlewares will put into the cache and notify all listeners.
You can implement koa-like middlewares to asynchronously fetch HTTP RESTful resources, worker communication or synchronously access localStorage.
Welcome to extend or hack Reget or other classes to change behaviours
Table of Contents
- Http get, put, post for react component
- Setup
- Comparison
- Server Rendering
- Use Reget alone
- CacheStore class methods
- Reget class
- Middlewares
- SyncPromise
Http get, put, post for react component
{ return username} { // assume you have setup middleware to fetch HTTP const user = reget // first get will be undefined // after HTTP response and cached, connectReget will be re-run // so, second get will get user return user: user // you can return null to stop child component rendering}PureComponent
Setup
// create reget cache and assign it with middlewaresconst reget = // create koa-like middlewares handler: // Assign to your React context<RegetProvider reget=reget> <MyApp /></RegetProvider>
Comparison
Compare to Flux/Redux
- Built-in support for async, http, promise call
- Designed for big state tree. Cached state will be garbage collected
- No need to define constants (you can define url generate functions)
Compare to Relay/Falcor
- Can call any http endpoint (Restful or php page or even image)
- Flexible code your middleware, data conversion and normalization in js side
Server Rendering
reget // transfer data to clientconst json = JSON// -------const isoData = JSON // client sideconst browserReget = // handler()browserRegetReactDOM
You can use iso to ship data to browser
Use Reget alone
Reget can be a
const reget = handler: regetreget === 'bar'
API
reget will create a CallContext instance and pass down to middlewares
CallContext fields, getters and setters
// ctx fieldsreget: Object // caller reget object. Middleware is valid to call middlewares stack again, (prevent recursive problem on your own).cache: Object // reget's cache. middleware can use this to safely put data into cache // request related fieldsmethod: 'GET' // default 'GET'url: '/' // url with query string, default '/'path: '/' // url without query string, default '/'ifModifiedSince: null // default nullheaders: null // default undefinedinput: null // request body or data, default null // response related fieldsstatus: 404 // http-like response status getter and setter, default 404)body: null // http-like response body getter and setter, default null) {} // get normalized header {} // set header
CacheStore class methods
// sync get cache // sync set cache, trigger watchers to re-run in next tick. // invalidate cache // register a watcher for change on key // unregister a watcher for change on key // get pending change promise (or null), so you can wait for // gc this cache store
Reget class
cache // this instance's CacheStore // assigned handler function for request (GET, PUT, POST), can be created by ```compose``` module // http get (Sync) // http put (Async/Promise) // http post (Async/Promise) // http get (Async/Promise) // http request (Async/Promise) // get promise for all loading calls or one cache, null when promise not found // wait for all pending requests and events // If !key, entire store will be returned // If key is object, key&value will be import to this cache store.
Middlewares
koa like middlewares system. Please refer to path-to-regexp for path pattern.
const handler = const ctx = path: 'foo/hi'await // ctx.body === 'Hello World'
Middleware API
compose(...middlewares) create a function that accept a context argument and pass down to all middlewares
middlewares can be one of
- function(ctx, next){}
- array of function(ctx, next){}
- object: {route: 'pathPattern', get(){}, put(){}, post(){}, watch(){}, unwatch(){}}
- object: {mount: 'prefix', handler: anotherMiddleware}
- mount('prefix', anotherMiddleware)
like koa-route, path pattern use path-to-regexp to build regexp
Middleware Example
browserMiddleware = route: '/:key' { if key === 'height' || key === 'width' window { const changes = // mountPath = 'browser' if you use mount('browser', browserMiddleware) `/height`: windowinnerHeight `/width`: windowinnerWidth reget } window } { const key = ctxparams if key === 'height' || key === 'width' windowonresize = null } { // just use the cached value ctxstatus = 304 } { // cannot put ctxstatus = 404 }
SyncPromise
SyncPromise can wrap a value into a Promise like object. Why? because normal Promise .then is not sync
let value = null Promise// value !== 'A' // But SyncPromise// value === 'A'