笔记
截至2023年2月22日,Vercel正式提供内置CRON作业,以触发您的无服务器和边缘功能。阅读文档以了解更多信息。请记住,该功能仅在Beta阶段免费免费,这将是一般可用性的付费功能,这意味着GitHub Action Route将与完全免费的选项相关。
Next.js应用程序的Cron作业。
由于Vercel平台是由事件驱动的,因此不维护运行服务器,因此您无法在下一个.js应用程序中真正安排在API路由或无服务器功能上的电话。尽管有许多预先存在的服务提供了预定的Cron作业,但我最终决定GitHub Actions适合我的需求,因为它与已经居住在Github上的任何项目都很好地集成了,而且它是完全免费的。
所有GitHub操作都位于您的存储库的目录.github/workflows/中,并用YAML编写。
.github/workflows/starter.yaml是最基本的工作流程,可帮助您开始动作。
通过计划的事件,您可以按指定的间隔执行任务。例如,提供的工作流程.github/workflows/scheduled.yaml每60分钟执行卷曲的HTTP请求。
name : Hourly cron job
on :
schedule :
- cron : ' */60 * * * * '
jobs :
cron :
runs-on : ubuntu-latest
steps :
- name : Hourly cron job
run : |
curl --request POST
--url 'https://example.com/api/task'
--header 'Authorization: Bearer ${{ secrets.ACTION_KEY }}'如果您写Cron计划表达式遇到困难,请看一下Crontab Guru。
API路由和无服务器功能为使用Vercel上的Next.js构建API提供了一种直接的解决方案。文件夹pages/api中的任何文件均映射到/api/* ,并将视为API端点而不是page 。
如果您使用的是无服务器功能,则无论运行时如何,都需要将文件放入项目的根部/api/ Directory中。
要使用GITHUB操作安全触发API路由和无服务器功能,您需要在API调用标题中提供授权密钥,当执行时,该键与Next.js应用程序中的相应密钥相比。
您可以通过将加密的秘密添加到GitHub存储库中,并使用HTTP请求的标题将其添加来实现这一目标,如先前的代码段所示。除了将密钥添加到github存储库中,您还需要在下一个js应用程序中访问它,最好通过环境变量访问。
示例pages/api/example.js实现此授权流。
export default function handler ( req , res ) {
const { APP_KEY } = process . env ;
const { ACTION_KEY } = req . headers . authorization . split ( " " ) [ 1 ] ;
try {
if ( ACTION_KEY === APP_KEY ) {
// Process the POST request
res . status ( 200 ) . json ( { success : 'true' } )
} else {
res . status ( 401 )
}
} catch ( err ) {
res . status ( 500 )
}
}使用pages/api/example.ts进行打字稿。
import type { NextApiRequest , NextApiResponse } from 'next'
export default function handler ( req : NextApiRequest , res : NextApiResponse ) {
const { APP_KEY } = process . env ;
const { ACTION_KEY } = req . headers . authorization . split ( " " ) [ 1 ] ;
try {
if ( ACTION_KEY === APP_KEY ) {
// Process the POST request
res . status ( 200 ) . json ( { success : 'true' } )
} else {
res . status ( 401 )
}
} catch ( err ) {
res . status ( 500 )
}
}