All files / adapters mongodb.ts

79.68% Statements 51/64
68.75% Branches 11/16
93.75% Functions 15/16
79.68% Lines 51/64

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  8x   8x         8x 2x 2x             8x 2x   2x 2x 2x                           8x 1x           8x 14x   14x             14x 14x               9x 9x 3x       6x             1x                                                 1x 1x 1x             2x 2x       2x   2x 2x     2x 2x                   1x 1x     1x     1x             1x 1x     1x 1x 1x                                     1x 1x                   1x 1x           1x                 2x 1x 1x         1x     1x    
import { Type } from '../core/types';
import { DatabaseAdapter } from './interface';
import { MetadataRegistry } from '../core/MetadataRegistry';
import { SchemaReflector } from '../core/SchemaReflector';
 
/**
 * MongoDB-specific collection decorator
 */
export function Collection(name: string) {
  return function(target: any) {
    Reflect.defineMetadata('mongodb:collection', name, target);
  };
}
 
/**
 * MongoDB-specific index decorator
 */
export function Index(keys: Record<string, 1 | -1 | '2dsphere' | 'text'>, options: any = {}) {
  return function(target: any, propertyKey?: string) {
    // If applied to a class, define index for the collection
    if (!propertyKey) {
      const existingIndexes = Reflect.getMetadata('mongodb:indexes', target) || [];
      Reflect.defineMetadata('mongodb:indexes', [...existingIndexes, { keys, options }], target);
    } 
    // If applied to a property, define index for a specific field
    else E{
      const existingIndexes = Reflect.getMetadata('mongodb:indexes', target.constructor) || [];
      const indexDef = { keys: { [propertyKey]: keys }, options };
      Reflect.defineMetadata('mongodb:indexes', [...existingIndexes, indexDef], target.constructor);
    }
  };
}
 
/**
 * Shorthand decorator for MongoDB entities
 */
export function MongoDB<T extends { new (...args: any[]): any }>(target: T): T {
  return DatabaseAdapter('MongoDB')(target);
}
 
/**
 * Implementation of DatabaseAdapter for MongoDB
 */
export class MongoDBAdapter implements DatabaseAdapter {
  readonly type = 'MongoDB';
  private registry: MetadataRegistry;
  private reflector = new SchemaReflector();
  
  /**
   * Constructor for MongoDB adapter
   * @param registry The metadata registry to use for schema information
   * @param connectionString The MongoDB connection string
   */
  constructor(registry: MetadataRegistry, private connectionString: string) {
    this.registry = registry;
  }
  
  /**
   * Get the collection name for an entity type
   */
  private getCollectionName<T>(entityType: Type<T>): string {
    // Get custom collection name if defined, otherwise use entity name in plural form
    const collectionName = Reflect.getMetadata('mongodb:collection', entityType);
    if (collectionName) {
      return collectionName;
    }
    
    // Simple pluralization (just add 's')
    return `${entityType.name.toLowerCase()}s`;
  }
  
  /**
   * Get all defined indexes for an entity type
   */
  private getIndexes<T>(entityType: Type<T>): any[] {
    return Reflect.getMetadata('mongodb:indexes', entityType) || [];
  }
  
  /**
   * Convert entity to MongoDB document
   */
  private entityToDocument<T>(entity: T): Record<string, any> {
    const entityType = entity.constructor as Type<T>;
    const entitySchema = this.reflector.getEntitySchema(entityType);
    const document: Record<string, any> = {};
    
    // Convert each property
    for (const [key, meta] of Object.entries(entitySchema.properties)) {
      Iif ((entity as any)[key] !== undefined) {
        document[key] = (entity as any)[key];
      }
    }
    
    return document;
  }
  
  /**
   * Convert MongoDB document to entity instance
   */
  private documentToEntity<T>(entityType: Type<T>, document: Record<string, any>): T {
    const entity = new entityType();
    Object.assign(entity, document);
    return entity;
  }
 
  /**
   * Query for a single entity by criteria
   */
  async query<T>(entityType: Type<T>, criteria: object): Promise<T | null> {
    const collectionName = this.getCollectionName(entityType);
    console.log(`[MongoDBAdapter] Querying ${collectionName} with criteria:`, criteria);
    
    // In a real implementation, this would use the MongoDB driver to execute a query
    // Mock implementation for demonstration purposes
    if ('id' in criteria) {
      // MongoDB uses _id as the primary key, but we'll use id for consistency
      const query = { id: criteria.id };
      console.log(`[MongoDBAdapter] Finding document with query:`, query);
      
      // Simulate database call
      const result = await this.mockQueryExecution<T>(entityType, criteria);
      return result;
    }
    
    return null;
  }
  
  /**
   * Query for multiple entities by criteria
   */
  async queryMany<T>(entityType: Type<T>, criteria: object): Promise<T[]> {
    const collectionName = this.getCollectionName(entityType);
    console.log(`[MongoDBAdapter] Querying ${collectionName} for multiple documents with criteria:`, criteria);
    
    // Mock implementation - in real code, would use MongoDB driver
    console.log(`[MongoDBAdapter] Finding documents with query:`, criteria);
    
    // Simulate database call
    return []; // Mock empty result
  }
  
  /**
   * Save an entity to MongoDB
   */
  async save<T>(entity: T): Promise<void> {
    const entityType = entity.constructor as Type<T>;
    const collectionName = this.getCollectionName(entityType);
    
    // Validate the entity before saving
    const validation = this.reflector.validateEntity(entity);
    if (!validation.valid) {
      throw new Error(`Invalid entity: ${validation.errors.join(', ')}`);
    }
    
    // Convert entity to MongoDB document
    const document = this.entityToDocument(entity);
    console.log(`[MongoDBAdapter] Saving document to collection ${collectionName}:`, document);
    
    // In a real implementation, would use MongoDB driver
    // const result = await collection.updateOne(
    //   { id: document.id },
    //   { $set: document },
    //   { upsert: true }
    // );
  }
  
  /**
   * Delete an entity from MongoDB
   */
  async delete<T>(entityType: Type<T>, id: string | number): Promise<void> {
    const collectionName = this.getCollectionName(entityType);
    console.log(`[MongoDBAdapter] Deleting document with id ${id} from collection ${collectionName}`);
    
    // In a real implementation, would use MongoDB driver
    // const result = await collection.deleteOne({ id });
  }
  
  /**
   * Execute a raw MongoDB command
   */
  async runNativeQuery<T>(query: string, params?: any): Promise<T> {
    console.log(`[MongoDBAdapter] Running native query:`, query);
    console.log(`[MongoDBAdapter] Params:`, params);
    
    // In a real implementation, this would be something like:
    // const db = client.db();
    // return db.command(JSON.parse(query));
    
    return {} as T; // Mock result
  }
  
  /**
   * Mock method to simulate database query execution
   * In a real implementation, this would use the MongoDB driver
   */
  private async mockQueryExecution<T>(entityType: Type<T>, criteria: object): Promise<T | null> {
    // Just a mock implementation for demonstration
    if ('id' in criteria && criteria.id === '123') {
      const entity = new entityType();
      Object.assign(entity, {
        id: '123',
        name: 'Mock MongoDB Entity',
        createdAt: new Date()
      });
      return entity;
    }
    
    return null;
  }
}