Skip to content

Commit

Permalink
Merge pull request #2 from Shahar-Y/develop
Browse files Browse the repository at this point in the history
V1.0.6 - Fix redis save and return type
  • Loading branch information
Shahar-Y authored Mar 14, 2022
2 parents 9082d51 + 9e7afea commit 941dfb3
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 67 deletions.
4 changes: 2 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}\\src\\index.ts",
"preLaunchTask": "npm: build-ts",
"program": "${workspaceFolder}\\src\\example\\example.ts",
"preLaunchTask": "npm: build",
"outFiles": ["${workspaceFolder}/**/*.js"]
}
]
Expand Down
15 changes: 15 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -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

7 changes: 7 additions & 0 deletions src/miscellaneous/docker-compose.yml → docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 7 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -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.5",
"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",
Expand Down
9 changes: 2 additions & 7 deletions src/defaults.ts
Original file line number Diff line number Diff line change
@@ -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: () => {},
};
12 changes: 6 additions & 6 deletions src/example/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import { defaults } from '../defaults';
import { TryCache } from '../index';

(async () => {
const cb = new TryCache(defaults.redis, { silent: false, expire: 20 });
cb.initTryCache();
const cb = new TryCache(defaults.redisConnectionString, { silent: false, expire: 20 });
await cb.initTryCache();

const waitMs = 2000;
const myKey = 'myKey';

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('************************************************************************');
Expand All @@ -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('************************************************************************');
Expand Down Expand Up @@ -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
Expand All @@ -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<void> {
Expand Down
12 changes: 6 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -7,10 +7,10 @@ export let logger: Logger;

export class TryCache {
options: TCOptions;
redisData: RedisDataType;
redisConnectionString: string;

constructor(redisData: RedisDataType, opts?: Partial<TCOptions>) {
this.redisData = redisData;
constructor(redisConnectionString: string, opts?: Partial<TCOptions>) {
this.redisConnectionString = redisConnectionString;
this.options = { ...defaults.defaultTCOptions, ...opts };
}

Expand All @@ -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');
}
Expand Down Expand Up @@ -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;
Expand Down
22 changes: 14 additions & 8 deletions src/infrastructure/redis.ts
Original file line number Diff line number Diff line change
@@ -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();

Expand All @@ -21,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<string | object | null> {
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;
}

/**
Expand All @@ -31,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);
Expand Down
8 changes: 0 additions & 8 deletions src/paramTypes.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
export type RedisDataType = {
host: string;
port: number;
password: string;
dbIndex: number;
};

export type TCOptions = {
silent: boolean;
prettify: boolean;
expire: number;
};

Expand Down
4 changes: 2 additions & 2 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
39 changes: 17 additions & 22 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand All @@ -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. */
Expand All @@ -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. */

Expand All @@ -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": []
}

0 comments on commit 941dfb3

Please sign in to comment.