diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index ef486c9..0000000 --- a/.eslintrc.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": ["plugin:adonis/typescriptPackage", "prettier"], - "plugins": ["prettier"], - "rules": { - "prettier/prettier": [ - "error", - { - "endOfLine": "auto" - } - ] - } -} diff --git a/.prettierrc b/.prettierrc index 79064fa..792fef3 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,10 +1,10 @@ { - "trailingComma": "all", - "semi": false, - "singleQuote": true, - "useTabs": true, - "quoteProps": "consistent", - "bracketSpacing": true, - "arrowParens": "always", - "printWidth": 100 + "trailingComma": "all", + "semi": false, + "singleQuote": true, + "useTabs": true, + "quoteProps": "consistent", + "bracketSpacing": true, + "arrowParens": "always", + "printWidth": 100 } diff --git a/README.md b/README.md index 68e4b25..055504d 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ CACHE_DRIVER=file // defaults to FILE import Cache from '@ioc:Kaperskyguru/Adonis-cache' let posts = await Cache.remember('_posts_', 60, async function () { - return await Post.all() + return await Post.all() }) ``` diff --git a/adonis-typings/index.ts b/adonis-typings/index.ts index a6bf486..0db76d1 100644 --- a/adonis-typings/index.ts +++ b/adonis-typings/index.ts @@ -8,26 +8,26 @@ */ declare module '@ioc:Kaperskyguru/Adonis-Cache' { - /** - * Shape of adonis-cache config. - */ - export interface CacheConfig { - driver: string - drivers: object - } + /** + * Shape of adonis-cache config. + */ + export interface CacheConfig { + driver: string + drivers: object + } - export interface CacheInterface { - get(name: string): Promise - set(name: string, data: any, duration: number): Promise - forever(name: string, data: any): Promise - update(name: string, data: any, duration?: number): Promise - delete(name: string): Promise - remember(name: string, minutes: number, callback: Function): Promise - rememberForever(name: string, callback: Function): Promise - many(keys: Array): Promise - setMany(data: object, minutes: number): Promise - flush(): Promise - } - const Cache: CacheInterface - export default Cache + export interface CacheInterface { + get(name: string): Promise + set(name: string, data: any, duration: number): Promise + forever(name: string, data: any): Promise + update(name: string, data: any, duration?: number): Promise + delete(name: string): Promise + remember(name: string, minutes: number, callback: Function): Promise + rememberForever(name: string, callback: Function): Promise + many(keys: Array): Promise + setMany(data: object, minutes: number): Promise + flush(): Promise + } + const Cache: CacheInterface + export default Cache } diff --git a/config/Config.ts b/config/Config.ts index 3dcfc18..7b4084a 100644 --- a/config/Config.ts +++ b/config/Config.ts @@ -1,3 +1,3 @@ module.exports = { - cacheDriver: 'file', + cacheDriver: 'file', } diff --git a/instructions.js b/instructions.js index 89718b6..51a1a03 100644 --- a/instructions.js +++ b/instructions.js @@ -3,10 +3,10 @@ const path = require('path') module.exports = async (cli) => { - try { - const inFile = path.join(__dirname, './config', 'Config.ts') - const outFile = path.join(cli.helpers.configPath(), 'cache.js') - await cli.copy(inFile, outFile) - cli.command.completed('create', 'config/cache.js') - } catch (error) {} + try { + const inFile = path.join(__dirname, './config', 'Config.ts') + const outFile = path.join(cli.helpers.configPath(), 'cache.js') + await cli.copy(inFile, outFile) + cli.command.completed('create', 'config/cache.js') + } catch (error) {} } diff --git a/instructions.md b/instructions.md index d61e749..4c90769 100644 --- a/instructions.md +++ b/instructions.md @@ -14,6 +14,6 @@ const Cache = use('Cache') const Cache = use('Cache') Cache.get('posts').then((post) => { - res.json(post) + res.json(post) }) ``` diff --git a/npm-audit.html b/npm-audit.html index 935ffb8..a92c5bb 100644 --- a/npm-audit.html +++ b/npm-audit.html @@ -1,149 +1,149 @@ - - - - + + + + - - - - + + + + - NPM Audit Report - + NPM Audit Report + - - + pre code { + color: #fff; + } + + - -
-

NPM Audit Report

+ +
+

NPM Audit Report

-
-
-
-
-
0
-

Known vulnerabilities

-
-
-
-
-
0
-

Dependencies

-
-
-
-
-
May 15th 2021, 8:59:10 pm
-

Last updated

-
-
-
-
-
-
-
0
-

- critical -

-
-
-
-
-
0
-

- high -

-
-
-
-
-
0
-

- moderate -

-
-
-
-
-
0
-

- low -

-
-
-
-
-
0
-

- info -

-
-
-
-
+
+
+
+
+
0
+

Known vulnerabilities

+
+
+
+
+
0
+

Dependencies

+
+
+
+
+
May 15th 2021, 8:59:10 pm
+

Last updated

+
+
+
+
+
+
+
0
+

+ critical +

+
+
+
+
+
0
+

+ high +

+
+
+
+
+
0
+

+ moderate +

+
+
+
+
+
0
+

+ low +

+
+
+
+
+
0
+

+ info +

+
+
+
+
-
-
- - - - - - - - - - -
NameModuleSeverityCVEs
-
-
-
+
+
+ + + + + + + + + + +
NameModuleSeverityCVEs
+
+
+
- - - + + + - - + + diff --git a/package.json b/package.json index 2494825..9272466 100644 --- a/package.json +++ b/package.json @@ -1,114 +1,144 @@ { - "name": "@kaperskyguru/adonis-cache", - "version": "2.1.0", - "description": "Adonis Cache Package", - "main": "build/providers/CacheProvider", - "scripts": { - "mrm": "mrm --preset=@adonisjs/mrm-preset", - "clean": "rm -rf build", - "compile": "npm run clean && tsc", - "build": "npm run compile && npm run copyfiles", - "pretest": "npm run lint", - "test": "echo ''", - "copyfiles": "copyfiles \"README.md\" \"templates/**/*.txt\" \"instructions.js\" \"instructions.md\" build", - "prepublishOnly": "npm run build", - "lint": "eslint . --ext=.ts --fix", - "format": "prettier --write .", - "commit": "git-cz", - "release": "np", - "version": "npm run build", - "sync-labels": "github-label-sync --labels ./node_modules/@adonisjs/mrm-preset/gh-labels.json Kaperskyguru/adonis-cache" - }, - "keywords": [ - "adonis", - "adonisjs", - "cache" - ], - "homepage": "https://github.com/kaperskyguru/adonis-cache#readme", - "author": "Solomon Eseme", - "license": "MIT", - "devDependencies": { - "@adonisjs/core": "^5.7.2", - "@adonisjs/mrm-preset": "^2.4.0", - "@adonisjs/redis": "7.0.2", - "@adonisjs/repl": "^3.1.10", - "@types/node": "^13.13.52", - "commitizen": "^4.2.4", - "copyfiles": "^2.4.1", - "doctoc": "^2.1.0", - "eslint": "^8.13.0", - "eslint-config-prettier": "^8.5.0", - "eslint-plugin-adonis": "^2.1.0", - "eslint-plugin-prettier": "^4.0.0", - "github-label-sync": "^2.2.0", - "husky": "^6.0.0", - "mrm": "^2.6.2", - "np": "^7.6.1", - "prettier": "^2.0.5", - "reflect-metadata": "^0.1.13", - "ts-node": "^8.6.2", - "typescript": "^4.5.4" - }, - "files": [ - "build/adonis-typings", - "build/providers", - "build/src", - "build/config", - "build/instructions.js", - "build/templates" - ], - "husky": { - "hooks": { - "pre-commit": "npm audit --production --json | ./node_modules/.bin/npm-audit-html && git add npm-audit.html && doctoc README.md --title='## Table of contents' && git add README.md", - "commit-msg": "node ./node_modules/@adonisjs/mrm-preset/validateCommit/conventional/validate.js" - } - }, - "types": "build/adonis-typings/index.d.ts", - "np": { - "contents": ".", - "anyBranch": false - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Kaperskyguru/kap-adonis-cache.git" - }, - "bugs": { - "url": "https://github.com/Kaperskyguru/kap-adonis-cache/issues" - }, - "config": { - "commitizen": { - "path": "cz-conventional-changelog" - } - }, - "publishConfig": { - "access": "public" - }, - "adonisjs": { - "instructions": "./build/instructions.js", - "instructionsMd": "./build/instructions.md", - "types": "@kaperskyguru/adonis-cache", - "providers": [ - "@kaperskyguru/adonis-cache" - ], - "templates": { - "config": [ - "cache.txt" - ], - "contract": [ - "cache.txt" - ] - } - }, - "peerDependencies": { - "@adonisjs/core": "^5.1.1", - "@adonisjs/redis": "^7.0.2" - }, - "peerDependenciesMeta": { - "@adonisjs/redis": { - "optional": true - } - }, - "dependencies": { - "fs": "^0.0.1-security" - } + "name": "@kaperskyguru/adonis-cache", + "version": "2.1.0", + "description": "Adonis Cache Package", + "main": "build/providers/CacheProvider", + "scripts": { + "mrm": "mrm --preset=@adonisjs/mrm-preset", + "clean": "rm -rf build", + "compile": "npm run clean && tsc", + "build": "npm run compile && npm run copyfiles", + "pretest": "npm run lint", + "test": "echo ''", + "copyfiles": "copyfiles \"README.md\" \"templates/**/*.txt\" \"instructions.js\" \"instructions.md\" build", + "prepublishOnly": "npm run build", + "lint": "eslint . --ext=.ts --fix", + "format": "prettier --write .", + "commit": "git-cz", + "release": "np", + "version": "npm run build", + "sync-labels": "github-label-sync --labels ./node_modules/@adonisjs/mrm-preset/gh-labels.json Kaperskyguru/adonis-cache" + }, + "keywords": [ + "adonis", + "adonisjs", + "cache" + ], + "homepage": "https://github.com/kaperskyguru/adonis-cache#readme", + "author": "Solomon Eseme", + "license": "MIT", + "devDependencies": { + "@adonisjs/core": "^5.7.2", + "@adonisjs/mrm-preset": "^2.4.0", + "@adonisjs/redis": "7.0.2", + "@adonisjs/repl": "^3.1.10", + "@types/node": "^13.13.52", + "commitizen": "^4.2.4", + "copyfiles": "^2.4.1", + "doctoc": "^2.1.0", + "eslint": "^8.13.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-adonis": "^2.1.0", + "eslint-plugin-prettier": "^4.0.0", + "github-label-sync": "^2.2.0", + "husky": "^6.0.0", + "mrm": "^2.6.2", + "np": "^7.6.1", + "prettier": "^2.0.5", + "reflect-metadata": "^0.1.13", + "ts-node": "^8.6.2", + "typescript": "^4.6.3" + }, + "files": [ + "build/adonis-typings", + "build/providers", + "build/src", + "build/config", + "build/instructions.js", + "build/templates" + ], + "husky": { + "hooks": { + "pre-commit": "npm audit --production --json | ./node_modules/.bin/npm-audit-html && git add npm-audit.html && doctoc README.md --title='## Table of contents' && git add README.md", + "commit-msg": "node ./node_modules/@adonisjs/mrm-preset/validateCommit/conventional/validate.js" + } + }, + "types": "build/adonis-typings/index.d.ts", + "np": { + "contents": ".", + "anyBranch": false + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Kaperskyguru/kap-adonis-cache.git" + }, + "bugs": { + "url": "https://github.com/Kaperskyguru/kap-adonis-cache/issues" + }, + "config": { + "commitizen": { + "path": "cz-conventional-changelog" + } + }, + "publishConfig": { + "access": "public" + }, + "eslintConfig": { + "extends": [ + "plugin:adonis/typescriptPackage", + "prettier" + ], + "plugins": [ + "prettier" + ], + "rules": { + "prettier/prettier": [ + "error", + { + "endOfLine": "auto" + } + ] + } + }, + "eslintIgnore": [ + "build" + ], + "prettier": { + "trailingComma": "es5", + "semi": false, + "singleQuote": true, + "useTabs": false, + "quoteProps": "consistent", + "bracketSpacing": true, + "arrowParens": "always", + "printWidth": 100 + }, + "adonisjs": { + "instructions": "./build/instructions.js", + "instructionsMd": "./build/instructions.md", + "types": "@kaperskyguru/adonis-cache", + "providers": [ + "@kaperskyguru/adonis-cache" + ], + "templates": { + "config": [ + "cache.txt" + ], + "contract": [ + "cache.txt" + ] + } + }, + "peerDependencies": { + "@adonisjs/core": "^5.1.1", + "@adonisjs/redis": "^7.0.2" + }, + "peerDependenciesMeta": { + "@adonisjs/redis": { + "optional": true + } + }, + "dependencies": { + "fs": "^0.0.1-security" + } } diff --git a/providers/CacheProvider.ts b/providers/CacheProvider.ts index 891143a..cfaa4ab 100644 --- a/providers/CacheProvider.ts +++ b/providers/CacheProvider.ts @@ -3,15 +3,15 @@ import { ApplicationContract } from '@ioc:Adonis/Core/Application' export default class CacheProvider { - constructor(protected app: ApplicationContract) {} - public register() { - this.app.container.singleton('Kaperskyguru/Adonis-Cache', () => { - const CacheLoader = require('../src/CacheLoader') - return new CacheLoader(this.app).createCache() - }) + constructor(protected app: ApplicationContract) {} + public register() { + this.app.container.singleton('Kaperskyguru/Adonis-Cache', () => { + const CacheLoader = require('../src/CacheLoader') + return new CacheLoader(this.app).createCache() + }) - this.app.container.alias('Kaperskyguru/Adonis-Cache', 'Cache') - } + this.app.container.alias('Kaperskyguru/Adonis-Cache', 'Cache') + } } module.exports = CacheProvider diff --git a/src/CacheLoader.ts b/src/CacheLoader.ts index d9a2b1e..2d6f635 100644 --- a/src/CacheLoader.ts +++ b/src/CacheLoader.ts @@ -5,51 +5,51 @@ const RedisCacheService = require('../src/Services/RedisCacheService') const MemCacheService = require('../src/Services/MemCacheService') class CacheLoader { - private cacheDriver = 'redis' - private app: any - - constructor(App: any) { - this.app = App - this._setConfig('driver', this.cacheDriver) - } - - public createCache() { - const driver: string = this._getConfig('driver') - let cache: any - switch (driver.toLowerCase()) { - case 'memcache': - // Load MemCacheService - cache = new Cache(new MemCacheService(this.app)) - break - - case 'redis': - // Load RedisCacheService - cache = new Cache(new RedisCacheService(this.app)) - break - - case 'database': - // Load DatabaseCacheService - cache = new Cache(new DatabaseCacheService(this.app)) - break - - default: - // Load FileCacheService - cache = new Cache(new FileCacheService(this.app)) - break - } - return cache - } - - private _getConfig(name: string): string { - return this.app.container.use('Adonis/Core/Config').get(`cache.${name}`) - } - private _setConfig(name: string, value: any) { - const config = this._getConfig(name) - if (config) { - return - } - this.app.container.use('Adonis/Core/Config').set(`cache.${name}`, value) - } + private cacheDriver = 'redis' + private app: any + + constructor(App: any) { + this.app = App + this._setConfig('driver', this.cacheDriver) + } + + public createCache() { + const driver: string = this._getConfig('driver') + let cache: any + switch (driver.toLowerCase()) { + case 'memcache': + // Load MemCacheService + cache = new Cache(new MemCacheService(this.app)) + break + + case 'redis': + // Load RedisCacheService + cache = new Cache(new RedisCacheService(this.app)) + break + + case 'database': + // Load DatabaseCacheService + cache = new Cache(new DatabaseCacheService(this.app)) + break + + default: + // Load FileCacheService + cache = new Cache(new FileCacheService(this.app)) + break + } + return cache + } + + private _getConfig(name: string): string { + return this.app.container.use('Adonis/Core/Config').get(`cache.${name}`) + } + private _setConfig(name: string, value: any) { + const config = this._getConfig(name) + if (config) { + return + } + this.app.container.use('Adonis/Core/Config').set(`cache.${name}`, value) + } } module.exports = CacheLoader diff --git a/src/Consumers/Cache.ts b/src/Consumers/Cache.ts index 4b25bc3..59ce103 100644 --- a/src/Consumers/Cache.ts +++ b/src/Consumers/Cache.ts @@ -1,91 +1,91 @@ import CacheInterface from '../Contracts/CacheInterface' import ServiceInterface from '../Contracts/ServiceInterface' class Cache implements CacheInterface { - private cacheService: ServiceInterface - constructor(cacheService: ServiceInterface) { - this.cacheService = cacheService - } + private cacheService: ServiceInterface + constructor(cacheService: ServiceInterface) { + this.cacheService = cacheService + } - public async get(name: string): Promise { - if (name) { - return await this.cacheService.get(name) - } - throw new Error('Specify a name') - } + public async get(name: string): Promise { + if (name) { + return await this.cacheService.get(name) + } + throw new Error('Specify a name') + } - public async has(name: string): Promise { - const value = await this.cacheService.get(name) - return !!value - } + public async has(name: string): Promise { + const value = await this.cacheService.get(name) + return !!value + } - public async set(name: string, data: any, minutes: number): Promise { - if (name && data) { - return await this.cacheService.set(name, data, minutes) - } - throw new Error('Specify a name and data to cache') - } + public async set(name: string, data: any, minutes: number): Promise { + if (name && data) { + return await this.cacheService.set(name, data, minutes) + } + throw new Error('Specify a name and data to cache') + } - public async delete(name: string): Promise { - if (await this.has(name)) { - await this.cacheService.delete(name) - return true - } - return false - } + public async delete(name: string): Promise { + if (await this.has(name)) { + await this.cacheService.delete(name) + return true + } + return false + } - public async update(name: string, data: any, minutes: number = 0): Promise { - if (await this.has(name)) { - await this.delete(name) - return await this.set(name, data, minutes) - } else return await this.set(name, data, minutes) - } + public async update(name: string, data: any, minutes: number = 0): Promise { + if (await this.has(name)) { + await this.delete(name) + return await this.set(name, data, minutes) + } else return await this.set(name, data, minutes) + } - public async remember(name: string, minutes: number, callback: Function): Promise { - if (await this.has(name)) { - return await this.get(name) - } else { - const data = await callback() - await this.set(name, data, minutes) - return data - } - } + public async remember(name: string, minutes: number, callback: Function): Promise { + if (await this.has(name)) { + return await this.get(name) + } else { + const data = await callback() + await this.set(name, data, minutes) + return data + } + } - public async rememberForever(name: string, callback: Function): Promise { - if (await this.has(name)) { - return await this.get(name) - } else { - const data = await callback() - await this.cacheService.set(name, data) - return data - } - } + public async rememberForever(name: string, callback: Function): Promise { + if (await this.has(name)) { + return await this.get(name) + } else { + const data = await callback() + await this.cacheService.set(name, data) + return data + } + } - public async many(keys: Array): Promise { - let values = Promise.all(keys.map((key: string) => this.get(key))) - let mappedValues: object = {} - for (let index: number = 0; index < keys.length; index++) { - mappedValues[keys[index]] = values[index] - } - return mappedValues - } + public async many(keys: Array): Promise { + let values = Promise.all(keys.map((key: string) => this.get(key))) + let mappedValues: object = {} + for (let index: number = 0; index < keys.length; index++) { + mappedValues[keys[index]] = values[index] + } + return mappedValues + } - public async setMany(data: object, minutes: number = 0): Promise { - for (let prop in data) { - await this.set(prop, data[prop], minutes) - } - return data - } + public async setMany(data: object, minutes: number = 0): Promise { + for (let prop in data) { + await this.set(prop, data[prop], minutes) + } + return data + } - public async flush(): Promise { - return await this.cacheService.flush() - } + public async flush(): Promise { + return await this.cacheService.flush() + } - public async forever(key: string, values: any): Promise { - if (key && values) { - return await this.cacheService.set(key, values) - } - throw new Error('Specify a name and data to cache') - } + public async forever(key: string, values: any): Promise { + if (key && values) { + return await this.cacheService.set(key, values) + } + throw new Error('Specify a name and data to cache') + } } /* diff --git a/src/Contracts/CacheInterface.ts b/src/Contracts/CacheInterface.ts index d1134b0..4d01e56 100644 --- a/src/Contracts/CacheInterface.ts +++ b/src/Contracts/CacheInterface.ts @@ -1,13 +1,13 @@ interface CacheInterface { - get(name: string): Promise - set(name: string, data: any, duration: number): Promise - forever(name: string, data: any): Promise - update(name: string, data: any, duration?: number): Promise - delete(name: string): Promise - remember(name: string, minutes: number, callback: Function): Promise - rememberForever(name: string, callback: Function): Promise - many(keys: Array): Promise - setMany(data: object, minutes: number): Promise - flush(): Promise + get(name: string): Promise + set(name: string, data: any, duration: number): Promise + forever(name: string, data: any): Promise + update(name: string, data: any, duration?: number): Promise + delete(name: string): Promise + remember(name: string, minutes: number, callback: Function): Promise + rememberForever(name: string, callback: Function): Promise + many(keys: Array): Promise + setMany(data: object, minutes: number): Promise + flush(): Promise } export default CacheInterface diff --git a/src/Contracts/EngineInterface.ts b/src/Contracts/EngineInterface.ts index 8f70f21..8651749 100644 --- a/src/Contracts/EngineInterface.ts +++ b/src/Contracts/EngineInterface.ts @@ -1,7 +1,7 @@ interface EngineInterface { - get(name: string): Promise - set(name: string, data: any, duration: number): Promise - delete(name: String): Promise - flush(): Promise + get(name: string): Promise + set(name: string, data: any, duration: number): Promise + delete(name: String): Promise + flush(): Promise } export default EngineInterface diff --git a/src/Contracts/ServiceInterface.ts b/src/Contracts/ServiceInterface.ts index 4571229..ffdc237 100644 --- a/src/Contracts/ServiceInterface.ts +++ b/src/Contracts/ServiceInterface.ts @@ -1,7 +1,7 @@ interface ServiceInterface { - get(name: string): Promise - set(name: string, data: any, duration?: number): Promise - delete(name: string): Promise - flush(): Promise + get(name: string): Promise + set(name: string, data: any, duration?: number): Promise + delete(name: string): Promise + flush(): Promise } export default ServiceInterface diff --git a/src/Engines/DatabaseCache.ts b/src/Engines/DatabaseCache.ts index e2102b3..b1e78fc 100644 --- a/src/Engines/DatabaseCache.ts +++ b/src/Engines/DatabaseCache.ts @@ -3,42 +3,42 @@ import EngineInterface from '../Contracts/EngineInterface' // const DatabaseCache = use("DatabaseCache"); class DatabaseCache implements EngineInterface { - private defaultMinutes = 60 + private defaultMinutes = 60 - constructor(app: any) { - console.log(app) - } - public async get(name: string): Promise { - if (name) { - // Implement Database get here - console.log(name) - const value = '' - if (value) { - return JSON.parse(value) - } - } - } + constructor(app: any) { + console.log(app) + } + public async get(name: string): Promise { + if (name) { + // Implement Database get here + console.log(name) + const value = '' + if (value) { + return JSON.parse(value) + } + } + } - public async set(name: string, data: any, duration: number = this.defaultMinutes): Promise { - if (name && data) { - // Implement Set method - console.log(name, data, duration) - // data = JSON.stringify(data); - // if (duration == null) { - // return await this._addCache(name, data); - // } - // return await this._addExpiredCache(name, data, duration); - } - } - public async flush(): Promise { - throw new Error('Method not implemented.') - } + public async set(name: string, data: any, duration: number = this.defaultMinutes): Promise { + if (name && data) { + // Implement Set method + console.log(name, data, duration) + // data = JSON.stringify(data); + // if (duration == null) { + // return await this._addCache(name, data); + // } + // return await this._addExpiredCache(name, data, duration); + } + } + public async flush(): Promise { + throw new Error('Method not implemented.') + } - public async delete(name: string): Promise { - // Implement Delete function - console.log(name) + public async delete(name: string): Promise { + // Implement Delete function + console.log(name) - return true - } + return true + } } export default DatabaseCache diff --git a/src/Engines/FileCache.ts b/src/Engines/FileCache.ts index f67d6b9..d32f85b 100644 --- a/src/Engines/FileCache.ts +++ b/src/Engines/FileCache.ts @@ -2,131 +2,131 @@ import EngineInterface from '../Contracts/EngineInterface' import fs from 'fs' class FileCache implements EngineInterface { - private fileConfig: any - private app: any - private hash: any - - constructor(app: any) { - this.app = app - this.hash = app.container.use('Adonis/Core/Hash') - try { - this.fileConfig = app.container.use('Adonis/Core/Config').get('cache').drivers.file - if (!this.fileConfig) { - throw new Error('File driver configuration not found') - } - this.init() - } catch (error) { - throw new Error(error) - } - } - - private init() { - !fs.existsSync(this.app.tmpPath(this.fileConfig.path)) && - fs.mkdirSync(this.app.tmpPath(this.fileConfig.path), { recursive: true }) - } - - private path() { - return this.app.tmpPath(this.fileConfig.path) - } - - private ensureCacheDirectoryExists(path: string) { - !fs.existsSync(path) && fs.mkdirSync(path, { recursive: true }) - } - - private write(key: string, data: any) { - this.ensureCacheDirectoryExists(this.path()) - - fs.writeFileSync(this.path() + '/' + '_' + this.hashKey(key), data, 'binary') - } - - private writeWithTime(key: string, data: any, duration: number) { - this.ensureCacheDirectoryExists(this.path()) - const currentDate = new Date() - const futureDate = new Date(currentDate.getTime() + duration * 60000) - const expiresIn = futureDate.getTime() - // Append Timestamp to the data - - const newArr = {} - - newArr['meta'] = { expiresIn } - newArr['data'] = data - - fs.writeFileSync( - this.path() + '/' + this.hashKey(key) + '.cache', - JSON.stringify(newArr), - 'binary' - ) - } - - private read(key: string): any { - const data = JSON.parse( - fs.readFileSync(this.path() + '/' + this.hashKey(key) + '.cache', 'binary') - ) - - if (data['meta']) { - const time = new Date(data['meta']['expiresIn']).getTime() - if (time < new Date().getTime()) { - return this.deleteFIle(key) - } - } - return JSON.stringify(data['data']) - } - - public async get(name: string): Promise { - if (await this.isCacheExist(name)) { - const data = this.read(name) - if (typeof data === 'boolean') { - return null - } - return data - } - return null - } - - public async set(name: string, data: any, duration: number): Promise { - if (!name) { - throw new Error('Cache key not provided') - } - - if (!data) { - throw new Error('Cache data not provided') - } - - if (duration !== 0) { - return this.writeWithTime(name, data, duration) - } - - return this.write(name, data) - } - - public async flush(): Promise { - fs.rmdirSync(this.path(), { recursive: true }) - } - - public async delete(key: string): Promise { - return this.deleteFIle(key) - } - - private hashKey(key: string) { - return this.hash.make(key + '') - } - - private async isCacheExist(key: string): Promise { - const path = this.path() - return fs.existsSync(path + '/' + this.hashKey(key) + '.cache') - } - - private async deleteFIle(key: string): Promise { - try { - if (await this.isCacheExist(key)) { - const path = this.path() - fs.unlinkSync(path + '/' + this.hashKey(key) + '.cache') - return true - } - return false - } catch (e) { - return false - } - } + private fileConfig: any + private app: any + private hash: any + + constructor(app: any) { + this.app = app + this.hash = app.container.use('Adonis/Core/Hash') + try { + this.fileConfig = app.container.use('Adonis/Core/Config').get('cache').drivers.file + if (!this.fileConfig) { + throw new Error('File driver configuration not found') + } + this.init() + } catch (error) { + throw new Error(error) + } + } + + private init() { + !fs.existsSync(this.app.tmpPath(this.fileConfig.path)) && + fs.mkdirSync(this.app.tmpPath(this.fileConfig.path), { recursive: true }) + } + + private path() { + return this.app.tmpPath(this.fileConfig.path) + } + + private ensureCacheDirectoryExists(path: string) { + !fs.existsSync(path) && fs.mkdirSync(path, { recursive: true }) + } + + private write(key: string, data: any) { + this.ensureCacheDirectoryExists(this.path()) + + fs.writeFileSync(this.path() + '/' + '_' + this.hashKey(key), data, 'binary') + } + + private writeWithTime(key: string, data: any, duration: number) { + this.ensureCacheDirectoryExists(this.path()) + const currentDate = new Date() + const futureDate = new Date(currentDate.getTime() + duration * 60000) + const expiresIn = futureDate.getTime() + // Append Timestamp to the data + + const newArr = {} + + newArr['meta'] = { expiresIn } + newArr['data'] = data + + fs.writeFileSync( + this.path() + '/' + this.hashKey(key) + '.cache', + JSON.stringify(newArr), + 'binary' + ) + } + + private read(key: string): any { + const data = JSON.parse( + fs.readFileSync(this.path() + '/' + this.hashKey(key) + '.cache', 'binary') + ) + + if (data['meta']) { + const time = new Date(data['meta']['expiresIn']).getTime() + if (time < new Date().getTime()) { + return this.deleteFIle(key) + } + } + return JSON.stringify(data['data']) + } + + public async get(name: string): Promise { + if (await this.isCacheExist(name)) { + const data = this.read(name) + if (typeof data === 'boolean') { + return null + } + return data + } + return null + } + + public async set(name: string, data: any, duration: number): Promise { + if (!name) { + throw new Error('Cache key not provided') + } + + if (!data) { + throw new Error('Cache data not provided') + } + + if (duration !== 0) { + return this.writeWithTime(name, data, duration) + } + + return this.write(name, data) + } + + public async flush(): Promise { + fs.rmdirSync(this.path(), { recursive: true }) + } + + public async delete(key: string): Promise { + return this.deleteFIle(key) + } + + private hashKey(key: string) { + return this.hash.make(key + '') + } + + private async isCacheExist(key: string): Promise { + const path = this.path() + return fs.existsSync(path + '/' + this.hashKey(key) + '.cache') + } + + private async deleteFIle(key: string): Promise { + try { + if (await this.isCacheExist(key)) { + const path = this.path() + fs.unlinkSync(path + '/' + this.hashKey(key) + '.cache') + return true + } + return false + } catch (e) { + return false + } + } } export default FileCache diff --git a/src/Engines/MemCache.ts b/src/Engines/MemCache.ts index fe9037c..87d66d9 100644 --- a/src/Engines/MemCache.ts +++ b/src/Engines/MemCache.ts @@ -3,42 +3,42 @@ import EngineInterface from '../Contracts/EngineInterface' // const MemCache = use("MemCache"); class MemCache implements EngineInterface { - private defaultMinutes = 60 + private defaultMinutes = 60 - constructor(app: any) { - console.log(app) - } - public async get(name: string): Promise { - if (name) { - // Implement Mem get here - console.log(name) - const value = '' - if (value) { - return JSON.parse(value) - } - } - } + constructor(app: any) { + console.log(app) + } + public async get(name: string): Promise { + if (name) { + // Implement Mem get here + console.log(name) + const value = '' + if (value) { + return JSON.parse(value) + } + } + } - public async set(name: string, data: any, duration: number = this.defaultMinutes): Promise { - if (name && data) { - console.log(name, data, duration) - // Implement Set method - // data = JSON.stringify(data); - // if (duration == null) { - // return await this._addCache(name, data); - // } - // return await this._addExpiredCache(name, data, duration); - } - } + public async set(name: string, data: any, duration: number = this.defaultMinutes): Promise { + if (name && data) { + console.log(name, data, duration) + // Implement Set method + // data = JSON.stringify(data); + // if (duration == null) { + // return await this._addCache(name, data); + // } + // return await this._addExpiredCache(name, data, duration); + } + } - public async flush(): Promise { - throw new Error('Method not implemented.') - } + public async flush(): Promise { + throw new Error('Method not implemented.') + } - public async delete(name: string): Promise { - // Implement Delete function - console.log(name) - return true - } + public async delete(name: string): Promise { + // Implement Delete function + console.log(name) + return true + } } export default MemCache diff --git a/src/Engines/RedisCache.ts b/src/Engines/RedisCache.ts index 813f734..618172f 100644 --- a/src/Engines/RedisCache.ts +++ b/src/Engines/RedisCache.ts @@ -1,98 +1,98 @@ import EngineInterface from '../Contracts/EngineInterface' import { - RedisManagerContract, - RedisConnectionContract, - RedisClusterConnectionContract, + RedisManagerContract, + RedisConnectionContract, + RedisClusterConnectionContract, } from '@ioc:Adonis/Addons/Redis' class RedisCache implements EngineInterface { - // private defaultMinutes = 60; - private redis: RedisManagerContract - private config: any + // private defaultMinutes = 60; + private redis: RedisManagerContract + private config: any - /** - * Custom connection or query client - */ - private connection?: string | RedisConnectionContract | RedisClusterConnectionContract + /** + * Custom connection or query client + */ + private connection?: string | RedisConnectionContract | RedisClusterConnectionContract - constructor(app: any) { - if (!app.container.hasBinding('Adonis/Addons/Redis')) { - throw new Error('"@adonisjs/redis" is required to use the "redis" token provider') - } + constructor(app: any) { + if (!app.container.hasBinding('Adonis/Addons/Redis')) { + throw new Error('"@adonisjs/redis" is required to use the "redis" token provider') + } - this.redis = app.container.use('Adonis/Addons/Redis') - this.config = app.container.use('Adonis/Core/Config').get('redis') - } + this.redis = app.container.use('Adonis/Addons/Redis') + this.config = app.container.use('Adonis/Core/Config').get('redis') + } - /** - * Returns the singleton instance of the redis connection - */ - private getRedisConnection(): RedisConnectionContract | RedisClusterConnectionContract { - /** - * Use custom connection if defined - */ - if (this.connection) { - return typeof this.connection === 'string' - ? this.redis.connection(this.connection) - : this.connection - } + /** + * Returns the singleton instance of the redis connection + */ + private getRedisConnection(): RedisConnectionContract | RedisClusterConnectionContract { + /** + * Use custom connection if defined + */ + if (this.connection) { + return typeof this.connection === 'string' + ? this.redis.connection(this.connection) + : this.connection + } - /** - * Config must have a connection defined - */ - if (!this.config.connections) { - throw new Error( - 'Missing "connections" property for redis provider inside "config/redis" file', - ) - } + /** + * Config must have a connection defined + */ + if (!this.config.connections) { + throw new Error( + 'Missing "connections" property for redis provider inside "config/redis" file' + ) + } - return this.redis.connection() - } + return this.redis.connection() + } - /** - * Define custom connection - */ - public setConnection( - connection: string | RedisConnectionContract | RedisClusterConnectionContract, - ): this { - this.connection = connection - return this - } + /** + * Define custom connection + */ + public setConnection( + connection: string | RedisConnectionContract | RedisClusterConnectionContract + ): this { + this.connection = connection + return this + } - public async get(name: string): Promise { - if (name) { - const value = await this.getRedisConnection().get(name) - return value ? value : null - } - } + public async get(name: string): Promise { + if (name) { + const value = await this.getRedisConnection().get(name) + return value ? value : null + } + } - public async set(name: string, data: any, duration: number): Promise { - if (name && data) { - if (duration === 0) { - return await this._addCache(name, data) - } - return await this._addExpiredCache(name, data, duration) - } - } + public async set(name: string, data: any, duration: number): Promise { + if (name && data) { + if (duration === 0) { + return await this._addCache(name, data) + } + return await this._addExpiredCache(name, data, duration) + } + } - public async delete(name: string): Promise { - await this.getRedisConnection().del(name) - return true - } + public async delete(name: string): Promise { + await this.getRedisConnection().del(name) + return true + } - public async flush(): Promise { - await this.getRedisConnection().flushdb() - } + public async flush(): Promise { + await this.getRedisConnection().flushdb() + } - private async _addExpiredCache(name: string, data: any, duration: number): Promise { - let expiration = Math.floor(duration * 60) - await this.getRedisConnection().set(name, data, 'EX', expiration) - return data - } + private async _addExpiredCache(name: string, data: any, duration: number): Promise { + let expiration = Math.floor(duration * 60) + await this.getRedisConnection().set(name, data, 'EX', expiration) + return data + } - private async _addCache(name: string, data: any): Promise { - await this.getRedisConnection().set(name, data) - return data - } + private async _addCache(name: string, data: any): Promise { + await this.getRedisConnection().set(name, data) + return data + } } export default RedisCache diff --git a/src/Services/DatabaseCacheService.ts b/src/Services/DatabaseCacheService.ts index 65fa2e3..40c5630 100644 --- a/src/Services/DatabaseCacheService.ts +++ b/src/Services/DatabaseCacheService.ts @@ -2,70 +2,70 @@ import ServiceInterface from '../Contracts/ServiceInterface' import DatabaseCache from '../Engines/DatabaseCache' class DatabaseCacheService extends DatabaseCache implements ServiceInterface { - constructor(config: any) { - super(config) - } + constructor(config: any) { + super(config) + } - public async get(name: string): Promise { - if (name) { - const value: string = await super.get(name) - if (value) { - return JSON.parse(value) - } - } - } + public async get(name: string): Promise { + if (name) { + const value: string = await super.get(name) + if (value) { + return JSON.parse(value) + } + } + } - public async has(name: string): Promise { - const value = await this.get(name) - if (value === null) { - return false - } - return true - } + public async has(name: string): Promise { + const value = await this.get(name) + if (value === null) { + return false + } + return true + } - public async set(name: string, data: any, duration: number): Promise { - if (name && data) { - data = JSON.stringify(data) - return await super.set(name, data, duration) - // if (duration == null) { - // return await this._addCache(name, data); - // } - // return await this._addExpiredCache(name, data, duration); - } - } + public async set(name: string, data: any, duration: number): Promise { + if (name && data) { + data = JSON.stringify(data) + return await super.set(name, data, duration) + // if (duration == null) { + // return await this._addCache(name, data); + // } + // return await this._addExpiredCache(name, data, duration); + } + } - public async delete(name: string): Promise { - if (await this.has(name)) { - await super.delete(name) - return true - } - return false - } + public async delete(name: string): Promise { + if (await this.has(name)) { + await super.delete(name) + return true + } + return false + } - public async update(name: string, data: any, duration: number): Promise { - if (await this.delete(name)) { - return await this.set(name, data, duration) - } else return await this.set(name, data, duration) - } + public async update(name: string, data: any, duration: number): Promise { + if (await this.delete(name)) { + return await this.set(name, data, duration) + } else return await this.set(name, data, duration) + } - public async remember(name: string, duration: number, callback: Function): Promise { - if (await this.has(name)) { - return await this.get(name) - } else { - const data = await callback() - await this.set(name, data, duration) - return data - } - } + public async remember(name: string, duration: number, callback: Function): Promise { + if (await this.has(name)) { + return await this.get(name) + } else { + const data = await callback() + await this.set(name, data, duration) + return data + } + } - public async rememberForever(name: string, callback: Function): Promise { - if (await this.has(name)) { - return await this.get(name) - } else { - const data = await callback() - await this.set(name, data, 50000000000000) - return data - } - } + public async rememberForever(name: string, callback: Function): Promise { + if (await this.has(name)) { + return await this.get(name) + } else { + const data = await callback() + await this.set(name, data, 50000000000000) + return data + } + } } module.exports = DatabaseCacheService diff --git a/src/Services/FileCacheService.ts b/src/Services/FileCacheService.ts index c565860..9e85b0e 100644 --- a/src/Services/FileCacheService.ts +++ b/src/Services/FileCacheService.ts @@ -2,55 +2,55 @@ import ServiceInterface from '../Contracts/ServiceInterface' import FileCache from '../Engines/FileCache' class FileCacheService extends FileCache implements ServiceInterface { - constructor(app: any) { - super(app) - } - - public async get(name: string): Promise { - if (name) { - const value = await super.get(name) - if (value) { - return this.deserialize(value) - } - return null - } - } - - public async has(name: string): Promise { - const value = await this.get(name) - return !!value - } - - public async set(name: string, data: any, duration: number = 0): Promise { - if (name && data) { - return await super.set(name, this.serialize(data), duration) - } - } - - public async delete(name: string): Promise { - if (await this.has(name)) { - await super.delete(name) - return true - } - return false - } - - public async flush(): Promise { - return await super.flush() - } - - public async update(name: string, data: any, duration: number): Promise { - if (await this.delete(name)) { - return await this.set(name, data, duration) - } else return await this.set(name, data, duration) - } - - private serialize(data: any): any { - return JSON.stringify(data) - } - - private deserialize(data: any): any { - return JSON.parse(data) - } + constructor(app: any) { + super(app) + } + + public async get(name: string): Promise { + if (name) { + const value = await super.get(name) + if (value) { + return this.deserialize(value) + } + return null + } + } + + public async has(name: string): Promise { + const value = await this.get(name) + return !!value + } + + public async set(name: string, data: any, duration: number = 0): Promise { + if (name && data) { + return await super.set(name, this.serialize(data), duration) + } + } + + public async delete(name: string): Promise { + if (await this.has(name)) { + await super.delete(name) + return true + } + return false + } + + public async flush(): Promise { + return await super.flush() + } + + public async update(name: string, data: any, duration: number): Promise { + if (await this.delete(name)) { + return await this.set(name, data, duration) + } else return await this.set(name, data, duration) + } + + private serialize(data: any): any { + return JSON.stringify(data) + } + + private deserialize(data: any): any { + return JSON.parse(data) + } } module.exports = FileCacheService diff --git a/src/Services/MemCacheService.ts b/src/Services/MemCacheService.ts index cde8686..af92549 100644 --- a/src/Services/MemCacheService.ts +++ b/src/Services/MemCacheService.ts @@ -2,70 +2,70 @@ import ServiceInterface from '../Contracts/ServiceInterface' import MemCache from '../Engines/MemCache' class MemCacheService extends MemCache implements ServiceInterface { - constructor(config: any) { - super(config) - } + constructor(config: any) { + super(config) + } - public async get(name: string): Promise { - if (name) { - const value: string = await super.get(name) - if (value) { - return JSON.parse(value) - } - } - } + public async get(name: string): Promise { + if (name) { + const value: string = await super.get(name) + if (value) { + return JSON.parse(value) + } + } + } - public async has(name: string): Promise { - const value = await this.get(name) - if (value === null) { - return false - } - return true - } + public async has(name: string): Promise { + const value = await this.get(name) + if (value === null) { + return false + } + return true + } - public async set(name: string, data: any, duration: number): Promise { - if (name && data) { - data = JSON.stringify(data) - return await super.set(name, data, duration) - // if (duration == null) { - // return await this._addCache(name, data); - // } - // return await this._addExpiredCache(name, data, duration); - } - } + public async set(name: string, data: any, duration: number): Promise { + if (name && data) { + data = JSON.stringify(data) + return await super.set(name, data, duration) + // if (duration == null) { + // return await this._addCache(name, data); + // } + // return await this._addExpiredCache(name, data, duration); + } + } - public async delete(name: string): Promise { - if (await this.has(name)) { - await super.delete(name) - return true - } - return false - } + public async delete(name: string): Promise { + if (await this.has(name)) { + await super.delete(name) + return true + } + return false + } - public async update(name: string, data: any, duration: number): Promise { - if (await this.delete(name)) { - return await this.set(name, data, duration) - } else return await this.set(name, data, duration) - } + public async update(name: string, data: any, duration: number): Promise { + if (await this.delete(name)) { + return await this.set(name, data, duration) + } else return await this.set(name, data, duration) + } - public async remember(name: string, duration: number, callback: Function): Promise { - if (await this.has(name)) { - return await this.get(name) - } else { - const data = await callback() - await this.set(name, data, duration) - return data - } - } + public async remember(name: string, duration: number, callback: Function): Promise { + if (await this.has(name)) { + return await this.get(name) + } else { + const data = await callback() + await this.set(name, data, duration) + return data + } + } - public async rememberForever(name: string, callback: Function): Promise { - if (await this.has(name)) { - return await this.get(name) - } else { - const data = await callback() - await this.set(name, data, 50000000000000) - return data - } - } + public async rememberForever(name: string, callback: Function): Promise { + if (await this.has(name)) { + return await this.get(name) + } else { + const data = await callback() + await this.set(name, data, 50000000000000) + return data + } + } } module.exports = MemCacheService diff --git a/src/Services/RedisCacheService.ts b/src/Services/RedisCacheService.ts index 5b168f6..94ad07e 100644 --- a/src/Services/RedisCacheService.ts +++ b/src/Services/RedisCacheService.ts @@ -2,50 +2,50 @@ import ServiceInterface from '../Contracts/ServiceInterface' import RedisCache from '../Engines/RedisCache' class RedisCacheService extends RedisCache implements ServiceInterface { - constructor(app: any) { - super(app) - } - - public async get(name: string): Promise { - if (name) { - const value: string = await super.get(name) - if (value) { - return this.deserialize(value) - } - } - } - - public async has(name: string): Promise { - const value = await this.get(name) - return !value - } - - public async set(name: string, data: any, duration: number = 0): Promise { - if (name && data) { - return await super.set(name, this.serialize(data), duration) - } - } - - public async delete(name: string): Promise { - return await super.delete(name) - } - - public async update(name: string, data: any, duration: number): Promise { - if (await this.delete(name)) { - return await this.set(name, data, duration) - } else return await this.set(name, data, duration) - } - - public async flush(): Promise { - await super.flush() - } - - private serialize(data: any): any { - return JSON.stringify(data) - } - - private deserialize(data: any): any { - return JSON.parse(data) - } + constructor(app: any) { + super(app) + } + + public async get(name: string): Promise { + if (name) { + const value: string = await super.get(name) + if (value) { + return this.deserialize(value) + } + } + } + + public async has(name: string): Promise { + const value = await this.get(name) + return !value + } + + public async set(name: string, data: any, duration: number = 0): Promise { + if (name && data) { + return await super.set(name, this.serialize(data), duration) + } + } + + public async delete(name: string): Promise { + return await super.delete(name) + } + + public async update(name: string, data: any, duration: number): Promise { + if (await this.delete(name)) { + return await this.set(name, data, duration) + } else return await this.set(name, data, duration) + } + + public async flush(): Promise { + await super.flush() + } + + private serialize(data: any): any { + return JSON.stringify(data) + } + + private deserialize(data: any): any { + return JSON.parse(data) + } } module.exports = RedisCacheService diff --git a/tsconfig.json b/tsconfig.json index 30ec0c7..ce619d3 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,14 +1,13 @@ { - "extends": "./node_modules/@adonisjs/mrm-preset/_tsconfig", - "compilerOptions": { - "experimentalDecorators": true, - "emitDecoratorMetadata": true, - "skipLibCheck": true, - "useDefineForClassFields": true - }, - "files": [ - "./node_modules/@adonisjs/core/build/adonis-typings/index.d.ts", - "./node_modules/@adonisjs/redis/build/adonis-typings/index.d.ts", - "./adonis-typings/index.ts" - ] + "extends": "./node_modules/@adonisjs/mrm-preset/_tsconfig", + "compilerOptions": { + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "skipLibCheck": true + }, + "files": [ + "./node_modules/@adonisjs/core/build/adonis-typings/index.d.ts", + "./node_modules/@adonisjs/redis/build/adonis-typings/index.d.ts", + "./adonis-typings/index.ts" + ] }