Created
April 11, 2024 08:22
-
-
Save leongkui/b23a49739e7d4598b8754bec72acc8cc to your computer and use it in GitHub Desktop.
Next.JS FireAndForget background long running
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { getLogger } from '@core-ui/lib/logger'; | |
| import { NextApiRequest, NextApiResponse } from 'next'; | |
| import { apiHandler } from '@core-ui/lib/apiHandler'; | |
| import { internal_runWithWaitUntil as waitUntil } from 'next/dist/server/web/internal-edge-wait-until'; | |
| // WARNING: This api handler uses next internal function that is not designed for production | |
| // https://github.com/vercel/next.js/issues/50522#issuecomment-1838593482 | |
| const getHandler = async (req: NextApiRequest, res: NextApiResponse): Promise<NextApiResponse> => { | |
| const logger = getLogger('/api/sitemap.ts:GET'); | |
| logger.info('Fire and Forget triggered'); | |
| const apiSecret = req.query.secret; | |
| logger.debug(apiSecret, 'apiSecret'); | |
| if (!process.env.API_SECRET) { | |
| logger.error('API_SECRET is not set'); | |
| return res.status(500).end(); | |
| } | |
| if (apiSecret !== process.env.API_SECRET) { | |
| logger.error('API_SECRET is incorrect'); | |
| return res.status(401).end(); | |
| } | |
| waitUntil(async () => { | |
| // sleep for 30 seconds to simulate a long running task | |
| // eslint-disable-next-line no-promise-executor-return | |
| await new Promise(timesUp => setTimeout(timesUp, 60000)); | |
| logger.info('Done waiting'); | |
| }); | |
| logger.info('Forget about it'); | |
| return res.status(200).end(); | |
| }; | |
| export default apiHandler({ | |
| GET: Promise.resolve({ default: getHandler }), | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment