@laconia/core
Advanced tools
Comparing version 0.6.0 to 0.7.0
{ | ||
"name": "@laconia/core", | ||
"version": "0.6.0", | ||
"version": "0.7.0", | ||
"description": "Micro dependency injection framework", | ||
@@ -5,0 +5,0 @@ "keywords": [ |
@@ -27,3 +27,5 @@ # @laconia/core | ||
* Dependency injection | ||
* Reduce boilerplate code that is needed to avoid common Lambda programming error | ||
* Caching for heavy instance creation | ||
* Reduce boilerplate code | ||
* Avoid common Lambda programming error | ||
@@ -131,2 +133,9 @@ One of the problem in AWS Lambda is the `UnhandledPromiseRejectionWarning` problem where | ||
#### Cache | ||
When `#register` is called, all of the instances returned by the function specified will be | ||
cached by default and will expire every 5 minutes. It is therefore a good practice to offload | ||
some of the heavy operations that don't change on every Lambda run to `LaconiaContext`. | ||
This feature can be turned off, see API section. | ||
### API | ||
@@ -150,3 +159,3 @@ | ||
#### `register(instanceFn)` | ||
#### `register(factoryFn, options)` | ||
@@ -156,5 +165,11 @@ Registers objects into LaconiaContext. Objects registered here will be made | ||
* `instanceFn(laconiaContext)` | ||
* `factoryFn(laconiaContext)` | ||
* This `Function` is called when your Lambda is invoked | ||
* An object which contains the instances to be registered must be returned | ||
* `options`: | ||
* `cache` | ||
* `enabled = true` | ||
* Set to false to turn off caching | ||
* `maxAge = 300000` | ||
* Your factoryFn will be called when the cache has reached its maximum age specified by this option | ||
@@ -168,2 +183,17 @@ Example: | ||
})); | ||
// Reduce maxAge | ||
const handler = () => {}; | ||
laconia(handler).register( | ||
async () => ( | ||
{ | ||
/* heavy operations */ | ||
}, | ||
{ | ||
cache: { | ||
maxAge: 1000 | ||
} | ||
} | ||
) | ||
); | ||
``` | ||
@@ -170,0 +200,0 @@ |
const LaconiaContext = require("./LaconiaContext"); | ||
const SingleCache = require("./SingleCache"); | ||
const cacheResult = (fn, maxAge) => { | ||
const cache = new SingleCache(maxAge); | ||
return async (...args) => { | ||
if (cache.isEmpty() || cache.hasExpired()) { | ||
cache.set(await fn(...args)); | ||
} | ||
return cache.get(); | ||
}; | ||
}; | ||
module.exports = class CoreLaconiaContext extends LaconiaContext { | ||
@@ -12,2 +24,6 @@ constructor(baseContext) { | ||
} | ||
registerFactory(factory, { enabled = true, maxAge = 300000 } = {}) { | ||
super.registerFactory(enabled ? cacheResult(factory, maxAge) : factory); | ||
} | ||
}; |
@@ -22,4 +22,4 @@ const CoreLaconiaContext = require("./CoreLaconiaContext"); | ||
}, | ||
register: factoryFn => { | ||
laconiaContext.registerFactory(factoryFn); | ||
register: (factoryFn, options = {}) => { | ||
laconiaContext.registerFactory(factoryFn, options.cache); | ||
return laconia; | ||
@@ -26,0 +26,0 @@ } |
11658
8
130
216