Skip to content

Script Example

在这里例子中,我们将会从 hacker news 中获取前 10 个故事,并保存到 NEWS 表格中。

表格准备

我们需要一个表格存储 hacker news 的数据,这个表格需要具备以下字段:

  • id: 故事的 ID
  • title: 故事的标题
  • url: 故事的 URL
  • score: 故事的评分
  • by: 故事的作者
  • time: 故事的时间

Bindings

我们通过 Bindings 来绑定 NEWS 表格。

这样我们可以直接使用 eidos.currentSpace.NEWS.rows.query() 来获取数据。

notify

我们通过 eidos.currentSpace.notify() 来发送通知。 消息会在右下角弹出。方便用户知晓当前脚本的状态。

完整代码

// 定义输入输出的类型
interface HNItem {
id: number;
title: string;
url: string;
score: number;
by: string;
time: number;
}
export const commands = [
{
name: "default",
description: "Fetch HackerNews Top 10 and save to NEWS table",
outputJSONSchema: {
type: "object",
properties: {
success: { type: "boolean" },
message: { type: "string" },
savedItems: {
type: "array",
items: {
type: "object",
properties: {
id: { type: "number" },
title: { type: "string" },
},
},
},
},
},
},
];
async function fetchHNItem(id: number): Promise<HNItem> {
const response = await fetch(
`https://hacker-news.firebaseio.com/v0/item/${id}.json`
);
return response.json();
}
async function fetchTopStories(): Promise<number[]> {
const response = await fetch(
"https://hacker-news.firebaseio.com/v0/topstories.json"
);
return response.json();
}
export default async function (input: Input, context: Context) {
try {
// 获取前10个故事的ID
const topStoryIds = await fetchTopStories();
const top10Ids = topStoryIds.slice(0, 10);
// 获取每个故事的详细信息
const stories = await Promise.all(top10Ids.map((id) => fetchHNItem(id)));
// 保存到NEWS表
const savedItems: any[] = [];
for (const story of stories) {
const existing = await eidos.currentSpace.NEWS.rows.query({
id: story.id,
});
if (existing.length === 0) {
// 如果不存在,则创建新记录
await eidos.currentSpace.NEWS.rows.create({
id: story.id,
title: story.title,
url: story.url || "",
score: story.score,
by: story.by,
time: story.time,
});
savedItems.push({
id: story.id,
title: story.title,
});
}
}
// 发送通知
eidos.currentSpace.notify({
title: "HackerNews Top 10 Updated",
description: `Successfully saved ${savedItems.length} new stories`,
});
return {
success: true,
message: `Successfully saved ${savedItems.length} new stories`,
savedItems,
};
} catch (error) {
eidos.currentSpace.notify({
title: "Error",
description: `Failed to fetch and save HackerNews stories: ${error.message}`,
});
return {
success: false,
message: `Error: ${error.message}`,
savedItems: [],
};
}
}