import { AtURI, AtURIString, DID, NSID, ValidateNSID } from "./atproto.ts"; const BASEURL = "https://constellation.microcosm.blue"; /** Essentially an AtURI, fed back by Constellation. */ export type Reference = { did: string; collection: string; rkey: string; } /** Raw response type from /links */ type LinksResponse = { total: number; linking_records: Reference[]; cursor: string; }; type Target = AtURIString | DID; /** * Retrieves an array of record references to records containing links to the specified target. * @throws When the provided NSID is invalid. */ export async function getLinks(target: Target, collection: NSID, path: string): Promise { if (ValidateNSID(collection) == null) { throw new Error("invalid NSID for collection parameter"); } const _target = encodeURIComponent(target.toString()!); const _path = encodeURIComponent(path); let cursor = ""; let records: AtURI[] = []; while (cursor != null) { const rsp = await fetch(`${BASEURL}/links?target=${_target.toString()}&collection=${collection}&path=${_path}${cursor ? `&cursor=${cursor}` : ""}`); const data = await rsp.json() as LinksResponse; records = records.concat(data.linking_records.map(x=>new AtURI(x.did, x.collection, x.rkey))); cursor = data.cursor; } return records; }