Learn about our RFC process, Open RFC meetings & more.Join in the discussion! »

@rill/loader

2.2.1 • Public • Published

Rill
@rill/loader
API stability Standard NPM version Downloads Gitter Chat

Utility to handle cached data loading in Rill.

Installation

npm install @rill/loader

Example

Load the data in middleware.

const app = require('rill')()
const loader = require('@rill/loader')
 
app.use(loader())
app.get('/my-view',
    (ctx, next)=> {
        // A #load function will be attached to the context.
        return ctx.load('myStuff', ...).then((myStuff)=> {
            // Loaded data cached automatically attached to ctx.locals
            ctx.locals.myStuff; //-> 'data'
        })
    }
)

Register a data loader.

const loader = require('@rill/loader')
 
// Register a loadable item.
loader.register(
    { name: 'myStuff', ttl: '30 minutes' },
    (ctx, ...)=> {
        // Return any promise of data and it will be cached.
        return myApi.fetchMyStuff();
    }
);

API

ctx.load(name:String, arguments...)

Requests data from a registered loader and returns cached data if possible. name is the name of the loader and arguments are provided to the loader.

loader.register(opts:Object, getter:Function)

Registers a getter function with the loader. This function will be cached and automatically set it's data on ctx.locals when loaded.

Register Options

{
    // The name where the data will be stored on `ctx.locals`.
    name: "myStuff",
 
    // A timeout (in milliseconds or as a string) that the data will deleted in.
    ttl: 3000,
 
    // If true the `ttl` option will be reset every time the data is loaded.
    refresh: false,
 
    // If shared is set the true then a global cache will be used on the server side. (By default is uses the users session).
    shared: false
}

Contributions

  • Use npm test to run tests.

Please feel free to create a PR!

Install

npm i @rill/loader

DownloadsWeekly Downloads

1

Version

2.2.1

License

MIT

Last publish

Collaborators

  • avatar