1- import { MongoInvalidArgumentError } from './error' ;
2-
31/** @public */
42export const ExplainVerbosity = Object . freeze ( {
53 queryPlanner : 'queryPlanner' ,
@@ -19,33 +17,72 @@ export type ExplainVerbosity = string;
1917export type ExplainVerbosityLike = ExplainVerbosity | boolean ;
2018
2119/** @public */
20+ export interface ExplainCommandOptions {
21+ /** The explain verbosity for the command. */
22+ verbosity : ExplainVerbosity ;
23+ /** The maxTimeMS setting for the command. */
24+ maxTimeMS ?: number ;
25+ }
26+
27+ /**
28+ * @public
29+ *
30+ * When set, this configures an explain command. Valid values are boolean (for legacy compatibility,
31+ * see {@link ExplainVerbosityLike}), a string containing the explain verbosity, or an object containing the verbosity and
32+ * an optional maxTimeMS.
33+ *
34+ * Examples of valid usage:
35+ *
36+ * ```typescript
37+ * collection.find({ name: 'john doe' }, { explain: true });
38+ * collection.find({ name: 'john doe' }, { explain: false });
39+ * collection.find({ name: 'john doe' }, { explain: 'queryPlanner' });
40+ * collection.find({ name: 'john doe' }, { explain: { verbosity: 'queryPlanner' } });
41+ * ```
42+ *
43+ * maxTimeMS can be configured to limit the amount of time the server
44+ * spends executing an explain by providing an object:
45+ *
46+ * ```typescript
47+ * // limits the `explain` command to no more than 2 seconds
48+ * collection.find({ name: 'john doe' }, {
49+ * explain: {
50+ * verbosity: 'queryPlanner',
51+ * maxTimeMS: 2000
52+ * }
53+ * });
54+ * ```
55+ */
2256export interface ExplainOptions {
2357 /** Specifies the verbosity mode for the explain output. */
24- explain ?: ExplainVerbosityLike ;
58+ explain ?: ExplainVerbosityLike | ExplainCommandOptions ;
2559}
2660
2761/** @internal */
2862export class Explain {
29- verbosity : ExplainVerbosity ;
63+ readonly verbosity : ExplainVerbosity ;
64+ readonly maxTimeMS ?: number ;
3065
31- constructor ( verbosity : ExplainVerbosityLike ) {
66+ private constructor ( verbosity : ExplainVerbosityLike , maxTimeMS ?: number ) {
3267 if ( typeof verbosity === 'boolean' ) {
3368 this . verbosity = verbosity
3469 ? ExplainVerbosity . allPlansExecution
3570 : ExplainVerbosity . queryPlanner ;
3671 } else {
3772 this . verbosity = verbosity ;
3873 }
74+
75+ this . maxTimeMS = maxTimeMS ;
3976 }
4077
41- static fromOptions ( options ? : ExplainOptions ) : Explain | undefined {
42- if ( options ?. explain == null ) return ;
78+ static fromOptions ( { explain } : ExplainOptions = { } ) : Explain | undefined {
79+ if ( explain == null ) return ;
4380
44- const explain = options . explain ;
4581 if ( typeof explain === 'boolean' || typeof explain === 'string' ) {
4682 return new Explain ( explain ) ;
4783 }
4884
49- throw new MongoInvalidArgumentError ( 'Field "explain" must be a string or a boolean' ) ;
85+ const { verbosity, maxTimeMS } = explain ;
86+ return new Explain ( verbosity , maxTimeMS ) ;
5087 }
5188}
0 commit comments