import type { Document } from "./bson.ts";import { EJSONOptions } from "./extended_json.ts";import type { ObjectId } from "./objectid.ts";import { isObjectLike } from "./parser/utils.ts";
export interface DBRefLike { $ref: string; $id: ObjectId; $db?: string;}
export function isDBRefLike(value: unknown): value is DBRefLike { return ( isObjectLike(value) && value.$id != null && typeof value.$ref === "string" && (value.$db == null || typeof value.$db === "string") );}
export class DBRef { _bsontype = "DBRef"; collection!: string; oid!: ObjectId; db?: string; fields!: Document;
constructor( collection: string, oid: ObjectId, db?: string, fields?: Document, ) { 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 || {}; }
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("Deno.customInspect")](): string { const oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); return `new DBRef("${this.collection}", new ObjectId("${oid}")${ this.db ? `, "${this.db}"` : "" })`; }}