plac-micro-common 1.1.13 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,16 @@
1
- export declare const REDIS_CLIENT = "REDIS_CLIENT";
1
+ export declare const REDIS_CLIENTS = "REDIS_CLIENTS";
2
+ /**
3
+ * Named client token helper (if you want to inject a specific client directly)
4
+ * Example: @Inject(getRedisClientToken('geo')) private geoRedis: Redis
5
+ */
6
+ export declare const getRedisClientToken: (name: string) => string;
7
+ /**
8
+ * Backward compatible tokens:
9
+ * - REDIS_CLIENT is the "main" redis client
10
+ * - REDIS_GEO_CLIENT is the "geo" redis client
11
+ */
12
+ export declare const REDIS_CLIENT: string;
13
+ export declare const REDIS_GEO_CLIENT: string;
2
14
  export type RedisModuleOptions = {
3
15
  url?: string;
4
16
  host?: string;
@@ -1,4 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.REDIS_CLIENT = void 0;
4
- exports.REDIS_CLIENT = "REDIS_CLIENT";
3
+ exports.REDIS_GEO_CLIENT = exports.REDIS_CLIENT = exports.getRedisClientToken = exports.REDIS_CLIENTS = void 0;
4
+ exports.REDIS_CLIENTS = "REDIS_CLIENTS";
5
+ /**
6
+ * Named client token helper (if you want to inject a specific client directly)
7
+ * Example: @Inject(getRedisClientToken('geo')) private geoRedis: Redis
8
+ */
9
+ const getRedisClientToken = (name) => `REDIS_CLIENT:${name}`;
10
+ exports.getRedisClientToken = getRedisClientToken;
11
+ /**
12
+ * Backward compatible tokens:
13
+ * - REDIS_CLIENT is the "main" redis client
14
+ * - REDIS_GEO_CLIENT is the "geo" redis client
15
+ */
16
+ exports.REDIS_CLIENT = (0, exports.getRedisClientToken)("main");
17
+ exports.REDIS_GEO_CLIENT = (0, exports.getRedisClientToken)("geo");
@@ -16,40 +16,92 @@ const config_1 = require("@nestjs/config");
16
16
  const ioredis_1 = __importDefault(require("ioredis"));
17
17
  const redis_constant_1 = require("./redis.constant");
18
18
  const redis_service_1 = require("./redis.service");
19
+ function parseNames(v) {
20
+ // default includes geo for backward compatibility with your existing code
21
+ const raw = (v ?? "main,geo")
22
+ .split(",")
23
+ .map((s) => s.trim())
24
+ .filter(Boolean);
25
+ // ensure unique
26
+ return Array.from(new Set(raw));
27
+ }
28
+ function upper(name) {
29
+ return name.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase();
30
+ }
19
31
  let RedisModule = RedisModule_1 = class RedisModule {
20
32
  static forRootAsync() {
21
33
  return {
22
34
  module: RedisModule_1,
23
35
  imports: [config_1.ConfigModule],
24
36
  providers: [
37
+ // 1) Build ALL clients from env and store as a map
25
38
  {
26
- provide: redis_constant_1.REDIS_CLIENT,
39
+ provide: redis_constant_1.REDIS_CLIENTS,
27
40
  inject: [config_1.ConfigService],
28
41
  useFactory: (config) => {
29
- const url = config.get("REDIS_URL");
30
- const keyPrefix = config.get("REDIS_KEY_PREFIX") || undefined;
31
- // Prefer REDIS_URL if present
32
- const client = url
33
- ? new ioredis_1.default(url, { keyPrefix })
34
- : new ioredis_1.default({
35
- host: config.get("REDIS_HOST"),
36
- port: config.get("REDIS_PORT"),
37
- password: config.get("REDIS_PASSWORD") || undefined,
38
- db: config.get("REDIS_DB") || 0,
39
- keyPrefix,
42
+ const names = parseNames(config.get("REDIS_NAMES"));
43
+ const baseUrl = config.get("REDIS_URL");
44
+ const baseHost = config.get("REDIS_HOST");
45
+ const basePort = config.get("REDIS_PORT");
46
+ const basePassword = config.get("REDIS_PASSWORD") || undefined;
47
+ const baseDb = config.get("REDIS_DB") ?? 0;
48
+ const baseKeyPrefix = config.get("REDIS_KEY_PREFIX") || undefined;
49
+ const map = {};
50
+ for (const name of names) {
51
+ const N = upper(name);
52
+ const url = config.get(`REDIS_${N}_URL`) ?? baseUrl;
53
+ const host = config.get(`REDIS_${N}_HOST`) ?? baseHost;
54
+ const port = config.get(`REDIS_${N}_PORT`) ?? basePort;
55
+ const password = config.get(`REDIS_${N}_PASSWORD`) ?? basePassword;
56
+ const db = config.get(`REDIS_${N}_DB`) ?? baseDb;
57
+ const keyPrefix = config.get(`REDIS_${N}_KEY_PREFIX`) ?? baseKeyPrefix;
58
+ const client = url
59
+ ? new ioredis_1.default(url, { keyPrefix })
60
+ : new ioredis_1.default({
61
+ host,
62
+ port,
63
+ password,
64
+ db,
65
+ keyPrefix,
66
+ });
67
+ client.on("error", (err) => {
68
+ // eslint-disable-next-line no-console
69
+ console.error(`[redis:${name}] error:`, err?.message || err);
40
70
  });
41
- // (Optional) basic visibility
42
- client.on("error", (err) => {
43
- // don’t throw here; just log
44
- // eslint-disable-next-line no-console
45
- console.error("[redis] error:", err?.message || err);
46
- });
47
- return client;
71
+ map[name] = client;
72
+ }
73
+ return map;
48
74
  },
49
75
  },
76
+ // 2) Provide each named token for DI (optional but useful)
77
+ // e.g. @Inject(getRedisClientToken('geo')) geoRedis: Redis
78
+ {
79
+ provide: (0, redis_constant_1.getRedisClientToken)("main"),
80
+ inject: [redis_constant_1.REDIS_CLIENTS],
81
+ useFactory: (clients) => {
82
+ if (!clients.main)
83
+ throw new Error(`[redis] missing client "main" (check REDIS_NAMES)`);
84
+ return clients.main;
85
+ },
86
+ },
87
+ {
88
+ provide: (0, redis_constant_1.getRedisClientToken)("geo"),
89
+ inject: [redis_constant_1.REDIS_CLIENTS],
90
+ useFactory: (clients) => {
91
+ if (!clients.geo)
92
+ throw new Error(`[redis] missing client "geo" (check REDIS_NAMES)`);
93
+ return clients.geo;
94
+ },
95
+ },
96
+ // 3) Service uses the map; you can use any client name dynamically
97
+ redis_service_1.RedisService,
98
+ ],
99
+ exports: [
100
+ redis_constant_1.REDIS_CLIENTS,
50
101
  redis_service_1.RedisService,
102
+ (0, redis_constant_1.getRedisClientToken)("main"),
103
+ (0, redis_constant_1.getRedisClientToken)("geo"),
51
104
  ],
52
- exports: [redis_constant_1.REDIS_CLIENT, redis_service_1.RedisService],
53
105
  };
54
106
  }
55
107
  };
@@ -1,13 +1,18 @@
1
1
  import { OnModuleDestroy } from "@nestjs/common";
2
2
  import { Redis } from "ioredis";
3
+ type RedisClientMap = Record<string, Redis>;
3
4
  export declare class RedisService implements OnModuleDestroy {
4
- private readonly redis;
5
- constructor(redis: Redis);
6
- get(key: string): Promise<string | null>;
7
- del(key: string): Promise<number>;
8
- exists(key: string): Promise<number>;
9
- getJson<T>(key: string): Promise<T | null>;
10
- setJson(key: string, value: unknown, ttlSeconds?: number): Promise<"OK">;
11
- client(): Redis;
5
+ private readonly clients;
6
+ constructor(clients: RedisClientMap);
7
+ private pick;
8
+ get(key: string, clientName?: string): Promise<string | null>;
9
+ del(key: string, clientName?: string): Promise<number>;
10
+ exists(key: string, clientName?: string): Promise<number>;
11
+ client(clientName?: string): Redis;
12
+ getJson<T>(key: string, clientName?: string): Promise<T | null>;
13
+ setJson(key: string, value: unknown, ttlSeconds?: number, clientName?: string): Promise<"OK">;
14
+ getGeoJson<T>(key: string): Promise<T | null>;
15
+ setGeoJson(key: string, value: unknown, ttlSeconds?: number): Promise<"OK">;
12
16
  onModuleDestroy(): Promise<void>;
13
17
  }
18
+ export {};
@@ -14,25 +14,35 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.RedisService = void 0;
16
16
  const common_1 = require("@nestjs/common");
17
- const ioredis_1 = require("ioredis");
18
17
  const redis_constant_1 = require("./redis.constant");
19
18
  let RedisService = class RedisService {
20
- constructor(redis) {
21
- this.redis = redis;
19
+ constructor(clients) {
20
+ this.clients = clients;
22
21
  }
23
- // Raw helpers
24
- get(key) {
25
- return this.redis.get(key);
22
+ pick(name = "main") {
23
+ const client = this.clients[name];
24
+ if (!client) {
25
+ const available = Object.keys(this.clients).join(", ");
26
+ throw new Error(`[redis] client "${name}" not found. Available: ${available}`);
27
+ }
28
+ return client;
29
+ }
30
+ // -------------------- RAW --------------------
31
+ get(key, clientName = "main") {
32
+ return this.pick(clientName).get(key);
26
33
  }
27
- del(key) {
28
- return this.redis.del(key);
34
+ del(key, clientName = "main") {
35
+ return this.pick(clientName).del(key);
29
36
  }
30
- exists(key) {
31
- return this.redis.exists(key);
37
+ exists(key, clientName = "main") {
38
+ return this.pick(clientName).exists(key);
32
39
  }
33
- // JSON helpers (most common use)
34
- async getJson(key) {
35
- const val = await this.redis.get(key);
40
+ client(clientName = "main") {
41
+ return this.pick(clientName);
42
+ }
43
+ // -------------------- JSON --------------------
44
+ async getJson(key, clientName = "main") {
45
+ const val = await this.pick(clientName).get(key);
36
46
  if (!val)
37
47
  return null;
38
48
  try {
@@ -42,31 +52,36 @@ let RedisService = class RedisService {
42
52
  return null;
43
53
  }
44
54
  }
45
- async setJson(key, value, ttlSeconds) {
55
+ async setJson(key, value, ttlSeconds, clientName = "main") {
46
56
  const payload = JSON.stringify(value);
47
- if (ttlSeconds && ttlSeconds > 0) {
48
- return this.redis.set(key, payload, "EX", ttlSeconds);
49
- }
50
- return this.redis.set(key, payload);
57
+ const c = this.pick(clientName);
58
+ if (ttlSeconds && ttlSeconds > 0)
59
+ return c.set(key, payload, "EX", ttlSeconds);
60
+ return c.set(key, payload);
51
61
  }
52
- // Optional: if you need access to ioredis commands directly
53
- client() {
54
- return this.redis;
62
+ // Backward-compat convenience (optional)
63
+ async getGeoJson(key) {
64
+ return this.getJson(key, "geo");
65
+ }
66
+ async setGeoJson(key, value, ttlSeconds) {
67
+ return this.setJson(key, value, ttlSeconds, "geo");
55
68
  }
56
69
  async onModuleDestroy() {
57
- // Graceful shutdown
58
- try {
59
- await this.redis.quit();
60
- }
61
- catch {
62
- // fallback
63
- this.redis.disconnect();
70
+ // Graceful shutdown for ALL clients
71
+ const list = Object.values(this.clients);
72
+ for (const c of list) {
73
+ try {
74
+ await c.quit();
75
+ }
76
+ catch {
77
+ c.disconnect();
78
+ }
64
79
  }
65
80
  }
66
81
  };
67
82
  exports.RedisService = RedisService;
68
83
  exports.RedisService = RedisService = __decorate([
69
84
  (0, common_1.Injectable)(),
70
- __param(0, (0, common_1.Inject)(redis_constant_1.REDIS_CLIENT)),
71
- __metadata("design:paramtypes", [ioredis_1.Redis])
85
+ __param(0, (0, common_1.Inject)(redis_constant_1.REDIS_CLIENTS)),
86
+ __metadata("design:paramtypes", [Object])
72
87
  ], RedisService);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plac-micro-common",
3
- "version": "1.1.13",
3
+ "version": "1.2.0",
4
4
  "types": "dist/index.d.ts",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {