From 341eb9206f56a6fe52317426124213235bdab3af Mon Sep 17 00:00:00 2001 From: shahar-y Date: Sun, 13 Mar 2022 17:07:51 +0300 Subject: [PATCH 1/8] fixing types --- .vscode/launch.json | 2 +- package.json | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index df7339a..6ab9148 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,7 +10,7 @@ "name": "Launch Program", "skipFiles": ["/**"], "program": "${workspaceFolder}\\src\\index.ts", - "preLaunchTask": "npm: build-ts", + "preLaunchTask": "npm: build", "outFiles": ["${workspaceFolder}/**/*.js"] } ] diff --git a/package.json b/package.json index 1677353..f494432 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,15 @@ { "name": "try-cache", "description": "An auto-caching npm package for super-fast retrieval of less-consistant data", - "version": "1.0.0", - "main": "index.js", + "version": "1.0.1", + "main": "dist/index.js", + "types": "dist/index.d.ts", "scripts": { "start": "tsc && npm run serve", - "serve": "node lib/index.js", - "example": "tsc -p . && node lib/example/example.js", - "build-ts": "tsc" + "serve": "node dist/index.js", + "example": "tsc -p . && node dist/example/example.js", + "build": "tsc", + "prepublish": "tsc" }, "repository": { "type": "git", From 25f950e651d2e46667a0768250b2982e9020fc4f Mon Sep 17 00:00:00 2001 From: shahar-y Date: Sun, 13 Mar 2022 17:09:09 +0300 Subject: [PATCH 2/8] update lock --- package-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index a3089f4..48ef751 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "try-cache", - "version": "1.0.0", + "version": "1.0.1", "lockfileVersion": 1, "requires": true, "dependencies": { From 838a62a2f624c9b6944e69e051a1067dfddcfb01 Mon Sep 17 00:00:00 2001 From: shahar-y Date: Sun, 13 Mar 2022 17:09:19 +0300 Subject: [PATCH 3/8] 1.0.2 --- package-lock.json | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index 48ef751..50c3eb8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "try-cache", - "version": "1.0.1", + "version": "1.0.2", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index f494432..24c557d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "try-cache", "description": "An auto-caching npm package for super-fast retrieval of less-consistant data", - "version": "1.0.1", + "version": "1.0.2", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { From ce7e1b69b3eb870e6e1b9ace3b488148495201fa Mon Sep 17 00:00:00 2001 From: shahar-y Date: Sun, 13 Mar 2022 17:16:46 +0300 Subject: [PATCH 4/8] fix outdir --- tsconfig.json | 39 +++++++++++++++++---------------------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/tsconfig.json b/tsconfig.json index a2f7f9b..4a3fc25 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,17 +4,17 @@ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ - "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, + "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ + "declaration": true /* Generates corresponding '.d.ts' file. */, + "declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */, + "sourceMap": true /* Generates corresponding '.map' file. */, // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "lib", /* Redirect output structure to the directory. */ + "outDir": "dist" /* Redirect output structure to the directory. */, // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ @@ -25,8 +25,8 @@ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + "strict": true /* Enable all strict type-checking options. */, + "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ @@ -41,19 +41,16 @@ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ - "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, + "baseUrl": "./" /* Base directory to resolve non-absolute module names. */, "paths": { - "*": [ - "node_modules/*", - "src/types/*" - ] - }, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + "*": ["node_modules/*", "src/types/*"] + } /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */, // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ @@ -68,11 +65,9 @@ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ - }, - "include": [ - "src/*", "src/**/*", ".eslintrc.js" - ], + "skipLibCheck": true /* Skip type checking of declaration files. */, + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + }, + "include": ["src/*", "src/**/*", ".eslintrc.js"], "exclude": [] } From 523f893812eca34c6a171c1ac178bf7c26513269 Mon Sep 17 00:00:00 2001 From: shahar-y Date: Sun, 13 Mar 2022 17:16:57 +0300 Subject: [PATCH 5/8] 1.0.4 --- package-lock.json | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index 50c3eb8..de18e2a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "try-cache", - "version": "1.0.2", + "version": "1.0.4", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 24c557d..33ee20e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "try-cache", "description": "An auto-caching npm package for super-fast retrieval of less-consistant data", - "version": "1.0.2", + "version": "1.0.4", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { From 1e551b7b80dff6cd37d10f0719b872257354341a Mon Sep 17 00:00:00 2001 From: shahar-y Date: Sun, 13 Mar 2022 20:32:37 +0300 Subject: [PATCH 6/8] fixed connection url --- Dockerfile | 15 +++++++++++++++ .../docker-compose.yml => docker-compose.yml | 7 +++++++ src/defaults.ts | 9 ++------- src/example/example.ts | 2 +- src/index.ts | 10 +++++----- src/infrastructure/redis.ts | 7 ++++--- src/paramTypes.ts | 8 -------- 7 files changed, 34 insertions(+), 24 deletions(-) create mode 100644 Dockerfile rename src/miscellaneous/docker-compose.yml => docker-compose.yml (63%) diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..254475c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM node:14-alpine as BUILD +WORKDIR /app +COPY package*.json ./ +RUN npm install +COPY . . +RUN npm run build + +FROM node:14-alpine as PROD +WORKDIR /app +COPY --from=BUILD /app/package*.json ./ +COPY --from=BUILD app/dist ./dist +RUN npm install +ENTRYPOINT ["node", "/app/dist/index.js"] +EXPOSE 3000 + diff --git a/src/miscellaneous/docker-compose.yml b/docker-compose.yml similarity index 63% rename from src/miscellaneous/docker-compose.yml rename to docker-compose.yml index 802a8d9..108b2c0 100644 --- a/src/miscellaneous/docker-compose.yml +++ b/docker-compose.yml @@ -6,4 +6,11 @@ services: - '6379:6379' expose: - 6379 + + try-cache: + container_name: try-cache + build: . + ports: + - '3000:3000' + restart: always # docker-compose -f "src\miscellaneous\docker-compose.yml" up -d --build diff --git a/src/defaults.ts b/src/defaults.ts index 1392b69..70458dc 100644 --- a/src/defaults.ts +++ b/src/defaults.ts @@ -1,15 +1,10 @@ import { TCOptions } from './paramTypes'; // Default variables -const defaultTCOptions: TCOptions = { silent: true, prettify: true, expire: 5 * 60 }; +const defaultTCOptions: TCOptions = { silent: true, expire: 5 * 60 }; export const defaults = { - redis: { - port: 6379, - host: 'localhost', - dbIndex: 0, - password: '', - }, defaultTCOptions: defaultTCOptions, + redisConnectionString: 'redis://localhost:6379', defaultCallbackFunction: () => {}, }; diff --git a/src/example/example.ts b/src/example/example.ts index b902457..35f3f6c 100644 --- a/src/example/example.ts +++ b/src/example/example.ts @@ -3,7 +3,7 @@ import { defaults } from '../defaults'; import { TryCache } from '../index'; (async () => { - const cb = new TryCache(defaults.redis, { silent: false, expire: 20 }); + const cb = new TryCache(defaults.redisConnectionString, { silent: false, expire: 20 }); cb.initTryCache(); const waitMs = 2000; diff --git a/src/index.ts b/src/index.ts index b963450..1154f33 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import { TCOptions, RedisDataType, OperationOptions } from './paramTypes'; +import { TCOptions, OperationOptions } from './paramTypes'; import { Redis } from './infrastructure/redis'; import Logger, { criticalLog } from './utils/logger'; import { defaults } from './defaults'; @@ -7,10 +7,10 @@ export let logger: Logger; export class TryCache { options: TCOptions; - redisData: RedisDataType; + redisConnectionString: string; - constructor(redisData: RedisDataType, opts?: Partial) { - this.redisData = redisData; + constructor(redisConnectionString: string, opts?: Partial) { + this.redisConnectionString = redisConnectionString; this.options = { ...defaults.defaultTCOptions, ...opts }; } @@ -23,7 +23,7 @@ export class TryCache { logger = new Logger(this.options); // Init redis connection - Redis.connect(this.redisData); + Redis.connect(this.redisConnectionString); logger.log('successful connection to redis'); } diff --git a/src/infrastructure/redis.ts b/src/infrastructure/redis.ts index fc1bebe..79843a5 100644 --- a/src/infrastructure/redis.ts +++ b/src/infrastructure/redis.ts @@ -1,12 +1,13 @@ import * as redis from 'redis'; -import { RedisDataType } from '../paramTypes'; import { logger } from '../index'; export class Redis { static client: redis.RedisClientType; - static async connect(redisData: RedisDataType) { - this.client = redis.createClient(redisData); + static async connect(redisConnectionString: string) { + this.client = redis.createClient({ + url: redisConnectionString, + }); await this.client.connect(); diff --git a/src/paramTypes.ts b/src/paramTypes.ts index 3558d67..1a6b589 100644 --- a/src/paramTypes.ts +++ b/src/paramTypes.ts @@ -1,13 +1,5 @@ -export type RedisDataType = { - host: string; - port: number; - password: string; - dbIndex: number; -}; - export type TCOptions = { silent: boolean; - prettify: boolean; expire: number; }; From 8027dae9ffe970c26694785db506248d1751ab14 Mon Sep 17 00:00:00 2001 From: shahar-y Date: Sun, 13 Mar 2022 20:32:51 +0300 Subject: [PATCH 7/8] 1.0.5 --- package-lock.json | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index de18e2a..4e44e68 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "try-cache", - "version": "1.0.4", + "version": "1.0.5", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 33ee20e..939cde5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "try-cache", "description": "An auto-caching npm package for super-fast retrieval of less-consistant data", - "version": "1.0.4", + "version": "1.0.5", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { From 9e7afeafc89903598323ada0c42e636618c70f04 Mon Sep 17 00:00:00 2001 From: shahar-y Date: Mon, 14 Mar 2022 18:03:38 +0300 Subject: [PATCH 8/8] Fixed redis return type --- .vscode/launch.json | 2 +- src/example/example.ts | 10 +++++----- src/index.ts | 2 +- src/infrastructure/redis.ts | 15 ++++++++++----- src/utils/logger.ts | 4 ++-- 5 files changed, 19 insertions(+), 14 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 6ab9148..920e53b 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -9,7 +9,7 @@ "request": "launch", "name": "Launch Program", "skipFiles": ["/**"], - "program": "${workspaceFolder}\\src\\index.ts", + "program": "${workspaceFolder}\\src\\example\\example.ts", "preLaunchTask": "npm: build", "outFiles": ["${workspaceFolder}/**/*.js"] } diff --git a/src/example/example.ts b/src/example/example.ts index 35f3f6c..16b4e5d 100644 --- a/src/example/example.ts +++ b/src/example/example.ts @@ -4,7 +4,7 @@ import { TryCache } from '../index'; (async () => { const cb = new TryCache(defaults.redisConnectionString, { silent: false, expire: 20 }); - cb.initTryCache(); + await cb.initTryCache(); const waitMs = 2000; const myKey = 'myKey'; @@ -12,7 +12,7 @@ import { TryCache } from '../index'; console.log('Retrieving data for the first time'); console.time('1st run time taken'); const res1 = await cb.tryCache(myKey, () => dummyDB(2, 7, false)); - console.log(`First time result: ${res1}`); + console.log('First time result:', res1); console.timeEnd('1st run time taken'); console.log('************************************************************************'); @@ -21,7 +21,7 @@ import { TryCache } from '../index'; await sleep(waitMs); console.time('2nd run time taken'); const res2 = await cb.tryCache(myKey, () => dummyDB(2, 7, false)); - console.log(`Second time result: ${res2}`); + console.log('Second time result:', res2); console.timeEnd('2nd run time taken'); console.log('************************************************************************'); @@ -50,7 +50,7 @@ import { TryCache } from '../index'; callbackFunction: () => console.log('Callback function called'), }); console.timeEnd('4th run time taken'); - console.log(`Fourth time result: ${res4}`); + console.log('Fourth time result:', res4); })(); // simulate a database call @@ -59,7 +59,7 @@ async function dummyDB(x: number, y: number, shouldFail: boolean) { if (shouldFail) { throw new Error('Failed Successfully'); } - return x + y; + return { x, y }; } function sleep(ms: number): Promise { diff --git a/src/index.ts b/src/index.ts index 1154f33..389b960 100644 --- a/src/index.ts +++ b/src/index.ts @@ -51,7 +51,7 @@ export class TryCache { * @param expire - the expire time in seconds. * @returns - null. */ - async safeSetCache(key: string, value: string, expire?: number) { + async safeSetCache(key: string, value: string | object, expire?: number) { try { const res = await Redis.setKey(key, value, expire); return res; diff --git a/src/infrastructure/redis.ts b/src/infrastructure/redis.ts index 79843a5..76a6810 100644 --- a/src/infrastructure/redis.ts +++ b/src/infrastructure/redis.ts @@ -22,8 +22,13 @@ export class Redis { * getKey - gets a value from redis by a given key. * @param key - the key to get. */ - static async getKey(key: string) { - return await this.client.get(key); + static async getKey(key: string): Promise { + const value: string | null = await this.client.get(key); + if (!value) return null; + + const fixedValue: string = value.toString(); + const parsedValue = JSON.parse(fixedValue); + return parsedValue.TCValue; } /** @@ -32,9 +37,9 @@ export class Redis { * @param value - the value to set * @param expire - the expire time in seconds */ - static async setKey(key: string, value: string, expire?: number) { - logger.log(`Setting ${key} to ${value} with expire ${expire}`); - await this.client.set(key, value); + static async setKey(key: string, value: string | object, expire?: number) { + logger.log(`Setting ${key} with expire ${expire} to`, value); + await this.client.set(key, JSON.stringify({ TCValue: value })); if (expire) { await this.client.expire(key, expire); diff --git a/src/utils/logger.ts b/src/utils/logger.ts index 4d3f60c..320c49f 100644 --- a/src/utils/logger.ts +++ b/src/utils/logger.ts @@ -13,7 +13,7 @@ export default class Logger { this.options = options; } - log(message: string | object): void { - if (!this.options.silent) console.log(prefixLog, message); + log(message: string | object, ...args: any): void { + if (!this.options.silent) console.log(prefixLog, message, ...args); } }