code.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import type { Document } from './bson';
  2. /** @public */
  3. export interface CodeExtended {
  4. $code: string | Function;
  5. $scope?: Document;
  6. }
  7. /**
  8. * A class representation of the BSON Code type.
  9. * @public
  10. * @category BSONType
  11. */
  12. export class Code {
  13. _bsontype!: 'Code';
  14. code!: string | Function;
  15. scope?: Document;
  16. /**
  17. * @param code - a string or function.
  18. * @param scope - an optional scope for the function.
  19. */
  20. constructor(code: string | Function, scope?: Document) {
  21. if (!(this instanceof Code)) return new Code(code, scope);
  22. this.code = code;
  23. this.scope = scope;
  24. }
  25. toJSON(): { code: string | Function; scope?: Document } {
  26. return { code: this.code, scope: this.scope };
  27. }
  28. /** @internal */
  29. toExtendedJSON(): CodeExtended {
  30. if (this.scope) {
  31. return { $code: this.code, $scope: this.scope };
  32. }
  33. return { $code: this.code };
  34. }
  35. /** @internal */
  36. static fromExtendedJSON(doc: CodeExtended): Code {
  37. return new Code(doc.$code, doc.$scope);
  38. }
  39. /** @internal */
  40. [Symbol.for('nodejs.util.inspect.custom')](): string {
  41. return this.inspect();
  42. }
  43. inspect(): string {
  44. const codeJson = this.toJSON();
  45. return `new Code("${String(codeJson.code)}"${
  46. codeJson.scope ? `, ${JSON.stringify(codeJson.scope)}` : ''
  47. })`;
  48. }
  49. }
  50. Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' });