Skip to content

Instantly share code, notes, and snippets.

@nadilas
Created May 28, 2022 09:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nadilas/2e0e70605215fc94e50cc7b326993d76 to your computer and use it in GitHub Desktop.
Save nadilas/2e0e70605215fc94e50cc7b326993d76 to your computer and use it in GitHub Desktop.
Logtail flush in NextJS api endpoint
// 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