透過 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'
  ],
})

伺服器工具

驗證器 helper 會在您的 server/ 目錄中自動匯入。

Webhook 驗證器

所有驗證器 helper 都會全域公開,並可在您的伺服器 API 路由中使用。

這些 helper 會傳回布林值,指示 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
  • Heroku
  • Hygraph
  • Meta
  • NuxtHub
  • Paddle
  • PayPal
  • Polar
  • Stripe
  • 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