Created
June 6, 2024 08:03
-
-
Save EduardoAC/54ff8bca8820d087af2639a9a1ca2bfa to your computer and use it in GitHub Desktop.
Chrome extension - site page review - rating message handler - The goal of this function is to manage all the messages received by the content scripts regarding rating
This file contains 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
import { MessageRate } from "../../../types/message.types" | |
async function updateCacheRating( | |
sendResponse: SendResponseCallback, | |
data?: MessageRate, | |
): Promise<void> { | |
if (typeof data?.url === "string") { | |
try { | |
await chrome.storage.local.set({ [data.url]: data.rate }) | |
return sendResponse({ statusCode: 200 }) | |
} catch (error) { | |
console.log("Update Cache failed", error) | |
return sendResponse({ statusCode: 500 }) | |
} | |
} | |
sendResponse({ statusCode: 400 }) | |
} | |
async function getRateFromCache( | |
sendResponse: SendResponseCallback, | |
data?: MessageRate, | |
) { | |
try { | |
if (typeof data?.url === "string") { | |
const rateObject = await chrome.storage.local.get([data.url]) | |
return sendResponse({ statusCode: 200, data: rateObject[data.url] }) | |
} else { | |
throw new Error("URL must exist to provide rate information") | |
} | |
} catch (error) { | |
console.log("Failed to retrieved rating from cache", error) | |
return sendResponse({ statusCode: 500 }) | |
} | |
} | |
export async function ratingMessageHandler( | |
message: Message<MessageRate>, | |
sendResponse: SendResponseCallback, | |
) { | |
if (message.subType) { | |
switch (message.subType) { | |
case "get": | |
getRateFromCache(sendResponse, message.data) | |
break | |
case "update": | |
updateCacheRating(sendResponse, message.data) | |
break | |
} | |
return | |
} | |
sendResponse({ statusCode: 405 }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The project example of a site page review can be found at https://github.com/EduardoAC/site-review-extension.
Also, the code for the message sender can be found at https://gist.github.com/EduardoAC/000b1e39a6ec10a892e7c6cd93730a53.