Skip to content

Instantly share code, notes, and snippets.

@mcalavera81
Created August 12, 2021 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcalavera81/c7cb3bbdb7ee99a4b4b262d68ad0a546 to your computer and use it in GitHub Desktop.
Save mcalavera81/c7cb3bbdb7ee99a4b4b262d68ad0a546 to your computer and use it in GitHub Desktop.
request deduplication
function UpdateChatRoom(req: UpdateChatRoomRequest): ChatRoom {
if (req.requestId === undefined) { // #A
return ChatRoom.update(...);
}
const hash = crypto.createHash('sha256').update(JSON.stringify(req)).digest('hex');
const cachedResponse = cache.get(req.requestId);
if (!cachedResult) { // #B
const response = ChatRoom.update(...);
cache.set(req.requestId, { response, hash }); // #C
return response;
}
if (hash == cachedResult.hash) { // #D
return cachedResult.response;
} else {
throw new Error('409 Conflict'); // #E
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment