redis-wizard 0.0.1

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.
package/README.md ADDED
File without changes
package/index.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Redis Wizard 설정
3
+ */
4
+ export interface RedisWizardConfig {
5
+ /** 테이블/스코프 프리픽스 (예: "draft:applications") */
6
+ table: string;
7
+ /** 기본 캐시 만료 시간(초), 지정하지 않으면 만료 시간 없음 */
8
+ cacheExpired?: number;
9
+ }
10
+ /**
11
+ * Redis Wizard 인스턴스 인터페이스
12
+ */
13
+ export interface RedisWizard<T = any> {
14
+ /**
15
+ * 키에 해당하는 값을 조회합니다.
16
+ * @param key - 조회할 키 (table 프리픽스는 자동 추가)
17
+ * @returns 값이 존재하면 파싱된 객체, 없으면 null
18
+ */
19
+ read(key: string): Promise<T | null>;
20
+ /**
21
+ * 키-값 쌍을 저장합니다.
22
+ * @param key - 저장할 키 (table 프리픽스는 자동 추가)
23
+ * @param value - 저장할 값 (객체는 자동 직렬화)
24
+ * @param expireSeconds - 만료 시간(초), 지정하지 않으면 config.cacheExpired 사용
25
+ */
26
+ create(key: string, value: T, expireSeconds?: number): Promise<void>;
27
+ /**
28
+ * 키의 값을 부분 업데이트합니다.
29
+ * @param key - 업데이트할 키 (table 프리픽스는 자동 추가)
30
+ * @param partial - 업데이트할 부분 값
31
+ * @param expireSeconds - 만료 시간(초), 지정하지 않으면 config.cacheExpired 사용
32
+ * @returns 업데이트된 값, 키가 존재하지 않으면 null
33
+ */
34
+ update(key: string, partial: Partial<T>, expireSeconds?: number): Promise<T | null>;
35
+ /**
36
+ * 키를 삭제합니다.
37
+ * @param key - 삭제할 키 (table 프리픽스는 자동 추가)
38
+ * @returns 삭제 성공 여부
39
+ */
40
+ delete(key: string): Promise<boolean>;
41
+ /**
42
+ * 키의 존재 여부를 확인합니다.
43
+ * @param key - 확인할 키 (table 프리픽스는 자동 추가)
44
+ * @returns 키가 존재하면 true
45
+ */
46
+ exists(key: string): Promise<boolean>;
47
+ /**
48
+ * 키의 만료 시간을 설정합니다.
49
+ * @param key - 만료 시간을 설정할 키 (table 프리픽스는 자동 추가)
50
+ * @param seconds - 만료 시간(초), 지정하지 않으면 config.cacheExpired 사용
51
+ * @returns 설정 성공 여부
52
+ */
53
+ setExpire(key: string, seconds?: number): Promise<boolean>;
54
+ /**
55
+ * 키의 남은 만료 시간을 조회합니다.
56
+ * @param key - 조회할 키 (table 프리픽스는 자동 추가)
57
+ * @returns 남은 만료 시간(초), 만료 시간이 없으면 null
58
+ */
59
+ getTtl(key: string): Promise<number | null>;
60
+ }
61
+ /**
62
+ * Redis Wizard 인스턴스를 생성합니다.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * interface Application {
67
+ * id: string;
68
+ * title: string;
69
+ * status: 'draft' | 'published';
70
+ * }
71
+ *
72
+ * const redis = createRedis<Application>({
73
+ * table: "draft:applications",
74
+ * cacheExpired: 10000,
75
+ * });
76
+ *
77
+ * await redis.create("app-123", { id: "app-123", title: "My App", status: "draft" });
78
+ * const app = await redis.read("app-123");
79
+ * await redis.update("app-123", { status: "published" });
80
+ * await redis.delete("app-123");
81
+ * ```
82
+ *
83
+ * @param config - Redis Wizard 설정
84
+ * @returns Redis Wizard 인스턴스
85
+ */
86
+ export declare function createRedis<T = any>(config: RedisWizardConfig): RedisWizard<T>;
87
+ export { disconnect } from "./services/config";
88
+ export { getRedisClient } from "./services/config";
package/index.js ADDED
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getRedisClient = exports.disconnect = void 0;
4
+ exports.createRedis = createRedis;
5
+ const read_1 = require("./services/read");
6
+ const create_1 = require("./services/create");
7
+ const update_1 = require("./services/update");
8
+ const delete_1 = require("./services/delete");
9
+ const exists_1 = require("./services/exists");
10
+ const setExpire_1 = require("./services/setExpire");
11
+ const getTtl_1 = require("./services/getTtl");
12
+ /**
13
+ * Redis Wizard 인스턴스를 생성합니다.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * interface Application {
18
+ * id: string;
19
+ * title: string;
20
+ * status: 'draft' | 'published';
21
+ * }
22
+ *
23
+ * const redis = createRedis<Application>({
24
+ * table: "draft:applications",
25
+ * cacheExpired: 10000,
26
+ * });
27
+ *
28
+ * await redis.create("app-123", { id: "app-123", title: "My App", status: "draft" });
29
+ * const app = await redis.read("app-123");
30
+ * await redis.update("app-123", { status: "published" });
31
+ * await redis.delete("app-123");
32
+ * ```
33
+ *
34
+ * @param config - Redis Wizard 설정
35
+ * @returns Redis Wizard 인스턴스
36
+ */
37
+ function createRedis(config) {
38
+ const { table, cacheExpired } = config;
39
+ return {
40
+ async read(key) {
41
+ return await (0, read_1.read)(table, key);
42
+ },
43
+ async create(key, value, expireSeconds) {
44
+ await (0, create_1.create)(table, key, value, expireSeconds ?? cacheExpired);
45
+ },
46
+ async update(key, partial, expireSeconds) {
47
+ return await (0, update_1.update)(table, key, partial, expireSeconds ?? cacheExpired);
48
+ },
49
+ async delete(key) {
50
+ return await (0, delete_1.deleteKey)(table, key);
51
+ },
52
+ async exists(key) {
53
+ return await (0, exists_1.exists)(table, key);
54
+ },
55
+ async setExpire(key, seconds) {
56
+ const expireSeconds = seconds ?? cacheExpired;
57
+ if (expireSeconds === undefined) {
58
+ throw new Error("만료 시간을 지정해야 합니다. createRedis의 cacheExpired 설정 또는 seconds 파라미터를 제공하세요.");
59
+ }
60
+ return await (0, setExpire_1.setExpire)(table, key, expireSeconds);
61
+ },
62
+ async getTtl(key) {
63
+ return await (0, getTtl_1.getTtl)(table, key);
64
+ },
65
+ };
66
+ }
67
+ // Redis 연결 관리 함수 export
68
+ var config_1 = require("./services/config");
69
+ Object.defineProperty(exports, "disconnect", { enumerable: true, get: function () { return config_1.disconnect; } });
70
+ var config_2 = require("./services/config");
71
+ Object.defineProperty(exports, "getRedisClient", { enumerable: true, get: function () { return config_2.getRedisClient; } });
package/package.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "redis-wizard",
3
+ "description": "A modern TypeScript-based Redis database utility package that provides an enhanced wrapper around the redis library, offering simplified database operations with elegant chainable queries.",
4
+ "version": "0.0.1",
5
+ "main": "index.js",
6
+ "scripts": {},
7
+ "author": "park-minhyeong",
8
+ "license": "MIT",
9
+ "dependencies": {
10
+ "redis": "^5.10.0",
11
+ "nodemon": "^3.1.10",
12
+ "tspec": "^0.1.116"
13
+ },
14
+ "devDependencies": {}
15
+ }
@@ -0,0 +1,41 @@
1
+ import { type RedisClientType } from "redis";
2
+ /**
3
+ * Redis 연결 풀 설정
4
+ */
5
+ export interface RedisPoolConfig {
6
+ /** 연결 타임아웃 (밀리초), 기본값: 10000 */
7
+ connectTimeout?: number;
8
+ /** 연결 유지 활성화 여부, 기본값: true */
9
+ keepAlive?: boolean;
10
+ /** 연결 유지 초기 지연 시간 (밀리초), 기본값: 0 */
11
+ keepAliveInitialDelay?: number;
12
+ /** 재연결 전략: false(재연결 안함), number(밀리초 지연), function(재연결 전략 함수) */
13
+ reconnectStrategy?: false | number | ((retries: number) => number | Error);
14
+ /** 지연 연결 (true면 connect() 호출 시 연결), 기본값: false */
15
+ lazyConnect?: boolean;
16
+ /** 최대 재연결 시도 횟수, 기본값: 10 */
17
+ maxRetriesPerRequest?: number;
18
+ }
19
+ /**
20
+ * Redis 클라이언트가 연결되어 있는지 확인합니다.
21
+ * 연결되어 있지 않으면 자동으로 연결을 시도합니다.
22
+ *
23
+ * @param {RedisPoolConfig} [poolConfig] - 연결 풀 설정 (선택사항, 초기화 시에만 적용)
24
+ * @returns {Promise<RedisClientType>} 연결된 Redis 클라이언트
25
+ * @throws {Error} Redis 클라이언트가 초기화되지 않았거나 연결에 실패한 경우
26
+ */
27
+ export declare const getRedisClient: (poolConfig?: RedisPoolConfig) => Promise<RedisClientType>;
28
+ /**
29
+ * Redis 연결 풀 설정을 업데이트합니다.
30
+ * 이미 연결된 경우에는 재연결이 필요할 수 있습니다.
31
+ *
32
+ * @param {RedisPoolConfig} poolConfig - 새로운 연결 풀 설정
33
+ * @returns {Promise<void>}
34
+ */
35
+ export declare const configurePool: (poolConfig: RedisPoolConfig) => Promise<void>;
36
+ /**
37
+ * Redis 연결을 종료합니다.
38
+ *
39
+ * @returns {Promise<void>}
40
+ */
41
+ export declare const disconnect: () => Promise<void>;
@@ -0,0 +1,222 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.disconnect = exports.configurePool = exports.getRedisClient = void 0;
4
+ const redis_1 = require("redis");
5
+ /**
6
+ * Redis 클라이언트 인스턴스
7
+ * @private
8
+ */
9
+ let redisClient = null;
10
+ /**
11
+ * Redis 연결 상태
12
+ * @private
13
+ */
14
+ let isConnected = false;
15
+ /**
16
+ * 환경 변수에서 연결 풀 설정을 읽어옵니다.
17
+ * @returns {RedisPoolConfig} 연결 풀 설정
18
+ */
19
+ const getPoolConfigFromEnv = () => {
20
+ const config = {};
21
+ if (process.env.REDIS_CONNECT_TIMEOUT) {
22
+ config.connectTimeout = parseInt(process.env.REDIS_CONNECT_TIMEOUT, 10);
23
+ }
24
+ if (process.env.REDIS_KEEP_ALIVE !== undefined) {
25
+ config.keepAlive = process.env.REDIS_KEEP_ALIVE === "true";
26
+ }
27
+ if (process.env.REDIS_KEEP_ALIVE_DELAY) {
28
+ config.keepAliveInitialDelay = parseInt(process.env.REDIS_KEEP_ALIVE_DELAY, 10);
29
+ }
30
+ if (process.env.REDIS_LAZY_CONNECT === "true") {
31
+ config.lazyConnect = true;
32
+ }
33
+ if (process.env.REDIS_MAX_RETRIES) {
34
+ config.maxRetriesPerRequest = parseInt(process.env.REDIS_MAX_RETRIES, 10);
35
+ }
36
+ return config;
37
+ };
38
+ /**
39
+ * Redis 클라이언트를 초기화하고 연결합니다.
40
+ * 환경 변수 REDIS_URL이 설정되어 있으면 해당 URL을 사용하고,
41
+ * 없으면 기본값 'redis://localhost:6379'를 사용합니다.
42
+ * 연결 풀 설정은 환경 변수 또는 poolConfig 파라미터로 지정할 수 있습니다.
43
+ *
44
+ * @param {RedisPoolConfig} [poolConfig] - 연결 풀 설정 (선택사항)
45
+ * @throws {Error} Redis 연결에 실패한 경우
46
+ */
47
+ const initializeRedis = async (poolConfig) => {
48
+ const redisUrl = process.env.REDIS_PORT ? `redis://localhost:${process.env.REDIS_PORT}` : process.env.REDIS_URL;
49
+ if (!redisUrl) {
50
+ const error = new Error("Redis configuration error: REDIS_URL or REDIS_PORT environment variable is not set");
51
+ console.error("[Redis Config] Initialization failed:", error.message);
52
+ throw error;
53
+ }
54
+ if (redisClient && isConnected) {
55
+ console.log("[Redis Config] Client already connected, skipping initialization");
56
+ return;
57
+ }
58
+ // 환경 변수에서 연결 풀 설정 읽기
59
+ const envPoolConfig = getPoolConfigFromEnv();
60
+ // 파라미터와 환경 변수 설정 병합 (파라미터 우선)
61
+ const finalPoolConfig = {
62
+ connectTimeout: 10000,
63
+ keepAlive: true,
64
+ keepAliveInitialDelay: 0,
65
+ lazyConnect: false,
66
+ maxRetriesPerRequest: 10,
67
+ ...envPoolConfig,
68
+ ...poolConfig,
69
+ };
70
+ const socketConfig = {
71
+ connectTimeout: finalPoolConfig.connectTimeout,
72
+ };
73
+ if (finalPoolConfig.keepAlive !== undefined) {
74
+ socketConfig.keepAlive = finalPoolConfig.keepAlive;
75
+ }
76
+ if (finalPoolConfig.keepAliveInitialDelay !== undefined) {
77
+ socketConfig.keepAliveInitialDelay = finalPoolConfig.keepAliveInitialDelay;
78
+ }
79
+ if (finalPoolConfig.reconnectStrategy !== undefined) {
80
+ socketConfig.reconnectStrategy = finalPoolConfig.reconnectStrategy;
81
+ }
82
+ else {
83
+ socketConfig.reconnectStrategy = (retries) => {
84
+ if (retries > 10) {
85
+ return new Error("Too many reconnection attempts");
86
+ }
87
+ return Math.min(retries * 100, 3000);
88
+ };
89
+ }
90
+ const clientOptions = {
91
+ url: redisUrl,
92
+ socket: socketConfig,
93
+ ...(finalPoolConfig.lazyConnect !== undefined && { lazyConnect: finalPoolConfig.lazyConnect }),
94
+ ...(finalPoolConfig.maxRetriesPerRequest !== undefined && { maxRetriesPerRequest: finalPoolConfig.maxRetriesPerRequest }),
95
+ };
96
+ console.log(`[Redis Config] Initializing Redis client with URL: ${redisUrl.replace(/:[^:@]+@/, ":****@")}`, {
97
+ poolConfig: {
98
+ connectTimeout: finalPoolConfig.connectTimeout,
99
+ keepAlive: finalPoolConfig.keepAlive,
100
+ keepAliveInitialDelay: finalPoolConfig.keepAliveInitialDelay,
101
+ lazyConnect: finalPoolConfig.lazyConnect,
102
+ maxRetriesPerRequest: finalPoolConfig.maxRetriesPerRequest,
103
+ },
104
+ });
105
+ redisClient = (0, redis_1.createClient)(clientOptions);
106
+ redisClient.on("error", (err) => {
107
+ console.error("[Redis Config] Connection error occurred:", {
108
+ message: err.message,
109
+ stack: err.stack,
110
+ timestamp: new Date().toISOString(),
111
+ });
112
+ isConnected = false;
113
+ });
114
+ redisClient.on("connect", () => {
115
+ console.log("[Redis Config] Connecting to Redis server...");
116
+ });
117
+ redisClient.on("ready", () => {
118
+ console.log("[Redis Config] Redis client connected and ready", {
119
+ url: redisUrl.replace(/:[^:@]+@/, ":****@"),
120
+ timestamp: new Date().toISOString(),
121
+ });
122
+ isConnected = true;
123
+ });
124
+ redisClient.on("reconnecting", () => {
125
+ console.warn("[Redis Config] Attempting to reconnect to Redis server...", {
126
+ timestamp: new Date().toISOString(),
127
+ });
128
+ isConnected = false;
129
+ });
130
+ redisClient.on("end", () => {
131
+ console.log("[Redis Config] Redis connection ended", {
132
+ timestamp: new Date().toISOString(),
133
+ });
134
+ isConnected = false;
135
+ });
136
+ try {
137
+ console.log("[Redis Config] Establishing connection...");
138
+ await redisClient.connect();
139
+ }
140
+ catch (error) {
141
+ const errorMessage = error instanceof Error ? error.message : String(error);
142
+ console.error("[Redis Config] Failed to connect to Redis:", {
143
+ message: errorMessage,
144
+ url: redisUrl.replace(/:[^:@]+@/, ":****@"),
145
+ timestamp: new Date().toISOString(),
146
+ });
147
+ throw error;
148
+ }
149
+ };
150
+ /**
151
+ * Redis 클라이언트가 연결되어 있는지 확인합니다.
152
+ * 연결되어 있지 않으면 자동으로 연결을 시도합니다.
153
+ *
154
+ * @param {RedisPoolConfig} [poolConfig] - 연결 풀 설정 (선택사항, 초기화 시에만 적용)
155
+ * @returns {Promise<RedisClientType>} 연결된 Redis 클라이언트
156
+ * @throws {Error} Redis 클라이언트가 초기화되지 않았거나 연결에 실패한 경우
157
+ */
158
+ const getRedisClient = async (poolConfig) => {
159
+ if (!redisClient || !isConnected) {
160
+ console.log("[Redis Config] Client not available, initializing...");
161
+ await initializeRedis(poolConfig);
162
+ }
163
+ if (!redisClient) {
164
+ const error = new Error("Redis client initialization failed: client is null after initialization attempt");
165
+ console.error("[Redis Config]", error.message);
166
+ throw error;
167
+ }
168
+ return redisClient;
169
+ };
170
+ exports.getRedisClient = getRedisClient;
171
+ /**
172
+ * Redis 연결 풀 설정을 업데이트합니다.
173
+ * 이미 연결된 경우에는 재연결이 필요할 수 있습니다.
174
+ *
175
+ * @param {RedisPoolConfig} poolConfig - 새로운 연결 풀 설정
176
+ * @returns {Promise<void>}
177
+ */
178
+ const configurePool = async (poolConfig) => {
179
+ if (redisClient && isConnected) {
180
+ console.warn("[Redis Config] Pool configuration change requires reconnection. Disconnecting current client...");
181
+ await (0, exports.disconnect)();
182
+ }
183
+ await initializeRedis(poolConfig);
184
+ };
185
+ exports.configurePool = configurePool;
186
+ /**
187
+ * Redis 연결을 종료합니다.
188
+ *
189
+ * @returns {Promise<void>}
190
+ */
191
+ const disconnect = async () => {
192
+ if (redisClient && isConnected) {
193
+ console.log("[Redis Config] Disconnecting Redis client...");
194
+ try {
195
+ await redisClient.quit();
196
+ console.log("[Redis Config] Redis client disconnected successfully", {
197
+ timestamp: new Date().toISOString(),
198
+ });
199
+ }
200
+ catch (error) {
201
+ console.error("[Redis Config] Error during disconnection:", {
202
+ message: error instanceof Error ? error.message : String(error),
203
+ timestamp: new Date().toISOString(),
204
+ });
205
+ throw error;
206
+ }
207
+ isConnected = false;
208
+ redisClient = null;
209
+ }
210
+ else {
211
+ console.log("[Redis Config] No active connection to disconnect");
212
+ }
213
+ };
214
+ exports.disconnect = disconnect;
215
+ // 애플리케이션 시작 시 Redis 연결 초기화
216
+ initializeRedis().catch((error) => {
217
+ console.error("[Redis Config] Failed to initialize Redis on application startup:", {
218
+ message: error instanceof Error ? error.message : String(error),
219
+ stack: error instanceof Error ? error.stack : undefined,
220
+ timestamp: new Date().toISOString(),
221
+ });
222
+ });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Redis에 키-값 쌍을 저장합니다.
3
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
4
+ * 값은 자동으로 JSON 문자열로 직렬화됩니다.
5
+ *
6
+ * @param {string} table - 테이블/스코프 프리픽스
7
+ * @param {string} key - 저장할 키 (프리픽스 제외)
8
+ * @param {T} value - 저장할 값 (객체는 자동 직렬화)
9
+ * @param {number} [expireSeconds] - 만료 시간(초), 지정하지 않으면 기본값 사용
10
+ * @returns {Promise<void>}
11
+ * @throws {Error} Redis 저장 중 오류가 발생한 경우
12
+ */
13
+ export declare const create: <T = any>(table: string, key: string, value: T, expireSeconds?: number) => Promise<void>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.create = void 0;
4
+ const config_1 = require("./config");
5
+ /**
6
+ * Redis에 키-값 쌍을 저장합니다.
7
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
8
+ * 값은 자동으로 JSON 문자열로 직렬화됩니다.
9
+ *
10
+ * @param {string} table - 테이블/스코프 프리픽스
11
+ * @param {string} key - 저장할 키 (프리픽스 제외)
12
+ * @param {T} value - 저장할 값 (객체는 자동 직렬화)
13
+ * @param {number} [expireSeconds] - 만료 시간(초), 지정하지 않으면 기본값 사용
14
+ * @returns {Promise<void>}
15
+ * @throws {Error} Redis 저장 중 오류가 발생한 경우
16
+ */
17
+ const create = async (table, key, value, expireSeconds) => {
18
+ const client = await (0, config_1.getRedisClient)();
19
+ const fullKey = `${table}:${key}`;
20
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
21
+ try {
22
+ if (expireSeconds !== undefined) {
23
+ await client.setEx(fullKey, expireSeconds, serialized);
24
+ }
25
+ else {
26
+ await client.set(fullKey, serialized);
27
+ }
28
+ }
29
+ catch (error) {
30
+ console.error(`Redis SET 오류 (key: ${fullKey}):`, error);
31
+ throw error;
32
+ }
33
+ };
34
+ exports.create = create;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Redis에서 키를 삭제합니다.
3
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
4
+ *
5
+ * @param {string} table - 테이블/스코프 프리픽스
6
+ * @param {string} key - 삭제할 키 (프리픽스 제외)
7
+ * @returns {Promise<boolean>} 삭제 성공 여부 (키가 존재했으면 true, 없었으면 false)
8
+ * @throws {Error} Redis 삭제 중 오류가 발생한 경우
9
+ */
10
+ export declare const deleteKey: (table: string, key: string) => Promise<boolean>;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteKey = void 0;
4
+ const config_1 = require("./config");
5
+ /**
6
+ * Redis에서 키를 삭제합니다.
7
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
8
+ *
9
+ * @param {string} table - 테이블/스코프 프리픽스
10
+ * @param {string} key - 삭제할 키 (프리픽스 제외)
11
+ * @returns {Promise<boolean>} 삭제 성공 여부 (키가 존재했으면 true, 없었으면 false)
12
+ * @throws {Error} Redis 삭제 중 오류가 발생한 경우
13
+ */
14
+ const deleteKey = async (table, key) => {
15
+ const client = await (0, config_1.getRedisClient)();
16
+ const fullKey = `${table}:${key}`;
17
+ try {
18
+ const result = await client.del(fullKey);
19
+ return result > 0;
20
+ }
21
+ catch (error) {
22
+ console.error(`Redis DEL 오류 (key: ${fullKey}):`, error);
23
+ throw error;
24
+ }
25
+ };
26
+ exports.deleteKey = deleteKey;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Redis에서 키의 존재 여부를 확인합니다.
3
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
4
+ *
5
+ * @param {string} table - 테이블/스코프 프리픽스
6
+ * @param {string} key - 확인할 키 (프리픽스 제외)
7
+ * @returns {Promise<boolean>} 키가 존재하면 true, 없으면 false
8
+ * @throws {Error} Redis 확인 중 오류가 발생한 경우
9
+ */
10
+ export declare const exists: (table: string, key: string) => Promise<boolean>;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exists = void 0;
4
+ const config_1 = require("./config");
5
+ /**
6
+ * Redis에서 키의 존재 여부를 확인합니다.
7
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
8
+ *
9
+ * @param {string} table - 테이블/스코프 프리픽스
10
+ * @param {string} key - 확인할 키 (프리픽스 제외)
11
+ * @returns {Promise<boolean>} 키가 존재하면 true, 없으면 false
12
+ * @throws {Error} Redis 확인 중 오류가 발생한 경우
13
+ */
14
+ const exists = async (table, key) => {
15
+ const client = await (0, config_1.getRedisClient)();
16
+ const fullKey = `${table}:${key}`;
17
+ try {
18
+ const result = await client.exists(fullKey);
19
+ return result > 0;
20
+ }
21
+ catch (error) {
22
+ console.error(`Redis EXISTS 오류 (key: ${fullKey}):`, error);
23
+ throw error;
24
+ }
25
+ };
26
+ exports.exists = exists;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Redis에서 키의 남은 만료 시간을 조회합니다.
3
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
4
+ *
5
+ * @param {string} table - 테이블/스코프 프리픽스
6
+ * @param {string} key - 조회할 키 (프리픽스 제외)
7
+ * @returns {Promise<number | null>} 남은 만료 시간(초), 만료 시간이 없으면 null
8
+ * @throws {Error} Redis 만료 시간 조회 중 오류가 발생한 경우
9
+ */
10
+ export declare const getTtl: (table: string, key: string) => Promise<number | null>;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTtl = void 0;
4
+ const config_1 = require("./config");
5
+ /**
6
+ * Redis에서 키의 남은 만료 시간을 조회합니다.
7
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
8
+ *
9
+ * @param {string} table - 테이블/스코프 프리픽스
10
+ * @param {string} key - 조회할 키 (프리픽스 제외)
11
+ * @returns {Promise<number | null>} 남은 만료 시간(초), 만료 시간이 없으면 null
12
+ * @throws {Error} Redis 만료 시간 조회 중 오류가 발생한 경우
13
+ */
14
+ const getTtl = async (table, key) => {
15
+ const client = await (0, config_1.getRedisClient)();
16
+ const fullKey = `${table}:${key}`;
17
+ try {
18
+ const ttl = await client.ttl(fullKey);
19
+ return ttl >= 0 ? ttl : null;
20
+ }
21
+ catch (error) {
22
+ console.error(`Redis TTL 오류 (key: ${fullKey}):`, error);
23
+ throw error;
24
+ }
25
+ };
26
+ exports.getTtl = getTtl;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Redis에서 키에 해당하는 값을 조회합니다.
3
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
4
+ * 값이 JSON 문자열인 경우 자동으로 파싱하여 반환합니다.
5
+ *
6
+ * @param {string} table - 테이블/스코프 프리픽스
7
+ * @param {string} key - 조회할 키 (프리픽스 제외)
8
+ * @returns {Promise<T | null>} 키에 해당하는 값, 존재하지 않으면 null
9
+ * @throws {Error} Redis 조회 중 오류가 발생한 경우
10
+ */
11
+ export declare const read: <T = any>(table: string, key: string) => Promise<T | null>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.read = void 0;
4
+ const config_1 = require("./config");
5
+ /**
6
+ * Redis에서 키에 해당하는 값을 조회합니다.
7
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
8
+ * 값이 JSON 문자열인 경우 자동으로 파싱하여 반환합니다.
9
+ *
10
+ * @param {string} table - 테이블/스코프 프리픽스
11
+ * @param {string} key - 조회할 키 (프리픽스 제외)
12
+ * @returns {Promise<T | null>} 키에 해당하는 값, 존재하지 않으면 null
13
+ * @throws {Error} Redis 조회 중 오류가 발생한 경우
14
+ */
15
+ const read = async (table, key) => {
16
+ const client = await (0, config_1.getRedisClient)();
17
+ const fullKey = `${table}:${key}`;
18
+ try {
19
+ const value = await client.get(fullKey);
20
+ if (value === null) {
21
+ console.log(`Redis GET: key=${fullKey}, value=null`);
22
+ return null;
23
+ }
24
+ // JSON 문자열인지 확인하고 파싱 시도
25
+ if (typeof value === "string") {
26
+ const trimmedValue = value.trim();
27
+ // JSON 형식인지 간단히 확인 (시작이 { 또는 [)
28
+ if ((trimmedValue.startsWith("{") && trimmedValue.endsWith("}")) ||
29
+ (trimmedValue.startsWith("[") && trimmedValue.endsWith("]"))) {
30
+ try {
31
+ const parsed = JSON.parse(value);
32
+ console.log(`Redis GET: key=${fullKey}, parsed successfully`);
33
+ return parsed;
34
+ }
35
+ catch (parseError) {
36
+ // JSON 파싱 실패 시 원래 문자열 반환
37
+ console.log(`Redis GET: key=${fullKey}, JSON parse failed, returning string`);
38
+ return value;
39
+ }
40
+ }
41
+ }
42
+ console.log(`Redis GET: key=${fullKey}, returning raw value`);
43
+ return value;
44
+ }
45
+ catch (error) {
46
+ console.error(`Redis GET 오류 (key: ${fullKey}):`, error);
47
+ throw error;
48
+ }
49
+ };
50
+ exports.read = read;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Redis에서 키의 만료 시간을 설정합니다.
3
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
4
+ *
5
+ * @param {string} table - 테이블/스코프 프리픽스
6
+ * @param {string} key - 만료 시간을 설정할 키 (프리픽스 제외)
7
+ * @param {number} seconds - 만료 시간(초)
8
+ * @returns {Promise<boolean>} 설정 성공 여부
9
+ * @throws {Error} Redis 만료 시간 설정 중 오류가 발생한 경우
10
+ */
11
+ export declare const setExpire: (table: string, key: string, seconds: number) => Promise<boolean>;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setExpire = void 0;
4
+ const config_1 = require("./config");
5
+ /**
6
+ * Redis에서 키의 만료 시간을 설정합니다.
7
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
8
+ *
9
+ * @param {string} table - 테이블/스코프 프리픽스
10
+ * @param {string} key - 만료 시간을 설정할 키 (프리픽스 제외)
11
+ * @param {number} seconds - 만료 시간(초)
12
+ * @returns {Promise<boolean>} 설정 성공 여부
13
+ * @throws {Error} Redis 만료 시간 설정 중 오류가 발생한 경우
14
+ */
15
+ const setExpire = async (table, key, seconds) => {
16
+ const client = await (0, config_1.getRedisClient)();
17
+ const fullKey = `${table}:${key}`;
18
+ try {
19
+ const result = await client.expire(fullKey, seconds);
20
+ return Boolean(result);
21
+ }
22
+ catch (error) {
23
+ console.error(`Redis EXPIRE 오류 (key: ${fullKey}):`, error);
24
+ throw error;
25
+ }
26
+ };
27
+ exports.setExpire = setExpire;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Redis에서 키의 값을 부분 업데이트합니다.
3
+ * 기존 값을 읽어와서 병합한 후 저장합니다.
4
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
5
+ *
6
+ * @param {string} table - 테이블/스코프 프리픽스
7
+ * @param {string} key - 업데이트할 키 (프리픽스 제외)
8
+ * @param {Partial<T>} partial - 업데이트할 부분 값
9
+ * @param {number} [expireSeconds] - 만료 시간(초), 지정하지 않으면 기본값 사용
10
+ * @returns {Promise<T | null>} 업데이트된 값, 키가 존재하지 않으면 null
11
+ * @throws {Error} Redis 업데이트 중 오류가 발생한 경우
12
+ */
13
+ export declare const update: <T = any>(table: string, key: string, partial: Partial<T>, expireSeconds?: number) => Promise<T | null>;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.update = void 0;
4
+ const read_1 = require("./read");
5
+ const create_1 = require("./create");
6
+ /**
7
+ * Redis에서 키의 값을 부분 업데이트합니다.
8
+ * 기존 값을 읽어와서 병합한 후 저장합니다.
9
+ * 키는 자동으로 table 프리픽스가 추가됩니다.
10
+ *
11
+ * @param {string} table - 테이블/스코프 프리픽스
12
+ * @param {string} key - 업데이트할 키 (프리픽스 제외)
13
+ * @param {Partial<T>} partial - 업데이트할 부분 값
14
+ * @param {number} [expireSeconds] - 만료 시간(초), 지정하지 않으면 기본값 사용
15
+ * @returns {Promise<T | null>} 업데이트된 값, 키가 존재하지 않으면 null
16
+ * @throws {Error} Redis 업데이트 중 오류가 발생한 경우
17
+ */
18
+ const update = async (table, key, partial, expireSeconds) => {
19
+ // 기존 값 조회
20
+ const existing = await (0, read_1.read)(table, key);
21
+ if (existing === null) {
22
+ return null;
23
+ }
24
+ // 기존 값과 병합
25
+ const updated = { ...existing, ...partial };
26
+ // 저장
27
+ await (0, create_1.create)(table, key, updated, expireSeconds);
28
+ return updated;
29
+ };
30
+ exports.update = update;
package/version.txt ADDED
@@ -0,0 +1 @@
1
+ 0.0.1