From 611bdaa02d1266439ad11053993c47716a0d5eee Mon Sep 17 00:00:00 2001 From: vilicvane Date: Mon, 16 Oct 2023 20:31:47 +0800 Subject: [PATCH] Add webhook --- docs/.vitepress/config.js | 1 + docs/script/examples/digshare-scripts.md | 1 + docs/script/webhook.md | 73 ++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 docs/script/webhook.md diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.js index f0f542a..bd1afdb 100644 --- a/docs/.vitepress/config.js +++ b/docs/.vitepress/config.js @@ -56,6 +56,7 @@ gtag('config', 'G-HD5ZM67WNQ'); {text: '定时执行', link: '/script/scheduling.md'}, {text: '添加依赖', link: '/script/dependencies.md'}, {text: '调试脚本', link: '/script/debugging.md'}, + {text: 'Webhook', link: '/script/webhook.md'}, {text: '状态 State', link: '/script/state.md'}, {text: '消息 Message', link: '/script/message.md'}, {text: '高级用法', link: '/script/advanced-usages.md'}, diff --git a/docs/script/examples/digshare-scripts.md b/docs/script/examples/digshare-scripts.md index effa3bb..7476425 100644 --- a/docs/script/examples/digshare-scripts.md +++ b/docs/script/examples/digshare-scripts.md @@ -2,6 +2,7 @@ > 以下脚本基本为 TypeScript 编写。 +- [Webhook 消息](https://github.com/digshare-scipts/webhook-message) - [雪球用户自选股票更新](https://github.com/digshare-scripts/xueqiu-stock-picks) - [V2EX 爆贴推送](https://github.com/digshare-scripts/v2ex-trending) - [GitHub 中文项目趋势](https://github.com/digshare-scripts/github-trending-chinese-projects) diff --git a/docs/script/webhook.md b/docs/script/webhook.md new file mode 100644 index 0000000..c367b80 --- /dev/null +++ b/docs/script/webhook.md @@ -0,0 +1,73 @@ +# Webhook + +盯梢支持通过 webhook 调用脚本,支持调用参数(query string 和 body)和设定返回内容。 + +## 获取 webhook + +```sh +npx dss webhook +npx dss webhook --debug # 获取调试环境对应的 webhook +``` + +## 读取参数 + +盯梢 webhook 将 query string 和 body 参数合并为 `params` 对象,其中 query string 优先级更高,body 则支持 `application/json` 和 `application/x-www-form-urlencoded` 两种格式。 + +在脚本中,可以通过第二个参数的 `params` 属性获得: + +```js +import {script} from '@digshare/script'; + +export default script((_state, {params: {message}}) => { + return { + message: `这是来自 webhook 的消息:${message}`, + }; +}); +``` + +在调试时,可以通过 `--params` 选项传递参数: + +```sh +# 使用 URL 编码 +npx dss local-run --params message=hello +# 使用 JSON 格式 +npx dss local-run --params {\"message\":\"hello\"} + +# 其他支持 --params 的命令/参数组合 +npx dss run --params message=hello +npx dss deploy --run --params message=hello +npx dss deploy --dry-run --params message=hello +``` + +## 返回内容 + +如果调用 webhook 的服务要求特定的返回内容,可以通过 `response` 属性传递: + +```js +import {script} from '@digshare/script'; + +export default script(() => { + return { + response: '这是返回内容', + }; +}); +``` + +也可以设置特定的响应头,比如想返回 JSON 格式的内容,建议同时设定 `content-type` 响应头: + +```js +import {script} from '@digshare/script'; + +export default script(() => { + return { + response: { + headers: { + 'content-type': 'application/json', + }, + body: JSON.stringify({ + status: 'ok', + }), + }, + }; +}); +```