All files / src/operations validate_collection.ts

78.26% Statements 18/23
43.75% Branches 7/16
100% Functions 3/3
77.27% Lines 17/22

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    400x       400x                 400x             746x 746x 746x           746x 746x 746x 746x       975x               517x   517x 517x   517x   517x     517x      
import type { Admin } from '../admin';
import type { Document } from '../bson';
import { MongoUnexpectedServerResponseError } from '../error';
import type { Server } from '../sdam/server';
import type { ClientSession } from '../sessions';
import { type TimeoutContext } from '../timeout';
import { CommandOperation, type CommandOperationOptions } from './command';
 
/** @public */
export interface ValidateCollectionOptions extends CommandOperationOptions {
  /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */
  background?: boolean;
}
 
/** @internal */
export class ValidateCollectionOperation extends CommandOperation<Document> {
  override options: ValidateCollectionOptions;
  collectionName: string;
  command: Document;
 
  constructor(admin: Admin, collectionName: string, options: ValidateCollectionOptions) {
    // Decorate command with extra options
    const command: Document = { validate: collectionName };
    const keys = Object.keys(options);
    for (let i = 0; i < keys.length; i++) {
      if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') {
        command[keys[i]] = (options as Document)[keys[i]];
      }
    }
 
    super(admin.s.db, options);
    this.options = options;
    this.command = command;
    this.collectionName = collectionName;
  }
 
  override get commandName() {
    return 'validate' as const;
  }
 
  override async execute(
    server: Server,
    session: ClientSession | undefined,
    timeoutContext: TimeoutContext
  ): Promise<Document> {
    const collectionName = this.collectionName;
 
    const doc = await super.executeCommand(server, session, this.command, timeoutContext);
    Iif (doc.result != null && typeof doc.result !== 'string')
      throw new MongoUnexpectedServerResponseError('Error with validation data');
    Iif (doc.result != null && doc.result.match(/exception|corrupt/) != null)
      throw new MongoUnexpectedServerResponseError(`Invalid collection ${collectionName}`);
    Iif (doc.valid != null && !doc.valid)
      throw new MongoUnexpectedServerResponseError(`Invalid collection ${collectionName}`);
 
    return doc;
  }
}