Skip to content

Commit 35d1814

Browse files
committed
check explain value in explain command constructor
1 parent fee4091 commit 35d1814

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

src/explain.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ export abstract class ExplainableCommand<
1919

2020
constructor(parent?: OperationParent, options?: T) {
2121
super(parent, options);
22+
23+
if (!Explain.explainOptionsValid(options)) {
24+
throw new MongoError(`explain must be one of ${Object.keys(Verbosity)} or a boolean`);
25+
}
26+
2227
this.explain = Explain.fromOptions(options);
2328
}
2429

@@ -57,15 +62,15 @@ export type VerbosityLike = Verbosity | boolean;
5762

5863
/** @internal */
5964
export class Explain {
60-
explain: Verbosity;
65+
verbosity: Verbosity;
6166

62-
constructor(explain: VerbosityLike) {
63-
if (typeof explain === 'boolean') {
67+
constructor(verbosity: VerbosityLike) {
68+
if (typeof verbosity === 'boolean') {
6469
// For backwards compatibility, true is interpreted as
6570
// "allPlansExecution" and false as "queryPlanner".
66-
this.explain = explain ? Verbosity.allPlansExecution : Verbosity.queryPlanner;
71+
this.verbosity = verbosity ? Verbosity.allPlansExecution : Verbosity.queryPlanner;
6772
} else {
68-
this.explain = Verbosity[explain];
73+
this.verbosity = Verbosity[verbosity];
6974
}
7075
}
7176

@@ -76,6 +81,14 @@ export class Explain {
7681
return new Explain(options.explain);
7782
}
7883

84+
static explainOptionsValid(options?: ExplainOptions): boolean {
85+
if (options == null || options.explain === undefined) {
86+
return true;
87+
}
88+
const explain = options.explain;
89+
return typeof explain === 'boolean' || explain in Verbosity;
90+
}
91+
7992
/**
8093
* Checks that the server supports explain on the given operation.
8194
* @internal
@@ -113,15 +126,12 @@ export class Explain {
113126
* @param command - the command on which to apply the read concern
114127
* @param options - the options containing the explain verbosity
115128
*/
116-
export function decorateWithExplain(command: Document, options: ExplainOptions): Document {
117-
const explain = Explain.fromOptions(options);
118-
if (explain === undefined) return command;
119-
129+
export function decorateWithExplain(command: Document, explain: Explain): Document {
120130
// A command being explained may not have an explain field directly on it
121131
if (command.explain !== undefined) {
122132
delete command.explain;
123133
}
124134

125-
command = { explain: command, verbosity: explain.explain };
135+
command = { explain: command, verbosity: explain.verbosity };
126136
return command;
127137
}

0 commit comments

Comments
 (0)