decentralised sync engine
at main 2.3 kB view raw
1import { CONSTELLATION_URL } from "@/lib/env"; 2import type { AtUri } from "@/lib/types/atproto"; 3import type { 4 ConstellationBacklink, 5 ConstellationBacklinkResponse, 6} from "@/lib/types/constellation"; 7import { constellationBacklinkResponseSchema } from "@/lib/types/constellation"; 8import { getRecordFromFullAtUri } from "@/lib/utils/atproto"; 9import type { Result } from "@/lib/utils/result"; 10import type { ZodError } from "zod"; 11 12export const getConstellationBacklink = async ({ 13 subject, 14 source, 15}: { 16 subject: string; 17 source: { 18 nsid: string; 19 fieldName?: string; 20 }; 21}): Promise< 22 Result< 23 ConstellationBacklinkResponse, 24 ZodError | { message: string; fetchStatus: number } 25 > 26> => { 27 const { nsid, fieldName } = source; 28 const sourceParam = fieldName ? `${nsid}:${fieldName}` : nsid; 29 const req = new Request( 30 `${CONSTELLATION_URL.origin}/xrpc/blue.microcosm.links.getBacklinks?subject=${encodeURIComponent(subject)}&source=${encodeURIComponent(sourceParam)}`, 31 ); 32 const res = await fetch(req); 33 34 if (!res.ok) 35 return { 36 ok: false, 37 error: { 38 message: "Fetch request to Constellation did not return 200.", 39 fetchStatus: res.status, 40 }, 41 }; 42 43 const data: unknown = await res.json(); 44 45 const { 46 success, 47 error, 48 data: constellationResponse, 49 } = constellationBacklinkResponseSchema.safeParse(data); 50 51 if (!success) { 52 return { ok: false, error }; 53 } else return { ok: true, data: constellationResponse }; 54}; 55 56export const getPdsRecordFromBacklink = async ( 57 backlink: ConstellationBacklink, 58): Promise<Result<unknown, unknown>> => { 59 const atUri = createAtUriFromBacklink(backlink); 60 const atUriRecordResult = await getRecordFromFullAtUri(atUri); 61 if (!atUriRecordResult.ok) 62 return { ok: false, error: atUriRecordResult.error }; 63 return { ok: true, data: atUriRecordResult.data }; 64}; 65 66export const createAtUriFromBacklink = ( 67 backlink: ConstellationBacklink, 68): Required<AtUri> => { 69 const { did: authority, collection, rkey: rKey } = backlink; 70 71 // @ts-expect-error tempalte literal issues 72 return { authority, collection, rKey }; 73};