透過 100+ 個秘訣學習 Nuxt!

webhook-validators
nuxt-webhook-validators

Nuxt 模組,可在邊緣運作,輕鬆驗證來自不同服務的傳入 Webhook。

webhook-validators

Nuxt Webhook 驗證器

npm version npm downloads License Nuxt Modules

一個簡單的 Nuxt 模組,可在邊緣運作,輕鬆驗證來自不同服務的傳入 Webhook。

功能

需求條件

此模組僅適用於作為伺服器 API 路由運行的 Nuxt 伺服器 (nuxt build)。

這表示您無法將此模組與 nuxt generate 一起使用。

快速設定

  1. 在您的 Nuxt 專案中新增 nuxt-webhook-validators
npx nuxi@latest module add webhook-validators
  1. 在您的 nuxt.config.ts 中新增模組
export default defineNuxtConfig({
  modules: [
    'nuxt-webhook-validators'
  ],
})

伺服器工具

驗證器輔助程式會自動匯入到您的 server/ 目錄中。

Webhook 驗證器

所有驗證器輔助程式都會全域公開,並且可以在您的伺服器 API 路由中使用。

這些輔助程式會傳回布林值,指示 Webhook 請求是否有效。

設定可以直接從您的 nuxt.config.ts 中的 runtimeConfig 定義

export default defineNuxtConfig({
  runtimeConfig: {
    webhook: {
      <provider>: {
        <requiredProps>: '',
      }
    }
  }
})

也可以使用環境變數設定

NUXT_WEBHOOK_<PROVIDER>_<REQUIRED_PROPERTY> = ""

前往 playground/.env.exampleplayground/nuxt.config.ts 查看每個供應商所需的所有可用屬性清單。

支援的 Webhook 驗證器

  • Discord
  • Dropbox
  • GitHub
  • GitLab
  • Heroku
  • Hygraph
  • Kick
  • Meta
  • NuxtHub
  • Paddle
  • PayPal
  • Polar
  • Resend
  • Shopify
  • Stripe
  • Svix
  • Twitch

您可以透過在 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