|
|
import type { Document } from './bson'; |
|
|
import { BSONValue } from './bson_value'; |
|
|
|
|
|
|
|
|
export interface CodeExtended { |
|
|
$code: string; |
|
|
$scope?: Document; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export class Code extends BSONValue { |
|
|
get _bsontype(): 'Code' { |
|
|
return 'Code'; |
|
|
} |
|
|
|
|
|
code: string; |
|
|
|
|
|
|
|
|
|
|
|
scope: Document | null; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
constructor(code: string | Function, scope?: Document | null) { |
|
|
super(); |
|
|
this.code = code.toString(); |
|
|
this.scope = scope ?? null; |
|
|
} |
|
|
|
|
|
toJSON(): { code: string; scope?: Document } { |
|
|
if (this.scope != null) { |
|
|
return { code: this.code, scope: this.scope }; |
|
|
} |
|
|
|
|
|
return { code: this.code }; |
|
|
} |
|
|
|
|
|
|
|
|
toExtendedJSON(): CodeExtended { |
|
|
if (this.scope) { |
|
|
return { $code: this.code, $scope: this.scope }; |
|
|
} |
|
|
|
|
|
return { $code: this.code }; |
|
|
} |
|
|
|
|
|
|
|
|
static fromExtendedJSON(doc: CodeExtended): Code { |
|
|
return new Code(doc.$code, doc.$scope); |
|
|
} |
|
|
|
|
|
|
|
|
[Symbol.for('nodejs.util.inspect.custom')](): string { |
|
|
return this.inspect(); |
|
|
} |
|
|
|
|
|
inspect(): string { |
|
|
const codeJson = this.toJSON(); |
|
|
return `new Code("${String(codeJson.code)}"${ |
|
|
codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : '' |
|
|
})`; |
|
|
} |
|
|
} |
|
|
|