---
name: ibgib-get-pattern
description: Patterns for robustly getting IbGibs from spaces
---

# IbGib Get Pattern Skill

This skill documents the standard pattern for retrieving IbGib objects from a space. Use this pattern to ensure robust error handling, consistent logging, and correct space interaction.

## When to Use

- Whenever you need to `get` one or more IbGibs by their address(es).

## Core Pattern: try..catch..finally

Always wrap retrieval logic in a `try..catch..finally` block to ensure errors are logged and execution state is finalized correctly.

```typescript
const lc = `[${myFunctionName.name}]`;
try {
    if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }

    // ... retrieval logic ...

} catch (error) {
    console.error(`${lc} ${extractErrorMsg(error)}`);
    throw error;
} finally {
    if (logalot) { console.log(`${lc} complete.`); }
}
```

## Space Retrieval Helpers

### Option A: Using `metaspace.get` (Preferred)

Use this when you have access to a `MetaspaceService` (It is often appropriate to provide a fallback to the default local user space, which is what the metaspace provides.)

```typescript
// Ensure space is provided or fallback to local user space
space ??= await metaspace.getLocalUserSpace({ lock: false });
if (!space) {
    throw new Error(`(UNEXPECTED) space falsy and we couldn't get default local user space from metaspace? (E: genuuid)`);
}

const resGet = await metaspace.get({ addrs, space });

// Validate result
if (resGet.success && resGet.ibGibs && resGet.ibGibs.length === addrs.length) {
    return resGet.ibGibs;
} else {
    // Robust error handling using rawResultIbGib
    const resIbGib = resGet.rawResultIbGib as IbGibSpaceResultIbGib<IbGib_V1, IbGibSpaceResultData, IbGibSpaceResultRel8ns>;
    const addrsNotFound = resIbGib?.data?.addrsNotFound ?? 'unknown';
    throw new Error(`couldn't find all addrs. addrsNotFound: ${addrsNotFound}? resGet.errorMsg: ${resGet.errorMsg} (E: genuuid)`);
}
```

### Option B: Using `getFromSpace` (Lower Level)

Use this when `metaspace` is not available, or when working in low-level helpers.

```typescript
import { getFromSpace } from "@ibgib/core-gib/dist/witness/space/space-helper.mjs";

// ... inside try block ...
const resGet = await getFromSpace({ space, addrs });

if (resGet.success && resGet.ibGibs?.length === addrs.length) {
    return resGet.ibGibs!;
} else {
    // Examine rawResultIbGib for more context
    const resIbGib = resGet.rawResultIbGib as IbGibSpaceResultIbGib<IbGib_V1, IbGibSpaceResultData, IbGibSpaceResultRel8ns>;
    if (!resIbGib?.data) {
        throw new Error(`(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: genuuid)`);
    }
    throw new Error(`(UNEXPECTED) couldn't find addrs? addrsNotFound: ${resIbGib.data.addrsNotFound}? space.ib: ${space.ib} (E: genuuid)`);
}
```

## Key Requirements

| Requirement | Detail |
|---|---|
| **Logging** | Define `const lc = \`[\${fn.name}]\`;\` at the start. Log starting/finishing if `logalot` is true. |
| **Error Handling** | Use `extractErrorMsg(error)` in the catch block. Re-throw after logging. |
| **Result Validation** | Always check `resGet.success` AND that the returned `ibGibs` array matches the expected length. |
| **Debugging Context** | When a fetch fails, cast `resGet.rawResultIbGib` to `IbGibSpaceResultIbGib` and include `addrsNotFound` in the error message. |
| **Space Fallback** | When using `metaspace`, consider falling back to `metaspace.getLocalUserSpace({ lock: false })` if no space is provided. |
