@ gesher/ sdk (英语)
盖舍 是 Otomator 的主机网络推取服务: 您的后端发送通知; 这个 SDK 帮助浏览器订阅和接收它们, 而不会在客户端中曝光 API 密钥 .
安装
npm install @gesher/sdk
快开始
-
复制
node_modules/@gesher/sdk/gesher-sw.js(或导入路径)@gesher/sdk/sw用于文件的捆绑解析)到您的站点 公开 根,例如:.public/gesher-sw.js因此,它被服务于/gesher-sw.js。 。 。 . -
指着SDK 后端 URL; 您的服务器代理
api.gesher.pro用熊鼠 API 键.
import { GesherClient } from '@gesher/sdk'
const gesher = new GesherClient({
subscribeEndpoint: '/api/push/subscribe',
unsubscribeEndpoint: '/api/push/unsubscribe',
// Optional: omit to fetch from https://api.gesher.pro/vapid-key
// vapidPublicKey: '...',
})
const result = await gesher.subscribe('user-123')
if (!result.ok) console.error(result.error)
if (await gesher.isSubscribed()) {
// ...
}
await gesher.unsubscribe() // or unsubscribe('user-123')
PWA 安装( 可选)
如果您的应用程序是带有网络应用程序表的进取 Web App, 您可以使用 SDK 助手来抓取 beforeinstallprompt 并显示安装按钮.
const gesher = new GesherClient({
subscribeEndpoint: '/api/push/subscribe',
unsubscribeEndpoint: '/api/push/unsubscribe',
})
// Call once at app startup
gesher.watchInstall()
// Show an "Install App" button when ready
gesher.onInstallStateChange((state) => {
if (state === 'available') showInstallButton()
if (state === 'installed') hideInstallButton()
})
// On button click
document.getElementById('install-btn')!.onclick = async () => {
const result = await gesher.install()
if (result.accepted) console.log('App installed!')
}
后端代理( Express)
你的路线从SDK接收了JSON尸体,并用密钥转发给格舍尔:
app.post('/api/push/subscribe', async (req, res) => {
const r = await fetch('https://api.gesher.pro/subscribe', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.GESHER_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(req.body),
})
res.status(r.status).send(await r.text())
})
未订阅使用相同的 JSON 机构(userId, (中文(简体) ), endpoint与 DELETE数字 :
app.post('/api/push/unsubscribe', async (req, res) => {
const r = await fetch('https://api.gesher.pro/unsubscribe', {
method: 'DELETE',
headers: {
Authorization: `Bearer ${process.env.GESHER_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(req.body),
})
res.status(r.status).send(await r.text())
})
配置
| 选项 | 说明 |
|---|---|
subscribeEndpoint | 您的后端 URL; SDK POST { userId, subscription }。 。 。 . |
unsubscribeEndpoint | 您的后端 URL; SDK POST { userId, endpoint }。 。 。 . |
vapidPublicKey | 可选的 URL 安全基础64 公钥; 如果省略, 从中获取 vapidKeyEndpoint。 。 。 . |
vapidKeyEndpoint | 可选的 默认为 https://api.gesher.pro/vapid-key。 。 。 . |
serviceWorkerPath | 可选的 默认 /gesher-sw.js。 。 。 . |
serviceWorkerScope | 可选的 默认 /。 。 。 . |
类型脚本
配置类型和有效载荷出口自 @gesher/sdk。 。 。 .
文档
更详细的情况: 页:1