Skip to content

Instantly share code, notes, and snippets.

@Siemko
Created February 24, 2025 09:41
Show Gist options
  • Save Siemko/c7ca7aad4c787fc0d2310c56d309da4a to your computer and use it in GitHub Desktop.
Save Siemko/c7ca7aad4c787fc0d2310c56d309da4a to your computer and use it in GitHub Desktop.
API Idempotence - sample
const app = new Hono().post(
"idempotence",
validator("header", (value, ctx) => {
const idempotencyKey = value["x-idempotency-key"];
if (idempotencyKey == undefined || idempotencyKey === "") {
throw new HTTPException(400, {
message: "X-Idempotency-Key is required",
});
}
return { idempotencyKey };
}),
async (ctx) => {
const { idempotencyKey } = ctx.req.valid("header");
const body = await ctx.req.json();
if (IDEMPOTENCY_CACHE.has(idempotencyKey)) {
return ctx.json(IDEMPOTENCY_CACHE.get(idempotencyKey));
} else {
const response = {
/* ... */
};
IDEMPOTENCY_CACHE.set(idempotencyKey, response);
return ctx.json(response);
}
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment