import Posthook from '@posthook/node';
import { Signatures, SignatureVerificationError } from '@posthook/node';
const posthook = new Posthook(process.env.POSTHOOK_API_KEY);
const signatures = new Signatures(process.env.POSTHOOK_SIGNING_KEY);
/* 1. Schedule */
async function startVideoEncoding(videoFile) {
// 1. Start the job on the 3rd party API
const job = await transcoderApi.start(videoFile);
// 2. Schedule the first check for 1 minute later
await posthook.hooks.schedule({
path: '/webhooks/check-status',
postIn: '1m',
data: {
jobId: job.id
}
});
}
/* 2. Handle */
app.post('/webhooks/check-status', async (req, res) => {
try {
const delivery = signatures.parseDelivery(req.body, req.headers);
const { jobId } = delivery.data;
const job = await transcoderApi.get(jobId);
if (job.status === 'completed') {
// DONE: Process the result
await db.saveVideo(job.url);
return res.status(200).send('Video processed');
}
if (job.status === 'failed') {
// FAIL: Handle error (maybe alert team)
return res.status(200).send('Job failed');
}
// PENDING: Reschedule check for another minute
await posthook.hooks.schedule({
path: '/webhooks/check-status',
postIn: '1m',
data: { jobId }
});
res.status(200).send('Still pending, rescheduled');
} catch (err) {
if (err instanceof SignatureVerificationError) {
return res.status(401).json({ error: err.message });
}
throw err;
}
});