Created
February 24, 2025 09:41
-
-
Save Siemko/c7ca7aad4c787fc0d2310c56d309da4a to your computer and use it in GitHub Desktop.
API Idempotence - sample
This file contains hidden or 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
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