# Migration guide: Relay-style connections

Audience: Developer

Migration guide for the breaking change from simple list fields to Relay-style Connection objects

## Overview

This guide covers a breaking change in the Pyck GraphQL API where all entity relationship fields now return Relay-style Connection objects instead of simple lists. This change enables consistent cursor-based pagination, filtering, and ordering across all relationships.

## What changed

**Before**: Relationship fields returned simple arrays.

```graphql
type Device {
  devicelocationsdevice: [DeviceLocation!]
  deviceusersdevice: [DeviceUser!]
}
```

**After**: Relationship fields return Connection objects with edges and nodes.

```graphql
type Device {
  deviceLocationsDevice(
    after: Cursor
    first: Int
    before: Cursor
    last: Int
    orderBy: DeviceLocationOrder
    where: DeviceLocationWhereInput
  ): DeviceLocationConnection!
  deviceUsersDevice(
    after: Cursor
    first: Int
    before: Cursor
    last: Int
    orderBy: DeviceUserOrder
    where: DeviceUserWhereInput
  ): DeviceUserConnection!
}
```

## Affected relationship fields

The following relationship fields have been changed to return Connection objects:

### Inventory service

| Type | Field | Connection Type |
|------|-------|-----------------|
| `InventoryItemSet` | `items` | `InventoryItemConnection` |
| `ReplenishmentOrder` | `replenishmentOrderItems` | `ReplenishmentOrderItemConnection` |
| `Repository` | `itemMovementToRepositories` | `ItemMovementConnection` |
| `Repository` | `itemMovementFromRepositories` | `ItemMovementConnection` |
| `Repository` | `repositoryMovementToRepositories` | `RepositoryMovementConnection` |
| `Repository` | `repositoryMovementFromRepositories` | `RepositoryMovementConnection` |
| `Repository` | `repositoryMovementRepositories` | `RepositoryMovementConnection` |
| `Repository` | `repositoryTransactions` | `TransactionConnection` |
| `Repository` | `repositoryStocks` | `StockConnection` |
| `Repository` | `children` | `RepositoryConnection` |

### Management service

| Type | Field | Connection Type |
|------|-------|-----------------|
| `Device` | `deviceLocationsDevice` | `DeviceLocationConnection` |
| `Device` | `deviceUsersDevice` | `DeviceUserConnection` |
| `Location` | `deviceLocationsLocation` | `DeviceLocationConnection` |
| `Tenant` | `tenantUsers` | `UserConnection` |
| `User` | `deviceUsersUsers` | `DeviceUserConnection` |

### Receiving service

| Type | Field | Connection Type |
|------|-------|-----------------|
| `ReceivingInbound` | `inboundItems` | `ReceivingInboundItemConnection` |

### Workflow service

| Type | Field | Connection Type |
|------|-------|-----------------|
| `Workflow` | `workflowSignals` | `WorkflowSignalConnection` |

## Connection object structure

All Connection types follow the Relay specification with this structure:

```graphql
type ExampleConnection {
  """A list of edges."""
  edges: [ExampleEdge]

  """Information to aid in pagination."""
  pageInfo: PageInfo!

  """Identifies the total count of items in the connection."""
  totalCount: Int!
}

type ExampleEdge {
  """The item at the end of the edge."""
  node: Example

  """A cursor for use in pagination."""
  cursor: Cursor!
}

type PageInfo {
  """When paginating forwards, are there more items?"""
  hasNextPage: Boolean!

  """When paginating backwards, are there more items?"""
  hasPreviousPage: Boolean!

  """When paginating backwards, the cursor to continue."""
  startCursor: Cursor

  """When paginating forwards, the cursor to continue."""
  endCursor: Cursor
}
```

## Migration steps

### Step 1: Update query structure

Change your queries to use the `edges { node { ... } }` pattern.

**Before:**

```graphql
query GetTenantUsers {
  tenants(first: 1) {
    edges {
      node {
        id
        name
        tenantusers {
          id
          username
          email
        }
      }
    }
  }
}
```

**After:**

```graphql
query GetTenantUsers {
  tenants(first: 1) {
    edges {
      node {
        id
        name
        tenantUsers {
          edges {
            node {
              id
              username
              email
            }
          }
          totalCount
        }
      }
    }
  }
}
```

The same change also renamed some fields. For example, `tenantusers` is now `tenantUsers`, `devicelocationsdevice` is now `deviceLocationsDevice` and `deviceusersdevice` is now `deviceUsersDevice`. Use the names in the tables above.

### Step 2: Update response handling

Update your client code to handle the new response structure.

**Before (JavaScript):**

```javascript
const users = response.data.tenants.edges[0].node.tenantusers;
users.forEach(user => {
  console.log(user.username);
});
```

**After (JavaScript):**

```javascript
const usersConnection = response.data.tenants.edges[0].node.tenantUsers;
const users = usersConnection.edges.map(edge => edge.node);
users.forEach(user => {
  console.log(user.username);
});

// Or access totalCount
console.log(`Total users: ${usersConnection.totalCount}`);
```

### Step 3: Implement pagination (optional)

Take advantage of the new pagination capabilities.

```graphql
query GetTenantUsersWithPagination($tenantId: ID!, $first: Int, $after: Cursor) {
  tenants(first: 1, where: { id: $tenantId }) {
    edges {
      node {
        id
        name
        tenantUsers(first: $first, after: $after) {
          edges {
            node {
              id
              username
              email
            }
            cursor
          }
          pageInfo {
            hasNextPage
            endCursor
          }
          totalCount
        }
      }
    }
  }
}
```

**Pagination helper (JavaScript):**

```javascript
async function fetchAllUsers(tenantId) {
  const allUsers = [];
  let hasNextPage = true;
  let cursor = null;

  while (hasNextPage) {
    const response = await client.query({
      query: GET_TENANT_USERS,
      variables: { tenantId, first: 50, after: cursor }
    });

    const connection = response.data.tenants.edges[0].node.tenantUsers;
    allUsers.push(...connection.edges.map(e => e.node));

    hasNextPage = connection.pageInfo.hasNextPage;
    cursor = connection.pageInfo.endCursor;
  }

  return allUsers;
}
```

### Step 4: Add filtering and ordering (optional)

Use the new filtering and ordering capabilities on relationship fields.

```graphql
query GetTenantRegularUsers($tenantId: ID!) {
  tenants(first: 1, where: { id: $tenantId }) {
    edges {
      node {
        tenantUsers(
          first: 10
          orderBy: { direction: ASC, field: USERNAME }
          where: { isAdmin: false }
        ) {
          edges {
            node {
              id
              username
              email
            }
          }
          totalCount
        }
      }
    }
  }
}
```

## Complete migration examples

### Example 1: `InventoryItemSet` with items

**Before:**

```graphql
query {
  inventoryItemSets(first: 10) {
    edges {
      node {
        id
        sku
        items {
          id
          sku
          data
        }
      }
    }
  }
}
```

**After:**

```graphql
query {
  inventoryItemSets(first: 10) {
    edges {
      node {
        id
        sku
        items(first: 100) {
          edges {
            node {
              id
              sku
              data
            }
          }
          totalCount
        }
      }
    }
  }
}
```

### Example 2: `ReceivingInbound` with `InboundItems`

**Before:**

```graphql
query {
  receivingInbounds(first: 10) {
    edges {
      node {
        id
        orderID
        inboundItems {
          sku
          quantity
        }
      }
    }
  }
}
```

**After:**

```graphql
query {
  receivingInbounds(first: 10) {
    edges {
      node {
        id
        orderID
        inboundItems {
          edges {
            node {
              sku
              quantity
            }
          }
          totalCount
        }
      }
    }
  }
}
```

### Example 3: Workflow with signals

**Before:**

```graphql
query {
  workflows(first: 10) {
    edges {
      node {
        id
        name
        workflowSignals {
          id
          natsTopic
          temporalSignalType
        }
      }
    }
  }
}
```

**After:**

```graphql
query {
  workflows(first: 10) {
    edges {
      node {
        id
        name
        workflowSignals {
          edges {
            node {
              id
              natsTopic
              temporalSignalType
            }
          }
          totalCount
        }
      }
    }
  }
}
```

### Example 4: Device with locations and users

**Before:**

```graphql
query {
  devices(first: 10) {
    edges {
      node {
        id
        name
        devicelocationsdevice {
          id
          location {
            name
          }
        }
        deviceusersdevice {
          id
          user {
            username
          }
        }
      }
    }
  }
}
```

**After:**

```graphql
query {
  devices(first: 10) {
    edges {
      node {
        id
        name
        deviceLocationsDevice(first: 20) {
          edges {
            node {
              id
              location {
                name
              }
            }
          }
          totalCount
        }
        deviceUsersDevice(first: 20) {
          edges {
            node {
              id
              user {
                username
              }
            }
          }
          totalCount
        }
      }
    }
  }
}
```

## What connections add to relationship fields

All relationship fields now support cursor-based pagination with the `first`, `last`, `before`, and `after` arguments. You can apply WhereInput filters directly on a relationship field to reduce data transfer, and order related items with OrderBy inputs on the relationship itself. The `totalCount` field returns how many related items exist. The connections comply fully with the [Relay Cursor Connections Specification](https://relay.dev/graphql/connections.htm).

## Troubleshooting

### Error: Cannot query field `edges` on type `[User!]`

This error indicates you are using the old query structure. Update your query to use the Connection pattern:

```graphql
# Wrong
users { id }

# Correct
users { edges { node { id } } }
```

### Error: Cannot query field `totalCount`

Ensure you are querying `totalCount` at the Connection level, not inside edges or node:

```graphql
# Wrong
users { edges { totalCount } }

# Correct
users {
  edges { node { id } }
  totalCount
}
```

### Performance considerations

When fetching nested relationships, always use the `first` argument to limit results:

```graphql
# Recommended: Limit nested connections
inventoryItemSets(first: 10) {
  edges {
    node {
      items(first: 50) {  # Limit nested items
        edges { node { id } }
      }
    }
  }
}
```

## Related documentation

- [PageInfo Type](https://docs.pyck.cloud/dev/api/types/pageinfo.md)
- [Relay Cursor Connections Specification](https://relay.dev/graphql/connections.htm)
- [GraphQL Getting Started](https://docs.pyck.cloud/dev/developers/getting-started.md)
