Created
May 28, 2022 09:33
-
-
Save nadilas/2e0e70605215fc94e50cc7b326993d76 to your computer and use it in GitHub Desktop.
Logtail flush in NextJS api endpoint
This file contains 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
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction | |
import { Node as Logtail } from '@logtail/js'; | |
const logger = new Logtail(process.env.LOGTAIL_SOURCE_TOKEN); | |
export default async function handler(req, res) { | |
const user = { | |
id: 123, | |
name: 'John Doe', | |
}; | |
logger.info( | |
'Handling a request to /api/hello', | |
{ user } // you can log structured data | |
); | |
res.status(200).json({ name: user.name }) | |
await flush(logger, 1000) | |
} | |
const flush = async (l, timeout) => { | |
await condition(() => l.logged() === l.synced(), timeout) | |
} | |
const sleep = (timeout) => { | |
return new Promise((resolve) => { | |
setTimeout(resolve, timeout) | |
}) | |
} | |
const condition = (fn, timeout) => { | |
if (timeout) { | |
return await Promise.race([sleep(timeout).then(() => false), conditionInner(fn).then(() => true)]); | |
} | |
return conditionInner(fn); | |
} | |
const tryUnblockCondition = (fn, resolve) => { | |
// Eager evaluation | |
if (fn()) { | |
resolve(); | |
return; | |
} | |
setTimeout(() => { | |
tryUnblockCondition(fn, resolve) | |
}, 5) | |
} | |
const conditionInner = async (fn) => { | |
return new Promise((resolve) => { | |
tryUnblockCondition(fn, resolve) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment