All files / kernel-ui/src/hooks useRegistry.ts

100% Statements 13/13
100% Branches 0/0
100% Functions 8/8
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                6x 6x     6x 4x   1x     1x     3x               6x   2x 1x 1x   1x                 6x          
import type { KRef } from '@metamask/ocap-kernel';
import { useCallback } from 'react';
 
import { useDatabase } from './useDatabase.ts';
import { usePanelContext } from '../context/PanelContext.tsx';
import { parseObjectRegistry } from '../services/db-parser.ts';
 
/**
 * Hook for registry actions.
 *
 * @returns Registry methods.
 */
export function useRegistry(): {
  fetchObjectRegistry: () => void;
  revoke: (kref: KRef) => void;
} {
  const { callKernelMethod, logMessage, setObjectRegistry } = usePanelContext();
  const { executeQuery } = useDatabase();
 
  // Fetch the kv db and parse it into an object registry
  const fetchObjectRegistry = useCallback((): void => {
    executeQuery('SELECT key, value FROM kv')
      .then((result) => {
        const parsedData = parseObjectRegistry(
          result as { key: string; value: string }[],
        );
        return setObjectRegistry(parsedData);
      })
      .catch((error: Error) =>
        logMessage(
          `Failed to fetch object registry: ${error.message}`,
          'error',
        ),
      );
  }, [executeQuery, logMessage, setObjectRegistry]);
 
  // Revoke an object
  const revoke = useCallback(
    (kref: KRef) => {
      callKernelMethod({ method: 'revoke', params: { kref } })
        .then(() => fetchObjectRegistry())
        .then(() => logMessage(`Revoked object ${kref}`, 'success'))
        .catch((error: Error) =>
          logMessage(
            `Failed to revoke object ${kref}: ${error.message}`,
            'error',
          ),
        );
    },
    [callKernelMethod, logMessage],
  );
 
  return {
    fetchObjectRegistry,
    revoke,
  };
}