# Build a channel app

Source: https://developers.swell.is/apps/build-a-channel-app-tutorial

A channel app keeps a marketplace or product feed in sync with a Swell sales channel. The merchant connects the app to a channel, and every app on that channel shares its products. This tutorial builds an app that reconciles the whole catalog when Swell sends `sales_channel.mode_updated`, and updates or removes single listings from product events in between. For the rules on active products, modes and overrides, see [Product availability by sales channel](https://developers.swell.is/guides/core-concepts/product-availability-by-sales-channel).

## Create the app

Channel apps need the latest version of the Swell CLI. Update it with `npm install -g @swell/cli`.

```sh
swell create app my_marketplace -t channel -y
```

The CLI sets `"type": "channel"` in `swell.json`, proposes a channel with the app's ID as its slug, and creates two functions, `functions/channel-sync.ts` and `functions/product-sync.ts`, with a `TODO` where your marketplace calls go. The functions on this page are those two, filled in.

```json
{
  "description": "",
  "id": "my_marketplace",
  "name": "My Marketplace",
  "type": "channel",
  "version": "1.0.0",
  "permissions": [],
  "sales_channels": [
    {
      "slug": "my_marketplace"
    }
  ]
}
```

`sales_channels` lists exactly one channel: the one the app proposes to the merchant. A slug has 3 to 64 characters: lowercase letters, digits and single underscores between them, starting with a letter. A channel can also have a display `name` of up to 100 characters, such as `{ "slug": "my_marketplace", "name": "My Marketplace" }`. Without one, a new channel takes the app's name. `swell app push` checks the declaration.

Some slugs are reserved. `online_store` is the built-in Online Store channel, which an app never proposes, and `apps` isn't allowed. Swell names these channels itself: `tiktok` (TikTok), `meta` (Facebook & Instagram), `google`, `amazon`, `ebay`, `walmart` and `pinterest`. Every app for one of these platforms proposes its slug, so they share one channel. Only such an app creates a reserved channel: a merchant's separate channel can't take its slug.

For an existing admin or integration app, set its type to `channel`, add `sales_channels` and add both functions. If the app uses scoped permissions, include `read_products` for the catalog query.

In the examples, `catalogFor(req)` stands for an adapter you write for the external service. It maps product fields to listings and uses the Swell product ID as the listing key. Scope its writes to the listings this app owns for the current store and environment.

## Connect to a channel

An installed channel app has no products until the merchant connects it to a channel on the app's page in the dashboard. The app can't connect itself. The dashboard starts from the channel the app proposes:

- **New channel:** if the slug isn't set up in this environment yet, the merchant creates the channel and chooses its mode: "Only products you add" (`selected`) or "All products, including new ones" (`all`).
- **Existing channel:** if the channel is already set up, for example by another app, the merchant connects this app to it. The channel keeps its name, mode and products. The dashboard shows its product count and the apps that use it.
- **Separate channel:** the merchant can give the app a channel of its own under another free slug, such as `tiktok2`, to manage its products apart from other apps.

The slug an installation uses can differ from the one in `swell.json`, so read it from the event or the app's settings. Each installation uses one channel and can't move to another. The settings, read with `await req.swell.settings()`, hold the channel:

```json
{
  "sales_channels": {
    "my_marketplace": {
      "mode": "selected",
      "name": "My Marketplace"
    }
  }
}
```

Swell sets this key and ignores writes to it. It is `{}` until the merchant connects the app. While the merchant's new channel is being created, its `mode` is `null` for a moment. A channel app can't have a settings group of its own named `sales_channels`.

The merchant switches the mode, or resets the channel's products, on the page of any app that uses the channel. Both apply to the channel, so to every app on it.

## Reconcile the catalog

Suppose a marketplace in `selected` mode lists only a tote. Switching to `all` clears the channel's product overrides and brings in every active product, including a mug the merchant never selected. Swell sends `sales_channel.mode_updated` to the functions of every active app on the channel. The switch sends no product events.

The handler gets `req.data.channel`, `req.data.mode` and `req.data.previous_mode`. The event arrives in these cases:

| What happened | Who gets it | mode / previous_mode |
| --- | --- | --- |
| The merchant created the channel while connecting this app | This app | Chosen mode / null |
| The merchant connected this app to an existing channel | This app | Current / current |
| The merchant switched the channel's mode | Every active app on the channel | New / old |
| The merchant reset the channel's products | Every active app on the channel | Current / current |
| The merchant turned this app back on, or an app update did | This app | Current / current |
| The merchant reinstalled this app with its data kept | This app | Current / current |

To find what to publish now, page through `GET /products` on the Backend API with `$sales_channel: { channel }`. Upsert each result. After all pages and upserts succeed, remove any listing this installation owns whose product ID wasn't in the scan.

```typescript
export const config: SwellConfig = {
  description: 'Reconcile the marketplace catalog',
  model: { events: ['sales_channel.mode_updated'] },
};

export default async function reconcile(req: SwellRequest) {
  const { channel } = req.data;
  if (!channel) return;

  const catalog = catalogFor(req);
  const seen = new Set<string>();
  for (let page = 1; ; page++) {
    const { results, page_count } = await req.swell.get('/products', {
      $sales_channel: { channel },
      limit: 100,
      page,
      sort: 'id asc',
    });
    for (const product of results) {
      await catalog.upsert(product);
      seen.add(product.id);
    }
    if (page >= page_count) break;
  }
  await catalog.removeExcept(seen);
}
```

### Manual resync

A manual resync runs the same scan with the slug from the app's settings. When `sales_channels` is empty, the merchant has yet to connect the app. When its `mode` is `null`, the channel is still being created. In both cases, return before changing any external listings. Once a mode is set, a successful scan with no results means all of this installation's listings should be removed.

```typescript
const { sales_channels = {} } = await req.swell.settings();
const [channel] = Object.keys(sales_channels);
if (!channel || !sales_channels[channel].mode) return;
```

## Sync one product

The merchant now excludes the mug from the channel. The mode stays `all`. Swell sends `product.updated` with `req.data.$in_channel` set to `false`. Remove the mug's listing. The tote stays listed.

```typescript
export const config: SwellConfig = {
  description: 'Sync one marketplace listing',
  model: {
    events: ['product.created', 'product.updated', 'product.deleted'],
  },
};

export default async function (req: SwellRequest) {
  const product = req.data;
  // Deleted since the event: product.deleted follows
  if (!product.id) return;

  const catalog = catalogFor(req);
  if (product.$in_channel) {
    await catalog.upsert(product);
  } else {
    await catalog.remove(product.id);
  }
}
```

`req.data` holds the product as it is when the event is delivered. Swell computes `$in_channel` for the channel this installation uses, by the same rule as `$sales_channel`. A price change on a listed product gives `true`, so the upsert updates its listing. Excluded, inactive and deleted products give `false`, as do all products while the app has no channel or its new channel is being created. Before and after hooks on products also get `$in_channel`. Webhooks don't get it, and can't subscribe to the mode event.

### Changing the selection

An app can include or exclude a product itself, with a product write under its own token that sets `sales_channels.<slug>`. Scoped access needs `write_products`. The change applies to every app on the channel. A hook result can't change it: Swell drops `sales_channels` from the result of a before or after hook on products and saves the rest. Don't write the selection back on every sync event, which can start a loop.

## Lifecycle and retries

The channel belongs to the store. What happens to the app's installation leaves the channel's mode and products as they are.

| The merchant | The app's channel | Mode event |
| --- | --- | --- |
| Installs the app | None yet. The app has no products. | None |
| Connects it to a channel | Set | Yes |
| Turns it off | Kept. The app misses events. | None |
| Turns it back on | Kept | Yes, equal modes |
| Uninstalls it | Kept for a reinstall. The channel stays, even with no apps left. | None |
| Reinstalls it | The same channel again | Yes, equal modes |
| Uninstalls it and clears its app data | Removed from the app. The channel and its products stay. After a reinstall, the merchant connects the app again. | None until connected |

A delivery can repeat. Make upserts reuse the same listing, and treat removing a listing that's already gone as success. Reconcile on every mode event, even when `mode` equals `previous_mode`. Live and test are separate installations with separate channels. A development copy with its own app record is another app, which the merchant connects like any other.

### Large catalogs

Model functions have a 10-second default timeout. If a scan may take longer, have the handler start a workflow with `await req.swell.workflows.create('sync-catalog')`, where `sync-catalog` is a workflow you define. Process one page per step, keep the IDs seen for that run, and remove stale listings after every page has succeeded. If product edits or another mode change overlap the scan, reconcile again after the overlapping work finishes.

### Good to know

- While the channel switches its mode or resets its products, a product write that changes its override is refused with `CHANNEL_BUSY`. Retry a few seconds later.
- A slug that isn't set up in the environment is refused, on writes and in `$sales_channel`. Use the slug from the event or the settings.
- If an app misses a mode event, its next one brings a full sync. The merchant can send one by turning the app off and on.
- A development install (no version) that's reinstalled while connected gets its event before `swell app push` installs its functions again, so no function receives it. Turn the app off and on after the push.
