Skip to content

Commit afad9af

Browse files
committed
refactor(NODE-5473): remove unused callback inheritance in operations layer (#3793)
1 parent 42d05ae commit afad9af

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

src/operations/eval.ts

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { Code, type Document } from '../bson';
2+
import type { Collection } from '../collection';
3+
import type { Db } from '../db';
4+
import { MongoServerError } from '../error';
5+
import { ReadPreference } from '../read_preference';
6+
import type { Server } from '../sdam/server';
7+
import type { ClientSession } from '../sessions';
8+
import { CommandOperation, type CommandOperationOptions } from './command';
9+
10+
/** @public */
11+
export interface EvalOptions extends CommandOperationOptions {
12+
nolock?: boolean;
13+
}
14+
15+
/** @internal */
16+
export class EvalOperation extends CommandOperation<Document> {
17+
override options: EvalOptions;
18+
code: Code;
19+
parameters?: Document | Document[];
20+
21+
constructor(
22+
db: Db | Collection,
23+
code: Code,
24+
parameters?: Document | Document[],
25+
options?: EvalOptions
26+
) {
27+
super(db, options);
28+
29+
this.options = options ?? {};
30+
this.code = code;
31+
this.parameters = parameters;
32+
// force primary read preference
33+
Object.defineProperty(this, 'readPreference', {
34+
value: ReadPreference.primary,
35+
configurable: false,
36+
writable: false
37+
});
38+
}
39+
40+
override async execute(server: Server, session: ClientSession | undefined): Promise<Document> {
41+
let finalCode = this.code;
42+
let finalParameters: Document[] = [];
43+
44+
// If not a code object translate to one
45+
if (!(finalCode && (finalCode as unknown as { _bsontype: string })._bsontype === 'Code')) {
46+
finalCode = new Code(finalCode as never);
47+
}
48+
49+
// Ensure the parameters are correct
50+
if (this.parameters != null && typeof this.parameters !== 'function') {
51+
finalParameters = Array.isArray(this.parameters) ? this.parameters : [this.parameters];
52+
}
53+
54+
// Create execution selector
55+
const cmd: Document = { $eval: finalCode, args: finalParameters };
56+
57+
// Check if the nolock parameter is passed in
58+
if (this.options.nolock) {
59+
cmd.nolock = this.options.nolock;
60+
}
61+
62+
// Execute the command
63+
const result = await super.executeCommand(server, session, cmd);
64+
if (result && result.ok === 1) {
65+
return result.retval;
66+
}
67+
68+
if (result) {
69+
throw new MongoServerError({ message: `eval failed: ${result.errmsg}` });
70+
}
71+
72+
return result;
73+
}
74+
}

0 commit comments

Comments
 (0)