一个简单的 Nuxt 模块,可在边缘运行,轻松验证来自不同服务的传入 Webhook。
此模块仅适用于运行 Nuxt 服务器时使用服务器 API 路由 (nuxt build)。
这意味着您不能将此模块与 nuxt generate 一起使用。
npx nuxi@latest module add webhook-validators
nuxt.config.ts 中添加模块export default defineNuxtConfig({
modules: [
'nuxt-webhook-validators'
],
})
验证器辅助函数会在您的 server/ 目录中自动导入。
所有验证器辅助函数都全局公开,可用于您的服务器 API 路由。
这些辅助函数返回一个布尔值,指示 Webhook 请求是否有效。
配置可以直接在您的 nuxt.config.ts 中的 runtimeConfig 中定义
export default defineNuxtConfig({
runtimeConfig: {
webhook: {
<provider>: {
<requiredProps>: '',
}
}
}
})
也可以使用环境变量设置
NUXT_WEBHOOK_<PROVIDER>_<REQUIRED_PROPERTY> = ""
前往 playground/.env.example 或 playground/nuxt.config.ts 查看每个提供者所需的所有可用属性列表。
您可以通过在 src/runtime/server/lib/validators/ 中创建一个新文件来添加您喜欢的 Webhook 验证器
在服务器 API 路由中验证 GitHub Webhook。
~/server/api/webhooks/github.post.ts
export default defineEventHandler(async (event) => {
const isValidWebhook = await isValidGitHubWebhook(event)
if (!isValidWebhook) {
throw createError({ statusCode: 401, message: 'Unauthorized: webhook is not valid' })
}
// Some logic...
return { isValidWebhook }
})
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Develop with the playground
npm run dev
# Build the playground
npm run dev:build
# Run ESLint
npm run lint
# Run Vitest
npm run test
npm run test:watch
# Run typecheck
npm run test:types
# Release new version
npm run release