Savelist Store Methods
verifySaveListHealth
Method Definition
async verifySaveListHealth() {
if (!this.savelist_api_healthy) {
useStateModifier(this.savelist_page_state, "loading");
try {
const response = await useAjaxEcom("/saved-lists/\_ping", {
method: "get",
});
if (response.data.msg === "OK") {
this.savelist_api_healthy = true;
useStateModifier(this.savelist_page_state, "success");
}
if (response.success === false) {
this.savelist_api_healthy = false;
useStateModifier(this.savelist_page_state, "failed");
throw response.errors[0];
}
}
catch (err) {
await useErrorHandler(err);
}
}
}
Description
The verifySaveListHealth method is an asynchronous function that checks the health status of the Save List API. It sends a GET request to the /saved-lists/_ping endpoint to verify if the API is operational. Based on the response, the method updates the health status (savelist_api_healthy) and modifies the savelist_page_state accordingly. If the API is healthy, it proceeds successfully; otherwise, it throws an error and handles it.
Purpose
This method ensures that the Save List API is functioning properly before any operations related to save lists are performed. It provides feedback on the API's status through the savelist_page_state variable.
Parameters
This method does not take any parameters.
Key Dependencies
useAjaxEcom: A utility function used to make AJAX requests to the Save List API.useStateModifier: A helper function that updates thesavelist_page_stateto reflect the current state of the operation (loading,success, orfailed).useErrorHandler: A utility function used to handle errors when the API call fails.
Workflow
- If
savelist_api_healthyis alreadytrue, the method exits early. - Sets
savelist_page_stateto"loading"usinguseStateModifier. - Sends a
GETrequest to/saved-lists/_pingusinguseAjaxEcom. - Handles the response:
- If
response.data.msgis"OK", setssavelist_api_healthytotrueand updatessavelist_page_stateto"success". - If
response.successisfalse, setssavelist_api_healthytofalse, updatessavelist_page_stateto"failed", and throws the first error inresponse.errors.
- If
- Catches any errors thrown during the process and passes them to
useErrorHandler.
Return Value
This method does not return any value. Instead, it updates the state variables:
savelist_api_healthy(boolean): Reflects the health status of the Save List API.savelist_page_state(string): Indicates the current state (loading,success, orfailed).
Example Usage
async function checkSaveListStatus() {
await verifySaveListHealth();
if (this.savelist_api_healthy) {
console.log("Save List API is operational.");
} else {
console.error("Save List API is not healthy.");
}
}
Error Handling
- Errors encountered during the API call or response processing are passed to
useErrorHandler. - Example scenarios where errors might occur:
- Network issues.
- Invalid or unexpected responses from the API.
Side Effects
- Updates
savelist_page_stateto visually indicate the status (loading,success, orfailed). - Modifies
savelist_api_healthyto reflect the API's operational status.
Notes
- This method should ideally be invoked before performing any operations that depend on the Save List API.
- Ensure that
useStateModifier,useAjaxEcom, anduseErrorHandlerare properly implemented for this method to function correctly.
createNewList
Method Definition
async createNewList(newListName: string, makeDefault: boolean) {
useStateModifier(this.user_savelists_modal_state, "loading");
const authStore = useAuthStore();
const customerId = ref("");
if (authStore.user) {
customerId.value = authStore.user.id;
}
if (authStore.is_authenticated) {
try {
const response = await useAjaxEcom(
`/customers/${customerId.value}/saved-lists`,
{
headers: {
"X-Toolstation-Customer-Id": customerId.value,
},
params: {
name: newListName,
},
method: "post",
}
);
if (!response.data) {
useStateModifier(this.savelist_page_state, "failed");
useStateModifier(this.user_savelists_modal_state, "failed");
throw `${useTranslation(
"couldNotCreate",
"Kan niet maken"
)} ${newListName}`;
}
// Check if the toggle is on to set as default
const saveListId = response.data.id;
if (makeDefault) {
const defaultResponse = await useAjaxEcom(
`/saved-lists/${saveListId}/default`,
{
method: "post",
}
);
if (defaultResponse && defaultResponse.error == false) {
throw new Error(
`${useTranslation(
"failedToMake",
"Kan de nieuwe bewaarlijst niet standaard instellen"
)}`
);
}
}
if (newListName === saveForLater) {
this.save_for_later_exists = true;
}
this.current_active_savelist.index = this.user_savelists.length;
await this.getUserSaveLists(true, this.current_active_savelist.index);
if (newListName !== myList && newListName !== saveForLater) {
toast(
`${useTranslation(
"newSaveList",
"Nieuwe lijst"
)} ${newListName} ${useTranslation("created", "gemaakt!")}`,
{
autoClose: true,
type: "success",
}
);
}
} catch (e) {
useErrorHandler(e);
useStateModifier(this.user_savelists_modal_state, "failed");
}
}
}
Description
The createNewList method is an asynchronous function that creates a new save list for a user. It sends a POST request to the Save List API with the new list name and, optionally, sets the list as the default if makeDefault is true. The method also updates various state variables and handles potential errors gracefully.
Purpose
This method enables authenticated users to create new save lists and optionally set them as their default save list.
Parameters
newListName(string): The name of the new save list to be created.makeDefault(boolean): A flag indicating whether the new save list should be set as the default.
Key Dependencies
useAjaxEcom: A utility function used to make AJAX requests to the Save List API.useStateModifier: A helper function that updates the state variables to reflect the current operation status (loading,failed, etc.).useAuthStore: A Pinia store providing user authentication details, including theuserobject andis_authenticatedflag.useErrorHandler: A utility function for handling errors during the API call.useTranslation: A utility for translating strings to the appropriate language.toast: A utility for displaying success notifications.
Workflow
- Sets
user_savelists_modal_stateto"loading"usinguseStateModifier. - Retrieves the authenticated user's
customerIdfrom theuseAuthStorestore. - Sends a
POSTrequest to the/customers/<customerId>/saved-listsendpoint with the new list name. - Handles the response:
- If no data is returned, updates the state to
"failed", displays an error message, and throws an error. - If
makeDefaultistrue, sends anotherPOSTrequest to set the created save list as the default.
- If no data is returned, updates the state to
- Updates the UI and state:
- Sets
save_for_later_existstotrueif the list name matches a predefined value (saveForLater). - Updates
current_active_savelist.indexto the new save list's index. - Calls
getUserSaveListsto refresh the user's save lists.
- Sets
- Displays a success notification unless the new list name matches predefined values (
myListorsaveForLater). - Catches and handles any errors using
useErrorHandler.
Return Value
This method does not return any value. Instead, it updates the following states:
user_savelists_modal_state: Reflects the current operation's status (e.g.,"loading","failed").savelist_page_state: Updates if the operation fails.current_active_savelist.index: Points to the newly created save list's index.save_for_later_exists: Indicates whether a "Save for Later" list already exists.
Example Usage
async function createListExample() {
await createNewList("My New List", true);
console.log("New save list created and set as default.");
}
Error Handling
- Errors encountered during the API call or response processing are passed to
useErrorHandler. - Example scenarios where errors might occur:
- Network issues.
- API failure to create the new list.
- Failure to set the save list as default.
Side Effects
- Sends a notification via
toastupon successful creation of a new save list. - Updates the UI to reflect the creation of a new save list.
- Calls
getUserSaveListsto refresh the list of save lists.
Notes
- This method is only accessible to authenticated users.
- Ensure that
useStateModifier,useAjaxEcom,useAuthStore, and other dependencies are correctly implemented. - Predefined values like
myListandsaveForLatershould be declared and imported where necessary.