🚀. Socket Launch Week Day 2:Introducing Manifest Alerts.Learn more
Sign In

adonis-cache

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

adonis-cache - npm Package Compare versions

Comparing version
0.2.1
to
0.3.0
+101
commands/ConfigGenerator.js
'use strict'
/**
* adonis-cache
*
* (c) Hany El Nokaly <hany.elnokaly@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const path = require('path')
const { Command } = require('@adonisjs/ace')
/**
* Command to generate a cache config file
*
* @class ConfigGenerator
* @constructor
*/
class ConfigGenerator extends Command {
constructor (Helpers) {
super()
this.Helpers = Helpers
}
/**
* IoC container injections
*
* @method inject
*
* @return {Array}
*/
static get inject () {
return ['Adonis/Src/Helpers']
}
/**
* The command signature
*
* @method signature
*
* @return {String}
*/
static get signature () {
return 'cache:config'
}
/**
* The command description
*
* @method description
*
* @return {String}
*/
static get description () {
return 'Generate cache config file'
}
/**
* Method called when command is executed
*
* @method handle
*
* @param {Object} options
* @return {void}
*/
async handle (options) {
/**
* Reading template as a string form the mustache file
*/
const template = await this.readFile(path.join(__dirname, './templates/config.mustache'), 'utf8')
/**
* Directory paths
*/
const relativePath = path.join('config', 'cache.js')
const configPath = path.join(this.Helpers.appRoot(), relativePath)
/**
* If command is not executed via command line, then return
* the response
*/
if (!this.viaAce) {
return this.generateFile(configPath, template, {})
}
/**
* Otherwise wrap in try/catch and show appropriate messages
* to the end user.
*/
try {
await this.generateFile(configPath, template, {})
this.completed('create', relativePath)
} catch (error) {
this.error(`${relativePath} cache config file already exists`)
}
}
}
module.exports = ConfigGenerator
'use strict'
/**
* adonis-cache
*
* (c) Hany El Nokaly <hany.elnokaly@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const path = require('path')
const { Command } = require('@adonisjs/ace')
/**
* Command to generate a migration for the cache database table
*
* @class TableGenerator
* @constructor
*/
class TableGenerator extends Command {
constructor(Helpers) {
super()
this.Helpers = Helpers
}
/**
* IoC container injections
*
* @method inject
*
* @return {Array}
*/
static get inject() {
return ['Adonis/Src/Helpers']
}
/**
* The command signature
*
* @method signature
*
* @return {String}
*/
static get signature() {
return 'cache:table'
}
/**
* The command description
*
* @method description
*
* @return {String}
*/
static get description() {
return 'Generate a migration for the cache database table'
}
/**
* Method called when command is executed
*
* @method handle
*
* @param {Object} options
* @return {void}
*/
async handle(options) {
/**
* Reading template as a string form the mustache file
*/
const template = await this.readFile(path.join(__dirname, './templates/table.mustache'), 'utf8')
/**
* Directory paths
*/
const relativePath = path.join('database/migrations', `${new Date().getTime()}_create_cache_table.js`)
const fullPath = path.join(this.Helpers.appRoot(), relativePath)
/**
* If command is not executed via command line, then return
* the response
*/
if (!this.viaAce) {
return this.generateFile(fullPath, template, {})
}
/**
* Otherwise wrap in try/catch and show appropriate messages
* to the end user.
*/
try {
await this.generateFile(fullPath, template, {})
this.completed('create', relativePath)
} catch (error) {
this.error(`${relativePath} file already exists`)
}
}
}
module.exports = TableGenerator
'use strict'
const Env = use('Env')
const Helpers = use('Helpers')
module.exports = {
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that gets used while
| using this caching library. This store is used when another is
| not explicitly specified when executing a given caching function.
|
*/
default: Env.get('CACHE_STORE', 'object'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "object", "database", "redis"
| Hint: Use "null" driver for disabling caching
|
*/
stores: {
object: {
driver: 'object'
},
database: {
driver: 'database',
table: 'cache',
connection: 'default'
},
redis: {
driver: 'redis',
connection: 'default'
},
null: {
driver: 'null'
}
},
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store, there might be other applications
| utilizing the same cache. So, we'll specify a value to get prefixed
| to all our keys so we can avoid collisions.
|
*/
prefix: 'adonis'
}
'use strict'
const Schema = use('Schema')
class CreateCacheTable extends Schema {
/**
* Run the migrations.
*
* @return {void}
*/
up () {
this.create('cache', (table) => {
table.string('key').unique()
table.text('value')
table.integer('expiration')
})
}
/**
* Reverse the migrations/
*
* @return {void}
*/
down () {
this.drop('cache')
}
}
module.exports = CreateCacheTable
+10
-12
{
"name": "adonis-cache",
"version": "0.2.1",
"version": "0.3.0",
"description": "Cache provider for AdonisJs framework",

@@ -23,15 +23,13 @@ "scripts": {

"devDependencies": {
"adonis-ace": "^3.0.4",
"adonis-fold": "^3.0.3",
"chai": "^3.5.0",
"co-mocha": "^1.1.3",
"ioredis": "^2.4.0",
"knex": "^0.12.2",
"mocha": "^3.1.0",
"sqlite3": "^3.1.4",
"standard": "^8.3.0"
"@adonisjs/ace": "^4.0.5",
"@adonisjs/fold": "^4.0.2",
"chai": "^4.1.2",
"ioredis": "^3.2.2",
"knex": "^0.14.2",
"mocha": "^4.0.1",
"sqlite3": "^3.1.8",
"standard": "^10.0.3"
},
"dependencies": {
"co": "^4.6.0",
"lodash": "^4.16.2"
"lodash": "^4.17.4"
},

@@ -38,0 +36,0 @@ "standard": {

@@ -12,8 +12,15 @@ 'use strict'

const ServiceProvider = require('adonis-fold').ServiceProvider
const { ServiceProvider } = require('@adonisjs/fold')
const CacheManager = require('../src/Stores/CacheManager')
class CacheProvider extends ServiceProvider {
* register () {
this.app.singleton('Adonis/Addons/Cache', function (app) {
/**
* Register all the required providers
*
* @method register
*
* @return {void}
*/
register () {
this.app.singleton('Adonis/Addons/Cache', (app) => {
return new CacheManager(app)

@@ -20,0 +27,0 @@ })

@@ -12,18 +12,31 @@ 'use strict'

const ServiceProvider = require('adonis-fold').ServiceProvider
const { ServiceProvider } = require('@adonisjs/fold')
class CommandsProvider extends ServiceProvider {
/**
* Register all the required providers
*
* @method register
*
* @return {void}
*/
register () {
this.app.bind('Adonis/Commands/Cache:Config', () => require('../commands/ConfigGenerator'))
this.app.bind('Adonis/Commands/Cache:Table', () => require('../commands/TableGenerator'))
}
* register () {
this.app.bind(`Adonis/Commands/Cache:Table`, (app) => {
const Helpers = app.use('Adonis/Src/Helpers')
const Generator = require(`../src/Commands/TableGenerator`)
return new Generator(Helpers)
})
this.app.bind(`Adonis/Commands/Cache:Config`, (app) => {
const Helpers = app.use('Adonis/Src/Helpers')
const Generator = require(`../src/Commands/ConfigGenerator`)
return new Generator(Helpers)
})
/**
* On boot
*
* @method boot
*
* @return {void}
*/
boot () {
/**
* Register command with ace.
*/
const ace = require('@adonisjs/ace')
ace.addCommand('Adonis/Commands/Cache:Config')
ace.addCommand('Adonis/Commands/Cache:Table')
}

@@ -30,0 +43,0 @@ }

+39
-45

@@ -26,5 +26,5 @@ # AdonisCache

After installation, you need to register the providers inside `bootstrap/app.js` file.
After installation, you need to register the providers inside `start/app.js` file.
##### bootstrap/app.js
##### start/app.js
```javascript

@@ -39,3 +39,3 @@ const providers = [

##### bootstrap/app.js
##### start/app.js
```javascript

@@ -46,8 +46,2 @@ const aceProviders = [

]
const commands = [
...,
'Adonis/Commands/Cache:Table',
'Adonis/Commands/Cache:Config'
]
```

@@ -57,3 +51,3 @@

##### bootstrap/app.js
##### start/app.js
```javascript

@@ -92,9 +86,9 @@ const aliases = {

> {tip} You may also use the `./ace cache:table` Ace command to generate a migration with the proper schema.
> {tip} You may also use the `adonis cache:table` Ace command to generate a migration with the proper schema.
#### Redis
Before using a Redis cache, you will need to install the `adonis-redis` package via npm.
Before using a Redis cache, you will need to have the Redis provider installed.
For more information on configuring Redis, consult its [AdonisJs documentation page](http://www.adonisjs.com/docs/3.0/redis).
For more information on configuring Redis, consult its [AdonisJs documentation page](http://adonisjs.com/docs/redis).

@@ -114,4 +108,4 @@ <a name="cache-usage"></a>

* index(request, response) {
const value = yield Cache.get('key')
async index(request, response) {
const value = await Cache.get('key')

@@ -128,5 +122,5 @@ //

```javascript
value = yield Cache.store('database').get('foo')
value = await Cache.store('database').get('foo')
yield Cache.store('redis').put('bar', 'baz', 10)
await Cache.store('redis').put('bar', 'baz', 10)
```

@@ -139,5 +133,5 @@ <a name="retrieving-items-from-the-cache"></a>

```javascript
value = yield Cache.get('key')
value = await Cache.get('key')
value = yield Cache.get('key', 'default')
value = await Cache.get('key', 'default')
```

@@ -148,5 +142,5 @@

```javascript
value = yield Cache.get('key', function * () {
return yield Database.table(...).where(...).first()
});
value = await Cache.get('key', async () => {
return await Database.table(...).where(...).first()
})
```

@@ -157,3 +151,3 @@

```javascript
values = yield Cache.many(['key1', 'key2', 'key3'])
values = await Cache.many(['key1', 'key2', 'key3'])
// values = {

@@ -171,3 +165,3 @@ // key1: value,

```javascript
if (yield Cache.has('key')) {
if (await Cache.has('key')) {
//

@@ -182,6 +176,6 @@ }

```javascript
yield Cache.increment('key')
yield Cache.increment('key', amount)
yield Cache.decrement('key')
yield Cache.decrement('key', amount)
await Cache.increment('key')
await Cache.increment('key', amount)
await Cache.decrement('key')
await Cache.decrement('key', amount)
```

@@ -194,4 +188,4 @@

```javascript
value = yield Cache.remember('key', minutes, function * () {
return yield Database.table(...).where(...).first()
value = await Cache.remember('key', minutes, async () => {
return await Database.table(...).where(...).first()
})

@@ -207,3 +201,3 @@ ```

```javascript
value = yield Cache.pull('key')
value = await Cache.pull('key')
```

@@ -217,3 +211,3 @@

```javascript
yield Cache.put('key', 'value', minutes);
await Cache.put('key', 'value', minutes)
```

@@ -226,3 +220,3 @@

yield Cache.put('key', 'value', expiresAt)
await Cache.put('key', 'value', expiresAt)
```

@@ -239,3 +233,3 @@

yield Cache.putMany(items, minutes)
await Cache.putMany(items, minutes)
```

@@ -248,3 +242,3 @@

```javascript
yield Cache.add('key', 'value', minutes)
await Cache.add('key', 'value', minutes)
```

@@ -257,3 +251,3 @@

```javascript
yield Cache.forever('key', 'value')
await Cache.forever('key', 'value')
```

@@ -267,3 +261,3 @@

```javascript
yield Cache.forget('key')
await Cache.forget('key')
```

@@ -274,3 +268,3 @@

```javascript
yield Cache.flush()
await Cache.flush()
```

@@ -291,5 +285,5 @@

```javascript
yield Cache.tags(['people', 'artists']).put('John', john, minutes)
await Cache.tags(['people', 'artists']).put('John', john, minutes)
yield Cache.tags(['people', 'authors']).put('Anne', anne, minutes)
await Cache.tags(['people', 'authors']).put('Anne', anne, minutes)
```

@@ -303,5 +297,5 @@

```javascript
const john = yield Cache.tags(['people', 'artists']).get('John')
const john = await Cache.tags(['people', 'artists']).get('John')
const anne = yield Cache.tags(['people', 'authors']).get('Anne')
const anne = await Cache.tags(['people', 'authors']).get('Anne')
```

@@ -315,3 +309,3 @@

```javascript
yield Cache.tags(['people', 'authors']).flush()
await Cache.tags(['people', 'authors']).flush()
```

@@ -322,3 +316,3 @@

```javascript
yield Cache.tags('authors').flush()
await Cache.tags('authors').flush()
```

@@ -329,3 +323,3 @@

To execute code on every cache operation, you may listen for the [events](http://www.adonisjs.com/docs/3.0/events) fired by the cache. Typically, you should place these event listeners within your `bootstrap/events.js`:
To execute code on every cache operation, you may listen for the [events](http://adonisjs.com/docs/events) fired by the cache. Typically, you should place these event listeners within your `start/events.js`:

@@ -332,0 +326,0 @@ ```

@@ -19,3 +19,2 @@ 'use strict'

class CacheManager {
constructor (app) {

@@ -47,4 +46,5 @@ this._app = app // The application instance

store (name = null) {
name = name ? name : this.getDefaultDriver()
return this._stores[name] = this._get(name)
name = name || this.getDefaultDriver()
this._stores[name] = this._get(name)
return this._stores[name]
}

@@ -51,0 +51,0 @@

@@ -12,7 +12,5 @@ 'use strict'

const co = require('co')
const Util = require('../Util')
class DatabaseStore {
constructor (connection, tableName, prefix = '') {

@@ -40,17 +38,15 @@ this._connection = connection

*/
get (key) {
return co(function * () {
const cache = yield this._table().where('key', this._prefix + key).first()
async get (key) {
const cache = await this._table().where('key', this._prefix + key).first()
if (cache === undefined) {
return null
}
if (cache === undefined) {
return null
}
if (Date.now() / 1000 >= cache.expiration) {
yield this.forget(key)
return null
}
if (Date.now() / 1000 >= cache.expiration) {
await this.forget(key)
return null
}
return Util.deserialize(cache.value)
}.bind(this))
return Util.deserialize(cache.value)
}

@@ -66,10 +62,9 @@

*/
many (keys) {
return co(function * () {
let mappedValues = {}
for (let key of keys) {
mappedValues[key] = this.get(key)
}
return yield mappedValues
}.bind(this))
async many (keys) {
let values = await Promise.all(keys.map(key => this.get(key)))
let mappedValues = {}
for (let i = 0; i < keys.length; i++) {
mappedValues[keys[i]] = values[i]
}
return mappedValues
}

@@ -85,14 +80,12 @@

*/
put (key, value, minutes = 0) {
return co(function * () {
const prefixedKey = this._prefix + key
const serializedValue = Util.serialize(value)
const expiration = Math.floor((Date.now() / 1000) + minutes * 60)
async put (key, value, minutes = 0) {
const prefixedKey = this._prefix + key
const serializedValue = Util.serialize(value)
const expiration = Math.floor((Date.now() / 1000) + minutes * 60)
try {
yield this._table().insert({key: prefixedKey, value: serializedValue, expiration: expiration})
} catch (e) {
yield this._table().where('key', prefixedKey).update({value: serializedValue, expiration: expiration})
}
}.bind(this))
try {
await this._table().insert({key: prefixedKey, value: serializedValue, expiration: expiration})
} catch (e) {
await this._table().where('key', prefixedKey).update({value: serializedValue, expiration: expiration})
}
}

@@ -107,8 +100,8 @@

*/
putMany (object, minutes) {
return co(function * () {
for (let prop in object) {
yield this.put(prop, object[prop], minutes)
}
}.bind(this))
async putMany (object, minutes) {
let operations = []
for (let prop in object) {
operations.push(this.put(prop, object[prop], minutes))
}
await Promise.all(operations)
}

@@ -167,3 +160,3 @@

}
const newValue = Util.serialize(callback(currentValue))
const newValue = callback(currentValue)
return trx.table(this._tableName).where('key', prefixedKey).update('value', newValue)

@@ -194,7 +187,5 @@ .then(r => resolve(newValue))

*/
forget (key) {
return co(function * () {
yield this._table().where('key', this._prefix + key).delete()
return true
}.bind(this))
async forget (key) {
await this._table().where('key', this._prefix + key).delete()
return true
}

@@ -207,6 +198,4 @@

*/
flush () {
return co(function * () {
yield this._table().delete()
}.bind(this))
async flush () {
await this._table().delete()
}

@@ -231,5 +220,4 @@

}
}
module.exports = DatabaseStore

@@ -15,3 +15,2 @@ 'use strict'

class NullStore extends TaggableStore {
/**

@@ -23,4 +22,4 @@ * Retrieve an item from the cache by key.

*/
get (key) {
return Promise.resolve(null)
async get (key) {
return null
}

@@ -36,3 +35,3 @@

*/
many (keys) {
async many (keys) {
let mappedValues = {}

@@ -42,3 +41,3 @@ for (let key of keys) {

}
return Promise.resolve(mappedValues)
return mappedValues
}

@@ -54,4 +53,4 @@

*/
put (key, value, minutes) {
return Promise.resolve(undefined)
async put (key, value, minutes) {
return undefined
}

@@ -66,4 +65,4 @@

*/
putMany (object, minutes) {
return Promise.resolve(undefined)
async putMany (object, minutes) {
return undefined
}

@@ -78,4 +77,4 @@

*/
increment (key, value = 1) {
return Promise.resolve(false)
async increment (key, value = 1) {
return false
}

@@ -90,4 +89,4 @@

*/
decrement (key, value = 1) {
return Promise.resolve(false)
async decrement (key, value = 1) {
return false
}

@@ -102,4 +101,4 @@

*/
forever (key, value) {
return Promise.resolve(undefined)
async forever (key, value) {
return undefined
}

@@ -113,4 +112,4 @@

*/
forget (key) {
return Promise.resolve(true)
async forget (key) {
return true
}

@@ -123,4 +122,4 @@

*/
flush () {
return Promise.resolve(undefined)
async flush () {
return undefined
}

@@ -127,0 +126,0 @@

@@ -16,3 +16,2 @@ 'use strict'

class ObjectStore extends TaggableStore {
constructor () {

@@ -29,16 +28,12 @@ super()

*/
get (key) {
return new Promise((resolve, reject) => {
const cache = this._storage[key]
if (cache === undefined) {
resolve(null)
return
}
if (Date.now() / 1000 >= cache.expiration) {
this.forget(key)
resolve(null)
return
}
resolve(Util.deserialize(cache.value))
})
async get (key) {
const cache = this._storage[key]
if (cache === undefined) {
return null
}
if (Date.now() / 1000 >= cache.expiration) {
this.forget(key)
return null
}
return Util.deserialize(cache.value)
}

@@ -148,3 +143,3 @@

}
const newValue = Util.serialize(callback(currentValue))
const newValue = callback(currentValue)
this._storage[key].value = newValue

@@ -172,7 +167,5 @@ resolve(newValue)

*/
forget (key) {
return new Promise((resolve, reject) => {
delete this._storage[key]
resolve(true)
})
async forget (key) {
delete this._storage[key]
return true
}

@@ -179,0 +172,0 @@

@@ -13,3 +13,2 @@ 'use strict'

const _ = require('lodash')
const co = require('co')
const TaggableStore = require('./TaggableStore')

@@ -21,3 +20,2 @@ const Util = require('../Util')

class RedisStore extends TaggableStore {
constructor (Redis, prefix = '', connection = 'default') {

@@ -37,6 +35,4 @@ super()

*/
get (key) {
return co(function * () {
return Util.deserialize(yield this.connection().get(this._prefix + key))
}.bind(this))
async get (key) {
return Util.deserialize(await this.connection().get(this._prefix + key))
}

@@ -52,10 +48,9 @@

*/
many (keys) {
return co(function * () {
let mappedValues = {}
for (let i = 0; i < keys.length; i++) {
mappedValues[keys[i]] = this.get(keys[i])
}
return yield mappedValues
}.bind(this))
async many (keys) {
let values = await Promise.all(keys.map(key => this.get(key)))
let mappedValues = {}
for (let i = 0; i < keys.length; i++) {
mappedValues[keys[i]] = values[i]
}
return mappedValues
}

@@ -71,14 +66,12 @@

*/
put (key, value, minutes = 0) {
return co(function * () {
const prefixedKey = this._prefix + key
let expiration = Math.floor(minutes * 60)
const serializedValue = Util.serialize(value)
async put (key, value, minutes = 0) {
const prefixedKey = this._prefix + key
let expiration = Math.floor(minutes * 60)
const serializedValue = Util.serialize(value)
if (isNaN(expiration) || expiration < 1) {
expiration = 1
}
if (isNaN(expiration) || expiration < 1) {
expiration = 1
}
yield this.connection().setex(prefixedKey, expiration, serializedValue)
}.bind(this))
await this.connection().setex(prefixedKey, expiration, serializedValue)
}

@@ -93,8 +86,6 @@

*/
putMany (object, minutes) {
return co(function * () {
for (let prop in object) {
yield this.put(prop, object[prop], minutes)
}
}.bind(this))
async putMany (object, minutes) {
for (let prop in object) {
await this.put(prop, object[prop], minutes)
}
}

@@ -109,14 +100,12 @@

*/
increment (key, value = 1) {
return co(function * () {
try {
return yield this.connection().incrby(this._prefix + key, value)
} catch (error) {
if (error.name === 'ReplyError') {
return false
} else {
throw error
}
async increment (key, value = 1) {
try {
return await this.connection().incrby(this._prefix + key, value)
} catch (error) {
if (error.name === 'ReplyError') {
return false
} else {
throw error
}
}.bind(this))
}
}

@@ -131,14 +120,12 @@

*/
decrement (key, value = 1) {
return co(function * () {
try {
return yield this.connection().decrby(this._prefix + key, value)
} catch (error) {
if (error.name === 'ReplyError') {
return false
} else {
throw error
}
async decrement (key, value = 1) {
try {
return await this.connection().decrby(this._prefix + key, value)
} catch (error) {
if (error.name === 'ReplyError') {
return false
} else {
throw error
}
}.bind(this))
}
}

@@ -153,6 +140,4 @@

*/
forever (key, value) {
return co(function * () {
yield this.connection().set(this._prefix + key, Util.serialize(value))
}.bind(this))
async forever (key, value) {
await this.connection().set(this._prefix + key, Util.serialize(value))
}

@@ -166,7 +151,5 @@

*/
forget (key) {
return co(function * () {
yield this.connection().del(this._prefix + key)
return true
}.bind(this))
async forget (key) {
await this.connection().del(this._prefix + key)
return true
}

@@ -179,6 +162,4 @@

*/
flush () {
return co(function * () {
yield this.connection().flushdb()
}.bind(this))
async flush () {
await this.connection().flushdb()
}

@@ -244,5 +225,4 @@

}
}
module.exports = RedisStore

@@ -15,6 +15,4 @@ 'use strict'

const _ = require('lodash')
const co = require('co')
class RedisTaggedCache extends TaggedCache {
/**

@@ -28,14 +26,5 @@ * Store an item in the cache.

*/
put (key, value, minutes = null) {
// return co(function * () {
// yield this._pushStandardKeys(yield this._tags.getNamespace(), key)
// yield super.put(key, value, minutes)
// }.bind(this))
return new Promise((resolve, reject) => {
this._tags.getNamespace()
.then(namespace => this._pushStandardKeys(namespace, key))
.then(r => super.put(key, value, minutes))
.then(r => resolve())
.catch(e => reject(e))
})
async put (key, value, minutes = null) {
await this._pushStandardKeys(await this._tags.getNamespace(), key)
await super.put(key, value, minutes)
}

@@ -50,14 +39,5 @@

*/
forever (key, value) {
// return co(function * () {
// yield this._pushForeverKeys(yield this._tags.getNamespace(), key)
// yield super.forever(key, value)
// }.bind(this))
return new Promise((resolve, reject) => {
this._tags.getNamespace()
.then(namespace => this._pushForeverKeys(namespace, key))
.then(r => super.forever(key, value))
.then(r => resolve())
.catch(e => reject(e))
})
async forever (key, value) {
await this._pushForeverKeys(await this._tags.getNamespace(), key)
await super.forever(key, value)
}

@@ -70,15 +50,6 @@

*/
flush () {
// return co(function * () {
// yield this._deleteForeverKeys()
// yield this._deleteStandardKeys()
// yield super.flush()
// }.bind(this))
return new Promise((resolve, reject) => {
this._deleteForeverKeys()
.then(r => this._deleteStandardKeys())
.then(r => super.flush())
.then(r => resolve())
.catch(e => reject(e))
})
async flush () {
await this._deleteForeverKeys()
await this._deleteStandardKeys()
await super.flush()
}

@@ -122,9 +93,7 @@

*/
_pushKeys (namespace, key, reference) {
return co(function * () {
const fullKey = this._store.getPrefix() + crypto.createHash('sha1').update(namespace).digest('hex') + ':' + key
for (let segment of namespace.split('|')) {
yield this._store.connection().sadd(this._referenceKey(segment, reference), fullKey)
}
}.bind(this))
async _pushKeys (namespace, key, reference) {
const fullKey = this._store.getPrefix() + crypto.createHash('sha1').update(namespace).digest('hex') + ':' + key
for (let segment of namespace.split('|')) {
await this._store.connection().sadd(this._referenceKey(segment, reference), fullKey)
}
}

@@ -162,9 +131,7 @@

*/
_deleteKeysByReference (reference) {
return co(function * () {
for (let segment of yield this._tags.getNamespace()) {
yield this._deleteValues(segment = this._referenceKey(segment, reference))
yield this._store.connection().del(segment)
}
}.bind(this))
async _deleteKeysByReference (reference) {
for (let segment of await this._tags.getNamespace()) {
await this._deleteValues(segment = this._referenceKey(segment, reference))
await this._store.connection().del(segment)
}
}

@@ -180,9 +147,7 @@

*/
_deleteValues (referenceKey) {
return co(function * () {
const values = _.uniq(yield this._store.connection().smembers(referenceKey))
for (let i = 0; i < values.length; i++) {
yield this._store.connection().del(values[i])
}
}.bind(this))
async _deleteValues (referenceKey) {
const values = _.uniq(await this._store.connection().smembers(referenceKey))
for (let i = 0; i < values.length; i++) {
await this._store.connection().del(values[i])
}
}

@@ -189,0 +154,0 @@

@@ -12,3 +12,2 @@ 'use strict'

const co = require('co')
const Util = require('../Util')

@@ -23,3 +22,2 @@

class Repository {
/**

@@ -100,6 +98,4 @@ * Create a new cache repository instance.

*/
has (key) {
return co(function * () {
return (yield this.get(key)) != null
}.bind(this))
async has (key) {
return (await this.get(key)) != null
}

@@ -114,16 +110,14 @@

*/
get (key, defaultValue = null) {
return co(function * () {
let value = yield this._store.get(yield this._itemKey(key))
async get (key, defaultValue = null) {
let value = await this._store.get(await this._itemKey(key))
if (value == null) {
this._fireCacheEvent('missed', [key])
if (value == null) {
this._fireCacheEvent('missed', [key])
return yield Util.valueOf(defaultValue)
} else {
this._fireCacheEvent('hit', [key, value])
}
return Util.valueOf(defaultValue)
} else {
this._fireCacheEvent('hit', [key, value])
}
return value
}.bind(this))
return value
}

@@ -139,14 +133,12 @@

*/
many (keys) {
return co(function * () {
const values = yield this._store.many(keys)
for (let key in values) {
if (values[key] == null) {
this._fireCacheEvent('missed', [key])
} else {
this._fireCacheEvent('hit', [key, values[key]])
}
async many (keys) {
const values = await this._store.many(keys)
for (let key in values) {
if (values[key] == null) {
this._fireCacheEvent('missed', [key])
} else {
this._fireCacheEvent('hit', [key, values[key]])
}
return values
}.bind(this))
}
return values
}

@@ -161,8 +153,6 @@

*/
pull (key, defaultValue = null) {
return co(function * () {
const value = yield this.get(key, defaultValue)
yield this.forget(key)
return value
}.bind(this))
async pull (key, defaultValue = null) {
const value = await this.get(key, defaultValue)
await this.forget(key)
return value
}

@@ -178,15 +168,13 @@

*/
put (key, value, minutes = null) {
return co(function * () {
if (value == null) {
return
}
async put (key, value, minutes = null) {
if (value == null) {
return
}
minutes = this._getMinutes(minutes)
minutes = this._getMinutes(minutes)
if (minutes != null) {
yield this._store.put(yield this._itemKey(key), value, minutes)
this._fireCacheEvent('write', [key, value, minutes])
}
}.bind(this))
if (minutes != null) {
await this._store.put(await this._itemKey(key), value, minutes)
this._fireCacheEvent('write', [key, value, minutes])
}
}

@@ -201,14 +189,12 @@

*/
putMany (values, minutes) {
return co(function * () {
minutes = this._getMinutes(minutes)
async putMany (values, minutes) {
minutes = this._getMinutes(minutes)
if (minutes != null) {
yield this._store.putMany(values, minutes)
if (minutes != null) {
await this._store.putMany(values, minutes)
for (let key in values) {
this._fireCacheEvent('write', [key, values[key], minutes])
}
for (let key in values) {
this._fireCacheEvent('write', [key, values[key], minutes])
}
}.bind(this))
}
}

@@ -224,21 +210,19 @@

*/
add (key, value, minutes) {
return co(function * () {
minutes = this._getMinutes(minutes)
async add (key, value, minutes) {
minutes = this._getMinutes(minutes)
if (minutes == null) {
return false
}
if (minutes == null) {
return false
}
if (typeof this._store['add'] === 'function') {
return yield this._store.add(yield this._itemKey(key), value, minutes)
}
if (typeof this._store['add'] === 'function') {
return this._store.add(await this._itemKey(key), value, minutes)
}
if ((yield this.get(key)) == null) {
yield this.put(key, value, minutes)
return true
}
if ((await this.get(key)) == null) {
await this.put(key, value, minutes)
return true
}
return false
}.bind(this))
return false
}

@@ -275,7 +259,5 @@

*/
forever (key, value) {
return co(function * () {
this._store.forever(yield this._itemKey(key), value)
this._fireCacheEvent('write', [key, value, 0])
}.bind(this))
async forever (key, value) {
this._store.forever(await this._itemKey(key), value)
this._fireCacheEvent('write', [key, value, 0])
}

@@ -291,16 +273,14 @@

*/
remember (key, minutes, closure) {
// If the item exists in the cache we will just return this immediately
// otherwise we will execute the given Closure and cache the result
// of that execution for the given number of minutes in storage.
return co(function * () {
let value = yield this.get(key)
if (value != null) {
return value
}
async remember (key, minutes, closure) {
// If the item exists in the cache we will just return this immediately
// otherwise we will execute the given Closure and cache the result
// of that execution for the given number of minutes in storage.
let value = await this.get(key)
if (value != null) {
return value
}
value = yield Util.valueOf(closure)
yield this.put(key, value, minutes)
return value
}.bind(this))
value = await Util.valueOf(closure)
await this.put(key, value, minutes)
return value
}

@@ -326,16 +306,14 @@

*/
rememberForever (key, closure) {
async rememberForever (key, closure) {
// If the item exists in the cache we will just return this immediately
// otherwise we will execute the given Closure and cache the result
// of that execution for the given number of minutes. It's easy.
return co(function * () {
let value = yield this.get(key)
if (value != null) {
return value
}
let value = await this.get(key)
if (value != null) {
return value
}
value = yield Util.valueOf(closure)
yield this.forever(key, value)
return value
}.bind(this))
value = await Util.valueOf(closure)
await this.forever(key, value)
return value
}

@@ -349,8 +327,6 @@

*/
forget (key) {
return co(function * () {
const success = yield this._store.forget(yield this._itemKey(key))
this._fireCacheEvent('delete', [key])
return success
}.bind(this))
async forget (key) {
const success = await this._store.forget(await this._itemKey(key))
this._fireCacheEvent('delete', [key])
return success
}

@@ -386,6 +362,4 @@

*/
_itemKey (key) {
return co(function * () {
return key
})
async _itemKey (key) {
return key
}

@@ -415,5 +389,4 @@

}
}
module.exports = Repository

@@ -17,3 +17,2 @@ 'use strict'

class TaggableStore {
/**

@@ -20,0 +19,0 @@ * Begin executing a new tags operation.

@@ -13,7 +13,5 @@ 'use strict'

const crypto = require('crypto')
const co = require('co')
const Repository = require('./Repository')
class TaggedCache extends Repository {
/**

@@ -46,6 +44,4 @@ * Create a new tagged cache instance.

*/
increment (key, value = 1) {
return co(function * () {
return yield this._store.increment(yield this._itemKey(key), value)
}.bind(this))
async increment (key, value = 1) {
return this._store.increment(await this._itemKey(key), value)
}

@@ -60,6 +56,4 @@

*/
decrement (key, value = 1) {
return co(function * () {
return yield this._store.decrement(yield this._itemKey(key), value)
}.bind(this))
async decrement (key, value = 1) {
return this._store.decrement(await this._itemKey(key), value)
}

@@ -89,6 +83,4 @@

*/
taggedItemKey (key) {
return co(function * () {
return crypto.createHash('sha1').update(yield this._tags.getNamespace()).digest('hex') + ':' + key
}.bind(this))
async taggedItemKey (key) {
return crypto.createHash('sha1').update(await this._tags.getNamespace()).digest('hex') + ':' + key
}

@@ -95,0 +87,0 @@ }

@@ -13,6 +13,4 @@ 'use strict'

const crypto = require('crypto')
const co = require('co')
class TagSet {
/**

@@ -35,8 +33,6 @@ * Create a new TagSet instance.

*/
reset () {
return co(function * () {
for (let name of this._names) {
yield this.resetTag(name)
}
}.bind(this))
async reset () {
for (let name of this._names) {
await this.resetTag(name)
}
}

@@ -50,7 +46,5 @@

*/
tagId (name) {
return co(function * () {
const id = yield this._store.get(this.tagKey(name))
return id ? id : yield this.resetTag(name)
}.bind(this))
async tagId (name) {
const id = await this._store.get(this.tagKey(name))
return id || this.resetTag(name)
}

@@ -64,6 +58,3 @@

_tagIds () {
return co(function * () {
const names = this._names.map(name => this.tagId(name))
return yield names
}.bind(this))
return Promise.all(this._names.map(name => this.tagId(name)))
}

@@ -76,6 +67,4 @@

*/
getNamespace () {
return co(function * () {
return (yield this._tagIds()).join('|')
}.bind(this))
async getNamespace () {
return (await this._tagIds()).join('|')
}

@@ -89,8 +78,6 @@

*/
resetTag (name) {
return co(function * () {
const id = crypto.randomBytes(8).toString('hex')
yield this._store.forever(this.tagKey(name), id)
return id
}.bind(this))
async resetTag (name) {
const id = crypto.randomBytes(8).toString('hex')
await this._store.forever(this.tagKey(name), id)
return id
}

@@ -97,0 +84,0 @@

@@ -12,4 +12,2 @@ 'use strict'

const co = require('co')
function serialize (data) {

@@ -23,20 +21,10 @@ return JSON.stringify(data)

function valueOf (value) {
return co(function * () {
if (value == null) {
return value
}
async function valueOf (value) {
if (typeof value === 'function') {
value = value()
}
if (typeof value === 'function') {
value = value()
}
if (typeof value === 'object') {
return yield value
}
return value
})
return value
}
module.exports = {serialize, deserialize, valueOf}

Sorry, the diff of this file is not supported yet

'use strict'
/**
* adonis-cache
*
* (c) Hany El Nokaly <hany.elnokaly@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const BaseGenerator = require('../../../adonis-commands/src/Generators/Base')
const path = require('path')
class TableGenerator extends BaseGenerator {
/**
* makes path to a given template
* @param {String} template
* @return {String}
*
* @private
*/
_makeTemplatePath (template) {
return path.join(__dirname, '../../templates', `${template}.mustache`)
}
/**
* returns signature to be used by ace
* @return {String}
*
* @public
*/
get signature () {
return `cache:config`
}
/**
* returns description to be used by ace as help command
* @return {String}
*
* @public
*/
get description () {
return 'Create a migration for the cache database table'
}
/**
* called by ace automatically. It will create a new
* config file inside the config directory.
* @param {Object} args
* @param {Object} options
*
* @public
*/
* handle (args, options) {
const toPath = this.helpers.configPath(`cache.js`)
const template = 'config'
const templateOptions = {}
yield this._wrapWrite(template, toPath, templateOptions)
}
}
module.exports = TableGenerator
'use strict'
/**
* adonis-cache
*
* (c) Hany El Nokaly <hany.elnokaly@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const BaseGenerator = require('../../../adonis-commands/src/Generators/Base')
const path = require('path')
class TableGenerator extends BaseGenerator {
/**
* makes path to a given template
* @param {String} template
* @return {String}
*
* @private
*/
_makeTemplatePath (template) {
return path.join(__dirname, '../../templates', `${template}.mustache`)
}
/**
* returns signature to be used by ace
* @return {String}
*
* @public
*/
get signature () {
return `cache:table`
}
/**
* returns description to be used by ace as help command
* @return {String}
*
* @public
*/
get description () {
return 'Create a migration for the cache database table'
}
/**
* called by ace automatically. It will create a new
* migrations file inside the migrations directory.
* @param {Object} args
* @param {Object} options
*
* @public
*/
* handle (args, options) {
const name = 'create_cache_table'
const toPath = this.helpers.migrationsPath(`${new Date().getTime()}_${name}.js`)
const template = 'table'
const templateOptions = {}
yield this._wrapWrite(template, toPath, templateOptions)
}
}
module.exports = TableGenerator
'use strict'
const Env = use('Env')
const Helpers = use('Helpers')
module.exports = {
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that gets used while
| using this caching library. This store is used when another is
| not explicitly specified when executing a given caching function.
|
*/
default: Env.get('CACHE_STORE', 'object'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "object", "database", "redis"
| Hint: Use "null" driver for disabling caching
|
*/
stores: {
object: {
driver: 'object'
},
database: {
driver: 'database',
table: 'cache',
connection: 'default'
},
redis: {
driver: 'redis',
connection: 'default'
},
null: {
driver: 'null'
}
},
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store, there might be other applications
| utilizing the same cache. So, we'll specify a value to get prefixed
| to all our keys so we can avoid collisions.
|
*/
prefix: 'adonis'
}
'use strict'
const Schema = use('Schema')
class CreateCacheTable extends Schema {
/**
* Run the migrations.
*
* @return {void}
*/
up () {
this.create('cache', (table) => {
table.string('key').unique()
table.text('value')
table.integer('expiration')
})
}
/**
* Reverse the migrations/
*
* @return {void}
*/
down () {
this.dropTableIfExists('cache')
}
}
module.exports = CreateCacheTable