Skip to main content
Temporary resources like shareable links, export files, or beta accounts need lifecycle management. Instead of running a nightly cleanup job, you can schedule the deletion at the exact moment of creation.

Workflow

  1. Schedule: When you create a resource, schedule its deletion for X hours later.
  2. Handle: Delete the resource.
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 createShareableLink(fileId) {
  // 1. Create the temporary link
  const linkToken = await db.createLink({ fileId });

  // 2. Schedule expiration for 24 hours
  await posthook.hooks.schedule({
    path: '/webhooks/expire-link',
    postIn: '24h',
    data: {
      token: linkToken
    }
  });

  return linkToken;
}

/* 2. Handle */
app.post('/webhooks/expire-link', async (req, res) => {
  try {
    const delivery = signatures.parseDelivery(req.body, req.headers);

    const { token } = delivery.data;

    // Check if it was already manually deleted?
    const link = await db.getLink(token);
    if (!link) {
      return res.status(200).send('Already deleted');
    }

    // Perform the cleanup
    await db.deleteLink(token);

    res.status(200).send('Resource expired');
  } catch (err) {
    if (err instanceof SignatureVerificationError) {
      return res.status(401).json({ error: err.message });
    }
    throw err;
  }
});