43 lines
1.3 KiB
Plaintext
43 lines
1.3 KiB
Plaintext
---
|
|
title: Adapter 与分页
|
|
description: 实现可取消的搜索请求,并返回可合并的分组分页结果。
|
|
order: 20
|
|
toc:
|
|
- id: implement-adapter
|
|
title: 实现 Adapter
|
|
- id: group-results
|
|
title: 组织结果
|
|
- id: paginate
|
|
title: 分页
|
|
---
|
|
|
|
## 实现 Adapter {#implement-adapter}
|
|
|
|
`SearchAdapter` 是 Search 唯一的数据依赖:
|
|
|
|
```ts
|
|
const searchAdapter: SearchAdapter = {
|
|
async search({ cursor, query, signal }) {
|
|
const response = await fetch(
|
|
`/api/search?q=${encodeURIComponent(query)}&cursor=${cursor ?? ""}`,
|
|
{ signal }
|
|
)
|
|
|
|
if (!response.ok) throw new Error("Search request failed")
|
|
return response.json()
|
|
},
|
|
}
|
|
```
|
|
|
|
必须把 `signal` 传给底层请求,避免较早的响应覆盖较新的查询。
|
|
|
|
## 组织结果 {#group-results}
|
|
|
|
每个 `SearchPage` 包含若干 `SearchResultGroup`。Group 的 `id` 在分页之间应保持稳定;Item 的 `id` 在所属 Group 内应保持稳定。Search 会用这两个标识合并结果并消除重复项。
|
|
|
|
可以通过 `payload` 携带应用数据,通过 `icon` 或 `image` 自定义结果外观。
|
|
|
|
## 分页 {#paginate}
|
|
|
|
还有后续数据时返回 `nextCursor`;没有更多结果时返回 `null` 或省略。界面只在存在游标时显示“加载更多”。游标可以是字符串或数字,并会原样传回 Adapter。
|