-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy patheval.ts
82 lines (70 loc) · 2.34 KB
/
eval.ts
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
import { Code, type Document } from '../bson';
import type { Collection } from '../collection';
import type { Db } from '../db';
import { MongoServerError } from '../error';
import { ReadPreference } from '../read_preference';
import type { Server } from '../sdam/server';
import type { ClientSession } from '../sessions';
import type { Callback } from '../utils';
import { CommandOperation, type CommandOperationOptions } from './command';
/** @public */
export interface EvalOptions extends CommandOperationOptions {
nolock?: boolean;
}
/** @internal */
export class EvalOperation extends CommandOperation<Document> {
override options: EvalOptions;
code: Code;
parameters?: Document | Document[];
constructor(
db: Db | Collection,
code: Code,
parameters?: Document | Document[],
options?: EvalOptions
) {
super(db, options);
this.options = options ?? {};
this.code = code;
this.parameters = parameters;
// force primary read preference
Object.defineProperty(this, 'readPreference', {
value: ReadPreference.primary,
configurable: false,
writable: false
});
}
override executeCallback(
server: Server,
session: ClientSession | undefined,
callback: Callback<Document>
): void {
let finalCode = this.code;
let finalParameters: Document[] = [];
// If not a code object translate to one
if (!(finalCode && (finalCode as unknown as { _bsontype: string })._bsontype === 'Code')) {
finalCode = new Code(finalCode as never);
}
// Ensure the parameters are correct
if (this.parameters != null && typeof this.parameters !== 'function') {
finalParameters = Array.isArray(this.parameters) ? this.parameters : [this.parameters];
}
// Create execution selector
const cmd: Document = { $eval: finalCode, args: finalParameters };
// Check if the nolock parameter is passed in
if (this.options.nolock) {
cmd.nolock = this.options.nolock;
}
// Execute the command
super.executeCommand(server, session, cmd, (err, result) => {
if (err) return callback(err);
if (result && result.ok === 1) {
return callback(undefined, result.retval);
}
if (result) {
callback(new MongoServerError({ message: `eval failed: ${result.errmsg}` }));
return;
}
callback(err, result);
});
}
}