on d08b4ef help sign in
86 lines 2.4 kB history raw
1import UrbitApi from '@urbit/http-api';
2import type { ContactUpdate, Patp, Group, Contact, Rolodex } from '@urbit/api';
3import _get from 'lodash/get';
4import { compose } from 'lodash/fp';
6import { normalizeId } from './id';
8console.log(`Initializing Urbit API at ${Date()}`);
9const api: UrbitApi = new UrbitApi('', '', window.desk);
10api.ship = window.ship;
11// api.connect();
13export function scry<T = any>(path: string): Promise<T> {
14 return api.scry<T>({ app: 'astrolabe', path });
17export function getPoint(patp: string): Promise<any> {
18 return scry<any>(`/point/${patp}`);
21export function getSpawnedPoints(patp: string): Promise<any> {
22 return scry<any>(`/point/${patp}/spawned`);
25export function getPeers(): Promise<any> {
26 return scry<any>(`/peers`);
29export async function searchPoints(search: string): Promise<Patp[]> {
30 const { points } = await scry<any>(`/search/${search}`);
31 return points.map(normalizeId);
34export function getDoc(path: string): Promise<string> {
35 return scry<string>(`/doc/${path}`);
38export function initialContacts(json: ContactUpdate, contacts: Rolodex): Rolodex {
39 const data = _get(json, 'initial', false);
40 if (data) {
41 contacts = data.rolodex;
42 }
43 return contacts;
44};
46export function addContact(json: ContactUpdate, contacts: Rolodex): Rolodex {
47 const data = _get(json, 'add', false);
48 if (data) {
49 contacts[data.ship] = data.contact;
50 }
51 return contacts;
52};
54export function removeContact(json: ContactUpdate, contacts: Rolodex): Rolodex {
55 const data = _get(json, 'remove', false);
56 if (
57 data &&
58 (data.ship in contacts)
59 ) {
60 delete contacts[data.ship];
61 }
62 return contacts;
63};
65export function handleContactUpdateEvent(updateContacts) {
66 return ({ 'contact-update': contactUpdate }) => {
67 console.log(`received contact-update: ${Object.keys(contactUpdate)}`)
68 const reducers = [initialContacts, addContact, removeContact];
69 const reducer = compose(reducers.map(r => sta => r(contactUpdate, sta)));
70 updateContacts(reducer);
71 };
74export function subscribeToContacts(e: (data: any) => void): Promise<any> {
75 return api.subscribe({
76 app: 'contact-store',
77 path: '/all',
78 event: handleContactUpdateEvent(e),
79 err: () => {
80 console.error(`Subscription to contact-store/all just get "err"`);
81 },
82 quit: () => {
83 console.error(`Subscription to contact-store/all just get "quit"`)
84 }
85 })