Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin', 'import', '@stylistic/ts'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'plugin:sonarjs/recommended-legacy',
'plugin:import/recommended',
'plugin:import/typescript',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: [
'**/node_modules/*',
'dist',
'tests',
'scripts',
'resources',
'.dev',
'.devops',
'.debug',
],
rules: {
'no-console': 'error',
'@typescript-eslint/no-inferrable-types': 'error',
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'no-eval': 'error',
'no-implied-eval': 'error',
'prefer-promise-reject-errors': 'warn',
complexity: ['error', 20],
'import/no-unresolved': 'error',
'import/order': [
'error',
{
alphabetize: {
/* sort in ascending order. Options: ["ignore", "asc", "desc"] */
order: 'asc',
/* ignore case. Options: [true, false] */
caseInsensitive: true,
},
},
],
},
settings: {
'import/resolver': {
typescript: {
project: './tsconfig.json',
},
},
},
};
48 changes: 48 additions & 0 deletions .github/workflows/pull-requests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: "Code Quality Control Workflow"

on:
- pull_request

jobs:
code_quality_matrix:
strategy:
fail-fast: false
matrix:
cmd: ["format:check", "lint:check", "build"]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Cache node modules
id: cache-npm
uses: actions/cache@v4
env:
cache-name: cache-node-modules
with:
# npm cache files are stored in `~/.npm` on Linux/macOS
path: ~/.npm
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-

- if: ${{ steps.cache-npm.outputs.cache-hit != 'true' }}
name: List the state of node modules
continue-on-error: true
run: npm list

- name: "Install Node Modules"
run: npm install -D

- name: "Running ${{ matrix.cmd }}"
run: npm run ${{ matrix.cmd }}
continue-on-error: ${{ matrix.cmd == 'lint:check' }}

- name: Annotate Code Linting Results
if: ${{ matrix.cmd == 'lint:check' }}
uses: ataylorme/eslint-annotate-action@v3
with:
report-json: "eslint_report.json"
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ npm-debug.log
# dist
dist

# temporary reports
eslint_report.json

#yarn
.pnp.*
.yarn/*
Expand Down
8 changes: 8 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"arrowParens": "avoid"
}
Empty file removed CHANGELOG.md
Empty file.
6 changes: 3 additions & 3 deletions lib/cache/cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CacheDriver } from "./interfaces";
import { CacheService } from "./service";
import { genKeyFromObj } from "./utils/genKey";
import { CacheDriver } from './interfaces';
import { CacheService } from './service';
import { genKeyFromObj } from './utils/genKey';

export class Cache {
static store(store?: string): CacheDriver {
Expand Down
2 changes: 1 addition & 1 deletion lib/cache/constants.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const CACHE_OPTIONS = "_intentjs_cache_options__";
export const CACHE_OPTIONS = '_intentjs_cache_options__';
12 changes: 6 additions & 6 deletions lib/cache/drivers/inMemory.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { GenericFunction } from "../../interfaces";
import { Package } from "../../utils/packageLoader";
import { CacheDriver, InMemoryDriverOption } from "../interfaces";
import { GenericFunction } from '../../interfaces';
import { Package } from '../../utils/packageLoader';
import { CacheDriver, InMemoryDriverOption } from '../interfaces';

export class InMemoryDriver implements CacheDriver {
private client: any;

constructor(private options: InMemoryDriverOption) {
const NodeCache = Package.load("node-cache");
const NodeCache = Package.load('node-cache');

this.client = new NodeCache({ stdTTL: 100, checkperiod: 120 });
}
Expand All @@ -19,7 +19,7 @@ export class InMemoryDriver implements CacheDriver {
async set(
key: string,
value: string | Record<string, any>,
ttlInSec?: number | undefined
ttlInSec?: number | undefined,
): Promise<boolean> {
const cacheKey = `${this.options.prefix}:::${key}`;

Expand All @@ -38,7 +38,7 @@ export class InMemoryDriver implements CacheDriver {
async remember<T = any>(
key: string,
cb: GenericFunction,
ttlInSec: number
ttlInSec: number,
): Promise<T> {
const exists = await this.has(key);
if (exists) return this.get(key);
Expand Down
14 changes: 7 additions & 7 deletions lib/cache/drivers/redis.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { GenericFunction } from "../../interfaces";
import { Package } from "../../utils";
import { CacheDriver, RedisDriverOption } from "../interfaces";
import { GenericFunction } from '../../interfaces';
import { Package } from '../../utils';
import { CacheDriver, RedisDriverOption } from '../interfaces';

export class RedisDriver implements CacheDriver {
private client: any;

constructor(private options: RedisDriverOption) {
const IORedis = Package.load("ioredis");
const IORedis = Package.load('ioredis');
if (options.url) {
this.client = new IORedis(options.url, { db: options.database || 0 });
} else {
Expand All @@ -33,12 +33,12 @@ export class RedisDriver implements CacheDriver {
async set(
key: string,
value: string | number | Record<string, any>,
ttlInSec?: number
ttlInSec?: number,
): Promise<boolean> {
try {
const redisKey = `${this.options.prefix}:::${key}`;
ttlInSec
? await this.client.set(redisKey, JSON.stringify(value), "EX", ttlInSec)
? await this.client.set(redisKey, JSON.stringify(value), 'EX', ttlInSec)
: await this.client.set(redisKey, JSON.stringify(value));
return true;
} catch {
Expand All @@ -54,7 +54,7 @@ export class RedisDriver implements CacheDriver {
async remember<T = any>(
key: string,
cb: GenericFunction,
ttlInSec: number
ttlInSec: number,
): Promise<T> {
const value = await this.get(key);
if (value) return value;
Expand Down
6 changes: 3 additions & 3 deletions lib/cache/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from "./service";
export * from "./interfaces";
export * from "./cache";
export * from './service';
export * from './interfaces';
export * from './cache';
6 changes: 3 additions & 3 deletions lib/cache/interfaces/driver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GenericFunction } from "../../interfaces";
import { GenericFunction } from '../../interfaces';

export interface CacheDriver {
/**
Expand All @@ -16,7 +16,7 @@ export interface CacheDriver {
set(
key: string,
value: Record<string, any> | string,
ttlInSec?: number
ttlInSec?: number,
): Promise<boolean>;

/**
Expand All @@ -28,7 +28,7 @@ export interface CacheDriver {
remember<T = any>(
key: string,
cb: GenericFunction,
ttlInSec: number
ttlInSec: number,
): Promise<T>;

rememberForever<T = any>(key: string, cb: GenericFunction): Promise<T>;
Expand Down
4 changes: 2 additions & 2 deletions lib/cache/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from "./options";
export * from "./driver";
export * from './options';
export * from './driver';
8 changes: 4 additions & 4 deletions lib/cache/interfaces/options.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ModuleMetadata, Type } from "@nestjs/common";
import { ModuleMetadata, Type } from '@nestjs/common';

export interface RedisDriverOption {
driver: "redis";
driver: 'redis';
host?: string;
port?: number;
url?: string;
Expand All @@ -12,7 +12,7 @@ export interface RedisDriverOption {
}

export interface InMemoryDriverOption {
driver: "memory";
driver: 'memory';
prefix: string;
}

Expand All @@ -28,7 +28,7 @@ export interface CacheAsyncOptionsFactory {
createCacheOptions(): Promise<CacheOptions> | CacheOptions;
}

export interface CacheAsyncOptions extends Pick<ModuleMetadata, "imports"> {
export interface CacheAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
name?: string;
isGlobal: boolean;
useExisting?: Type<CacheOptions>;
Expand Down
24 changes: 12 additions & 12 deletions lib/cache/service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Injectable, OnModuleInit } from "@nestjs/common";
import { RedisDriver } from "./drivers/redis";
import { CacheDriver, CacheOptions } from "./interfaces";
import { InMemoryDriver } from "./drivers/inMemory";
import { InternalLogger } from "../utils/logger";
import { IntentConfig } from "../config/service";
import { logTime } from "../utils/helpers";
import { Injectable, OnModuleInit } from '@nestjs/common';
import { IntentConfig } from '../config/service';
import { logTime } from '../utils/helpers';
import { InternalLogger } from '../utils/logger';
import { InMemoryDriver } from './drivers/inMemory';
import { RedisDriver } from './drivers/redis';
import { CacheDriver, CacheOptions } from './interfaces';

@Injectable()
export class CacheService implements OnModuleInit {
Expand All @@ -13,7 +13,7 @@ export class CacheService implements OnModuleInit {
static stores: Record<string, CacheDriver>;

constructor(config: IntentConfig) {
CacheService.data = config.get("cache");
CacheService.data = config.get('cache');
}

onModuleInit() {
Expand All @@ -26,18 +26,18 @@ export class CacheService implements OnModuleInit {

if (!driver) {
InternalLogger.error(
"QueueService",
`We couldn't find any driver associated with the "${stores[store].driver}".`
'QueueService',
`We couldn't find any driver associated with the "${stores[store].driver}".`,
);
continue;
}

CacheService.stores[store] = new driver(stores[store] as never);
InternalLogger.success(
"CacheService",
'CacheService',
`Cache store [${
stores[store].driver
}] successfully initiailized ${logTime(Date.now() - time)}`
}] successfully initiailized ${logTime(Date.now() - time)}`,
);
}
}
Expand Down
13 changes: 6 additions & 7 deletions lib/cache/utils/genKey.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import { createHash } from "node:crypto";
import { Arr } from "../../utils/array";
import { createHash } from 'node:crypto';
import { Arr } from '../../utils/array';

export const genKeyFromObj = (
obj: Record<string, any>,
dontHash: boolean = false
dontHash = false,
): string => {
const keys = Object.keys(obj).sort();
const keyStr = [];
for (const key of keys) {
const values = Arr.isArray(obj[key]) ? obj[key].join(",") : obj[key];
const values = Arr.isArray(obj[key]) ? obj[key].join(',') : obj[key];
keyStr.push(`${key}[${values}]`);
}

const str = keyStr.join(",");
const str = keyStr.join(',');
if (str.length > 10000 && !dontHash) {
const hash = createHash("sha1").update(str).digest("hex");
return hash;
return createHash('sha1').update(str).digest('hex');
}

return str;
Expand Down
Loading