code.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import type { Document } from './bson';
  2. import { BSONValue } from './bson_value';
  3. /** @public */
  4. export interface CodeExtended {
  5. $code: string;
  6. $scope?: Document;
  7. }
  8. /**
  9. * A class representation of the BSON Code type.
  10. * @public
  11. * @category BSONType
  12. */
  13. export class Code extends BSONValue {
  14. get _bsontype(): 'Code' {
  15. return 'Code';
  16. }
  17. code: string;
  18. // a code instance having a null scope is what determines whether
  19. // it is BSONType 0x0D (just code) / 0x0F (code with scope)
  20. scope: Document | null;
  21. /**
  22. * @param code - a string or function.
  23. * @param scope - an optional scope for the function.
  24. */
  25. constructor(code: string | Function, scope?: Document | null) {
  26. super();
  27. this.code = code.toString();
  28. this.scope = scope ?? null;
  29. }
  30. toJSON(): { code: string; scope?: Document } {
  31. if (this.scope != null) {
  32. return { code: this.code, scope: this.scope };
  33. }
  34. return { code: this.code };
  35. }
  36. /** @internal */
  37. toExtendedJSON(): CodeExtended {
  38. if (this.scope) {
  39. return { $code: this.code, $scope: this.scope };
  40. }
  41. return { $code: this.code };
  42. }
  43. /** @internal */
  44. static fromExtendedJSON(doc: CodeExtended): Code {
  45. return new Code(doc.$code, doc.$scope);
  46. }
  47. /** @internal */
  48. [Symbol.for('nodejs.util.inspect.custom')](): string {
  49. return this.inspect();
  50. }
  51. inspect(): string {
  52. const codeJson = this.toJSON();
  53. return `new Code("${String(codeJson.code)}"${
  54. codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''
  55. })`;
  56. }
  57. }