frontend client for gemstone. decentralised workplace app
1import type { AtUri } from "@/lib/types/atproto";
2import { stringToAtUri } from "@/lib/utils/atproto";
3import { getUserShards } from "@/queries/get-shards-from-pds";
4import type { OAuthSession } from "@atproto/oauth-client";
5import { useQuery } from "@tanstack/react-query";
6
7export const useShardsQuery = (session: OAuthSession) => {
8 const queryKey = ["shards", session.did];
9 return {
10 queryKey,
11 useQuery: () =>
12 useQuery({
13 queryKey: queryKey,
14 queryFn: async () => {
15 return await shardsQueryFn(session);
16 },
17 }),
18 };
19};
20
21const shardsQueryFn = async (session: OAuthSession) => {
22 const shards = await getUserShards({
23 pdsEndpoint: session.serverMetadata.issuer,
24 did: session.did,
25 });
26
27 if (!shards.ok) {
28 console.error("shardQueryFn error.", shards.error);
29 throw new Error(
30 `Something went wrong while getting the user's shard records.}`,
31 );
32 }
33
34 const results = shards.data
35 .map((record) => {
36 const convertResult = stringToAtUri(record.uri);
37 if (!convertResult.ok) {
38 console.error(
39 "Could not convert",
40 record,
41 "into at:// URI object.",
42 convertResult.error,
43 );
44 return;
45 }
46 if (!convertResult.data.collection || !convertResult.data.rKey) {
47 console.error(
48 record,
49 "did not convert to a full at:// URI with collection and rkey.",
50 );
51 return;
52 }
53 const uri: Required<AtUri> = {
54 authority: convertResult.data.authority,
55 collection: convertResult.data.collection,
56 rKey: convertResult.data.rKey,
57 };
58 return {
59 cid: record.cid,
60 uriStr: record.uri,
61 uri,
62 value: record.value,
63 };
64 })
65 .filter((atUri) => atUri !== undefined);
66
67 return results;
68};