| | import type { Document } from './bson'; |
| | import { BSONValue } from './bson_value'; |
| | import type { EJSONOptions } from './extended_json'; |
| | import type { ObjectId } from './objectid'; |
| |
|
| | |
| | export interface DBRefLike { |
| | $ref: string; |
| | $id: ObjectId; |
| | $db?: string; |
| | } |
| |
|
| | |
| | export function isDBRefLike(value: unknown): value is DBRefLike { |
| | return ( |
| | value != null && |
| | typeof value === 'object' && |
| | '$id' in value && |
| | value.$id != null && |
| | '$ref' in value && |
| | typeof value.$ref === 'string' && |
| | |
| | (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')) |
| | ); |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | export class DBRef extends BSONValue { |
| | get _bsontype(): 'DBRef' { |
| | return 'DBRef'; |
| | } |
| |
|
| | collection!: string; |
| | oid!: ObjectId; |
| | db?: string; |
| | fields!: Document; |
| |
|
| | |
| | |
| | |
| | |
| | |
| | constructor(collection: string, oid: ObjectId, db?: string, fields?: Document) { |
| | super(); |
| | |
| | const parts = collection.split('.'); |
| | if (parts.length === 2) { |
| | db = parts.shift(); |
| | |
| | collection = parts.shift()!; |
| | } |
| |
|
| | this.collection = collection; |
| | this.oid = oid; |
| | this.db = db; |
| | this.fields = fields || {}; |
| | } |
| |
|
| | |
| | |
| |
|
| | |
| | get namespace(): string { |
| | return this.collection; |
| | } |
| |
|
| | set namespace(value: string) { |
| | this.collection = value; |
| | } |
| |
|
| | toJSON(): DBRefLike & Document { |
| | const o = Object.assign( |
| | { |
| | $ref: this.collection, |
| | $id: this.oid |
| | }, |
| | this.fields |
| | ); |
| |
|
| | if (this.db != null) o.$db = this.db; |
| | return o; |
| | } |
| |
|
| | |
| | toExtendedJSON(options?: EJSONOptions): DBRefLike { |
| | options = options || {}; |
| | let o: DBRefLike = { |
| | $ref: this.collection, |
| | $id: this.oid |
| | }; |
| |
|
| | if (options.legacy) { |
| | return o; |
| | } |
| |
|
| | if (this.db) o.$db = this.db; |
| | o = Object.assign(o, this.fields); |
| | return o; |
| | } |
| |
|
| | |
| | static fromExtendedJSON(doc: DBRefLike): DBRef { |
| | const copy = Object.assign({}, doc) as Partial<DBRefLike>; |
| | delete copy.$ref; |
| | delete copy.$id; |
| | delete copy.$db; |
| | return new DBRef(doc.$ref, doc.$id, doc.$db, copy); |
| | } |
| |
|
| | |
| | [Symbol.for('nodejs.util.inspect.custom')](): string { |
| | return this.inspect(); |
| | } |
| |
|
| | inspect(): string { |
| | |
| | const oid = |
| | this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); |
| | return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${ |
| | this.db ? `, "${this.db}"` : '' |
| | })`; |
| | } |
| | } |
| |
|