Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | 1x 1x 1x 2x 2x 1x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 2x 1x 20x 20x 20x 20x 5x 5x 4x 1x 2x 2x 3x 1x 1x 1x 2x | import { Type } from "../core/types";
import { DatabaseAdapter } from "./interface";
import { MetadataRegistry } from "../core/MetadataRegistry";
import { SchemaReflector } from "../core/SchemaReflector";
/**
* Redis-specific key decorator
*/
export function Key(prefix: string) {
return function (target: any) {
Reflect.defineMetadata("redis:key", prefix, target);
};
}
/**
* Redis-specific TTL decorator for entity or property expiration
*/
export function TTL(seconds: number) {
return function (target: any, propertyKey?: string) {
if (!propertyKey) {
// Applied to class - global TTL for all instances
Reflect.defineMetadata("redis:ttl", seconds, target);
} else {
// Applied to property - property-specific TTL
const ttlMap =
Reflect.getMetadata("redis:property:ttl", target.constructor) ||
new Map();
ttlMap.set(propertyKey, seconds);
Reflect.defineMetadata("redis:property:ttl", ttlMap, target.constructor);
}
};
}
/**
* Redis-specific index decorator for secondary indexes
*/
export function Index(name: string) {
return function (target: any, propertyKey: string) {
const indexes =
Reflect.getMetadata("redis:indexes", target.constructor) || [];
indexes.push({ name, field: propertyKey });
Reflect.defineMetadata("redis:indexes", indexes, target.constructor);
};
}
/**
* Shorthand decorator for Redis entities
*/
export function Redis<T extends { new (...args: any[]): any }>(target: T): T {
return DatabaseAdapter("Redis")(target);
}
/**
* Implementation of DatabaseAdapter for Redis
*/
export class RedisAdapter implements DatabaseAdapter {
readonly type = "Redis";
private registry: MetadataRegistry;
private reflector = new SchemaReflector();
/**
* Constructor for Redis adapter
* @param registry The metadata registry to use for schema information
* @param connectionString The Redis connection string
*/
constructor(registry: MetadataRegistry, private connectionString: string) {
this.registry = registry;
}
/**
* Get the key prefix for an entity type
*/
private getKeyPrefix<T>(entityType: Type<T>): string {
// Get custom key prefix if defined, otherwise use entity name
const keyPrefix = Reflect.getMetadata("redis:key", entityType);
if (keyPrefix) {
return keyPrefix;
}
return entityType.name.toLowerCase();
}
/**
* Get the full Redis key for an entity
*/
private getEntityKey<T>(entityType: Type<T>, id: string | number): string {
const prefix = this.getKeyPrefix(entityType);
return `${prefix}:${id}`;
}
/**
* Get TTL for an entity type or property
*/
private getTTL<T>(entityType: Type<T>, propertyKey?: string): number | null {
if (propertyKey) {
const propertyTTLs = Reflect.getMetadata(
"redis:property:ttl",
entityType
);
if (propertyTTLs && propertyTTLs.has(propertyKey)) {
return propertyTTLs.get(propertyKey);
}
}
// Fall back to entity-level TTL
return Reflect.getMetadata("redis:ttl", entityType) || null;
}
/**
* Get all defined indexes for an entity type
*/
private getIndexes<T>(entityType: Type<T>): any[] {
return Reflect.getMetadata("redis:indexes", entityType) || [];
}
/**
* Convert entity to Redis hash
*/
private entityToHash<T>(entity: T): Record<string, string> {
const entityType = entity.constructor as Type<T>;
const entitySchema = this.reflector.getEntitySchema(entityType);
const hash: Record<string, string> = {};
// Convert each property to string (Redis hash values must be strings)
for (const [key, meta] of Object.entries(entitySchema.properties)) {
Iif ((entity as any)[key] !== undefined) {
const value = (entity as any)[key];
// Serialize non-string values to JSON
hash[key] = typeof value === "string" ? value : JSON.stringify(value);
}
}
return hash;
}
/**
* Convert Redis hash to entity instance
*/
private hashToEntity<T>(
entityType: Type<T>,
hash: Record<string, string>
): T {
const entity = new entityType();
const entitySchema = this.reflector.getEntitySchema(entityType);
// Deserialize each property according to its type
for (const [key, meta] of Object.entries(entitySchema.properties)) {
Iif (hash[key] !== undefined) {
try {
// Try to parse as JSON first
(entity as any)[key] = JSON.parse(hash[key]);
} catch (e) {
// If parsing fails, use the raw string
(entity as any)[key] = hash[key];
}
}
}
return entity;
}
/**
* Query for a single entity by criteria
*/
async query<T>(entityType: Type<T>, criteria: object): Promise<T | null> {
console.log(`[RedisAdapter] Querying with criteria:`, criteria);
const criteriaObj = criteria as Record<string, any>;
// In Redis, efficient queries are typically only by primary key
Iif ("id" in criteriaObj) {
const key = this.getEntityKey(entityType, criteriaObj.id);
console.log(`[RedisAdapter] Fetching hash at key: ${key}`);
// Simulate database call - in a real implementation, would use Redis client
// const hash = await redis.hgetall(key);
const result = await this.mockQueryExecution<T>(entityType, criteria);
return result;
}
// For more complex criteria, we can use secondary indexes if defined
// This would be much more complex in a real implementation
// and would likely involve scanning multiple keys or using Redis search
return null;
}
/**
* Query for multiple entities by criteria
*/
async queryMany<T>(entityType: Type<T>, criteria: object): Promise<T[]> {
console.log(
`[RedisAdapter] Querying for multiple entities with criteria:`,
criteria
);
// Get all indexes for this entity type
const indexes = this.getIndexes(entityType);
// In a real implementation, this would use Redis search capabilities
// or potentially scan multiple keys based on index patterns
// Mock implementation
return []; // Mock empty result
}
/**
* Save an entity to Redis
*/
async save<T extends object>(entity: T): Promise<void> {
const entityType = entity.constructor as Type<T>;
// Validate the entity before saving
const validation = this.reflector.validateEntity(entity);
Iif (!validation.valid) {
throw new Error(`Invalid entity: ${validation.errors.join(", ")}`);
}
// Get entity ID (required)
Iif (!("id" in entity)) {
throw new Error("Entity must have an id property to be saved to Redis");
}
const id = (entity as any).id;
const key = this.getEntityKey(entityType, id);
// Convert entity to hash
const hash = this.entityToHash(entity);
console.log(`[RedisAdapter] Saving hash to key ${key}:`, hash);
// In a real implementation, would use Redis client
// await redis.hset(key, hash);
// Apply TTL if specified
const ttl = this.getTTL(entityType);
Iif (ttl !== null) {
console.log(
`[RedisAdapter] Setting TTL of ${ttl} seconds for key ${key}`
);
// await redis.expire(key, ttl);
}
// Update indexes
const indexes = this.getIndexes(entityType);
for (const index of indexes) {
const indexValue = (entity as any)[index.field];
Iif (indexValue !== undefined) {
const indexKey = `${this.getKeyPrefix(entityType)}:index:${
index.name
}:${indexValue}`;
console.log(
`[RedisAdapter] Updating index at ${indexKey} to point to ${key}`
);
// await redis.set(indexKey, key);
}
}
}
/**
* Delete an entity from Redis
*/
async delete<T>(entityType: Type<T>, id: string | number): Promise<void> {
const key = this.getEntityKey(entityType, id);
console.log(`[RedisAdapter] Deleting key ${key}`);
// In a real implementation, would use Redis client
// await redis.del(key);
// Also need to clean up any indexes
// This would require first fetching the entity to get indexed values
// Simplified example for index cleanup
// const indexes = this.getIndexes(entityType);
// for (const index of indexes) {
// const entity = await this.query(entityType, { id });
// if (entity) {
// const indexValue = (entity as any)[index.field];
// if (indexValue !== undefined) {
// const indexKey = `${this.getKeyPrefix(entityType)}:index:${index.name}:${indexValue}`;
// await redis.del(indexKey);
// }
// }
// }
}
/**
* Execute a raw Redis command
*/
async runNativeQuery<T>(command: string, args?: any[]): Promise<T> {
console.log(`[RedisAdapter] Running native command: ${command}`);
console.log(`[RedisAdapter] Args:`, args);
// In a real implementation, this would be:
// return redis.sendCommand(command, args);
return {} as T; // Mock result
}
/**
* Mock method to simulate database query execution
* In a real implementation, this would use the Redis client
*/
private async mockQueryExecution<T>(
entityType: Type<T>,
criteria: object
): Promise<T | null> {
// Just a mock implementation for demonstration
const criteriaObj = criteria as Record<string, any>;
Iif ("id" in criteriaObj && criteriaObj.id === "123") {
const entity = new entityType();
Object.assign(entity, {
id: "123",
name: "Mock Redis Entity",
createdAt: new Date().toISOString(),
});
return entity;
}
return null;
}
}
|