on 74331e0 help sign in
92 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();
13function scry<T = any>(path: string): Promise<T> {
14 return api.scry<T>({ app: 'astrolabe', path });
17function getPoint(patp: string): Promise<any> {
18 return scry<any>(`/point/${patp}`);
21function getSpawnedPoints(patp: string): Promise<any> {
22 return scry<any>(`/point/${patp}/spawned`);
25async function searchPoints(search: string): Promise<Patp[]> {
26 const { points } = await scry<any>(`/search/${search}`);
27 return points.map(normalizeId);
30function getDoc(path: string): Promise<string> {
31 return scry<string>(`/doc/${path}`);
34function initialContacts(json: ContactUpdate, contacts: Rolodex): Rolodex {
35 const data = _get(json, 'initial', false);
36 if (data) {
37 contacts = data.rolodex;
38 }
39 return contacts;
40};
42function addContact(json: ContactUpdate, contacts: Rolodex): Rolodex {
43 const data = _get(json, 'add', false);
44 if (data) {
45 contacts[data.ship] = data.contact;
46 }
47 return contacts;
48};
50function removeContact(json: ContactUpdate, contacts: Rolodex): Rolodex {
51 const data = _get(json, 'remove', false);
52 if (
53 data &&
54 (data.ship in contacts)
55 ) {
56 delete contacts[data.ship];
57 }
58 return contacts;
59};
61function handleContactUpdateEvent(updateContacts) {
62 return ({ 'contact-update': contactUpdate }) => {
63 console.log(`received contact-update: ${Object.keys(contactUpdate)}`)
64 const reducers = [initialContacts, addContact, removeContact];
65 const reducer = compose(reducers.map(r => sta => r(contactUpdate, sta)));
66 updateContacts(reducer);
67 };
70function subscribeToContacts(e: (data: any) => void): Promise<any> {
71 return api.subscribe({
72 app: 'contact-store',
73 path: '/all',
74 event: handleContactUpdateEvent(e),
75 err: () => {
76 console.error(`Subscription to contact-store/all just get "err"`);
77 },
78 quit: () => {
79 console.error(`Subscription to contact-store/all just get "quit"`)
80 }
81 })
84export {
85 api,
86 scry,
87 getPoint,
88 getSpawnedPoints,
89 searchPoints,
90 getDoc,
91 subscribeToContacts,
92};