Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

1.7 KB
Raw Blame
import { useIsAuthenticated } from '@core/context/user';
import { throwOnErr } from '@core/util/result';
import {
  type ItemType,
  itemTypeToReferenceEntityType,
  storageServiceClient,
} from '@service-storage/client';
import type { ApiAttachmentEntityReference } from '@service-storage/generated/schemas/apiAttachmentEntityReference';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { attachmentReferencesKeys } from './keys';

const ATTACHMENT_REFERENCES_STALE_TIME = 60 * 1000;

async function fetchAttachmentReferences(
  entityType: ItemType,
  entityId: string
): Promise<ApiAttachmentEntityReference[]> {
  const response = await throwOnErr(() =>
    storageServiceClient.attachmentReferences({
      entity_type: itemTypeToReferenceEntityType(entityType),
      entity_id: entityId,
    })
  );

  return response.references;
}

// Cached callbacks outlive the caller; only plain values enter here.
function attachmentReferencesQueryOptions(
  type: ItemType,
  id: string | null | undefined
) {
  return {
    queryKey: id
      ? attachmentReferencesKeys.list(type, id).queryKey
      : attachmentReferencesKeys.list._def,
    queryFn: () => {
      if (!id) {
        throw new Error('Entity ID is required to fetch attachment references');
      }
      return fetchAttachmentReferences(type, id);
    },
    staleTime: ATTACHMENT_REFERENCES_STALE_TIME,
    enabled: !!id,
  };
}

export function useAttachmentReferencesQuery(
  entityId: Accessor<string | null | undefined>,
  entityType: Accessor<ItemType>
) {
  const authenticated = useIsAuthenticated();
  return useQuery(() =>
    attachmentReferencesQueryOptions(
      entityType(),
      authenticated() === true ? entityId() : undefined
    )
  );
}