Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ladda-cache

Package Overview
Dependencies
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ladda-cache - npm Package Compare versions

Comparing version 0.0.9 to 0.0.10

src/.tern-port

2

package.json
{
"name": "ladda-cache",
"version": "0.0.9",
"version": "0.0.10",
"description": "Data fetching layaer with support for caching",

@@ -5,0 +5,0 @@ "main": "dist/bundle.js",

@@ -5,27 +5,57 @@ # Ladda

# Background
When building a SPA, for example with React or Angular, you eventually need to have some kind of client side caching. You want stuff to be instant, but as the number of users increase the performance decline and your application's complexity increase because of all ad-hoc caching you start to add here and there. There are plenty of solutions out there, but typically they are very ambitious and pollute your application code with complexity. Ladda tries to keep things simple by moving data fetching, and especially caching, into a separate layer. **The goal is that you fetch your data everytime you want it**. Say that you have a user profile page which contains, really expensive to fetch, messages about the user. By far more than I should have, I have seen "if (inCache(...)) { ... } else { ... }". Gone are those sights. With Ladda you fetch your data everytime you want it. Either it comes from the cache or from a HTTP request. You don't have to care, you can just sit back and see the server load decline as well as your app magically become faster.
When building a SPA, for example with React or Angular, you eventually need to have some kind of client side caching. You want stuff to be instant, but as the number of users increase the performance decline and your application's complexity increase because of all ad-hoc caching you start to add here and there. There are plenty of solutions out there, but typically they are very ambitious and pollute your application code with complexity. Ladda tries to keep things simple by moving data fetching, and especially caching, into a separate layer. **The goal is that you fetch your data everytime you want it**. Say that you have a user profile page which contains, really expensive to fetch, messages about the user. By far more than I would have liked to, I have seen "if (inCache(...)) { ... } else { ... }". Gone are those sights. With Ladda you fetch your data everytime you want it. Either it comes from the cache or from a HTTP request. You don't have to care, you can just sit back and see the server load decline as well as your app magically become faster.
# What does this do
At its core this is just a registery of data fetching methods. You register a module and its methods becomes available, eg:
# Get Started
To use Ladda you need to configure it and export a API built from the configuration. You might create a file "api/index.js":
```javascript
const datastore = createDatastore();
const configure = compose(
registerMiddleware(caching(cacheConfig)),
registerApi('Github', Github),
registerApi('JsonPlaceholder', JsonPlaceholder)
);
import * as project from './project';
import { build } from 'ladda-cache';
const api = build(configure(datastore));
api.JsonPlaceholder.getAllPosts().then((posts) => console.log('posts', posts));
const config = {
projects: {
ttl: 300,
invalidates: ['projects', 'projectPreview'],
invalidatesOn: ['CREATE'],
api: project
}
};
export default build(config);
```
However, Ladda does support caching, which is what distinguish it
from just a bunch of fetch methods.
where project is a bunch of api-methods returning promises, eg:
# Code
Check out [/src/example](https://github.com/petercrona/ladda/blob/master/src/example/index.js) for a really simple example. This should quickly give you an idea of what this is about. The example API is defined in [/src/example/api/jsonplaceholder](https://github.com/petercrona/ladda/blob/master/src/example/api/jsonplaceholder.js) and the cache confing you find in [/src/example/cache-config.js](https://github.com/petercrona/ladda/blob/master/src/example/cache-config.js).
```javascript
createProject.operation = 'CREATE';
createProject.plural = false;
createProject.invalidates = ['getProjects(*)'];
export function createProject(project) {
return post(resource, { postData: project });
}
getProjects.operation = 'READ';
getProjects.plural = true;
export function getProjects(foo) {
return get(resource);
}
```
# Api Function Annotations
As you can see above we are adding information directly on the function object. Functions can be configured using:
* alwaysGetFreshData : <default: false> : Always fetch data and save in cache
* plural : <required> : Used when operation is set to READ. Informs Ladda that a list of multiple entities is expected.
* invalidates : <default: []> : Invalidates the query cache for the specified api function in the same type. If suffixed with (*) query cache regardless of query will be cleared. Otherwise only api function called without parameters.
* operation : <required> : CREATE | READ | UPDATE | DELETE - necessary for Ladda to handle caching correclty.
# Entity Config
For Ladda to work optimally you need to specify the relationship between entities and other caching settings.
* viewOf : null : Specifies that the current entity is a view of another entity. The super entity will influence the cache of the view and vice versa. Eg. if a UserPreview is a view of User, then updating a user's name calling User.updateName({ id, name }) will update UserPreview.name and vice versa.
* ttl : 300 : How long the cache is valid in seconds. After the number of seconds specified Ladda will pretend the cached entity don't exist.
* invalidates : [] : Other entities to invalidate on operations specified in "invalidatesOn"
* invalidatesOn : [CREATE] : Operations to invalidate on, where operations can be CREATE, READ, UPDATE, DELETE.
# Try it out
Clone the repo, go to the folder (/ladda) and run: *webpack-dev-server*.
Inspect the network traffic and play around with src/example/index.js.
Do a "npm install ladda-cache" in your project. Stay tuned for an example project.

@@ -124,2 +124,13 @@ // Concepts:

} else {
if (type.indexOf('(*)') !== -1) {
var allMatcher = getAllMatcher(type.substring(0, type.length - 3));
var candidates = Object.keys(datastore.entityCache || {});
var toInvalidate = candidates.filter(function (x) {
return allMatcher.test(x);
});
toInvalidate.forEach(function (key) {
delete datastore.entityCache[key];
});
datastore.queryCache[type.substring(0, type.length - 3)] = {};
}
datastore.queryCache[type] = {};

@@ -130,2 +141,6 @@ }

function getAllMatcher(type) {
return new RegExp('^' + type + '.*$');
}
function invalidateQueryCacheByFunction(datastore, type, method) {

@@ -132,0 +147,0 @@ const matcher = getMatcher(type, method);

@@ -34,3 +34,3 @@ import { createQuery } from 'query';

function getFromCache(apiFn, datastore, type, query) {
if (shouldUseQueryCache(apiFn.plural, apiFn.byId)) {
if (apiFn.plural) {
return getFromQueryCache(datastore, type, query, apiFn.name);

@@ -42,6 +42,2 @@ } else {

function shouldUseQueryCache(plural, byId) {
return plural === true || byId === false;
}
function getFromQueryCache(datastore, type, query, apiFnName) {

@@ -57,10 +53,9 @@ return getCollection(datastore, createQueryForCollection(type, query, apiFnName));

return data => {
if (shouldUseQueryCache(apiFn.plural, apiFn.byId)) {
[apiFn.name].concat(apiFn.cacheAliases || []).map((fnName) => {
addCollection(datastore,
createQueryForCollection(abstractEntity.name,
query,
fnName),
data);
});
if (apiFn.plural) {
const collectionQuery = createQueryForCollection(abstractEntity.name,
query,
apiFn.name);
addCollection(datastore,
collectionQuery,
data);
} else {

@@ -67,0 +62,0 @@ addItem(datastore, createQuery(abstractEntity.name, query), data);

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc