Savelists

Savelist Store Methods

verifySaveListHealth

Method Definition

savelist.store.ts
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 the savelist_page_state to reflect the current state of the operation (loading, success, or failed).
  • useErrorHandler: A utility function used to handle errors when the API call fails.

Workflow

  1. If savelist_api_healthy is already true, the method exits early.
  2. Sets savelist_page_state to "loading" using useStateModifier.
  3. Sends a GET request to /saved-lists/_ping using useAjaxEcom.
  4. Handles the response:
    • If response.data.msg is "OK", sets savelist_api_healthy to true and updates savelist_page_state to "success".
    • If response.success is false, sets savelist_api_healthy to false, updates savelist_page_state to "failed", and throws the first error in response.errors.
  5. 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, or failed).

Example Usage

example.ts
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_state to visually indicate the status (loading, success, or failed).
  • Modifies savelist_api_healthy to 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, and useErrorHandler are properly implemented for this method to function correctly.

createNewList

Method Definition

savelist.store.ts
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 the user object and is_authenticated flag.
  • 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

  1. Sets user_savelists_modal_state to "loading" using useStateModifier.
  2. Retrieves the authenticated user's customerId from the useAuthStore store.
  3. Sends a POST request to the /customers/<customerId>/saved-lists endpoint with the new list name.
  4. Handles the response:
    • If no data is returned, updates the state to "failed", displays an error message, and throws an error.
    • If makeDefault is true, sends another POST request to set the created save list as the default.
  5. Updates the UI and state:
    • Sets save_for_later_exists to true if the list name matches a predefined value (saveForLater).
    • Updates current_active_savelist.index to the new save list's index.
    • Calls getUserSaveLists to refresh the user's save lists.
  6. Displays a success notification unless the new list name matches predefined values (myList or saveForLater).
  7. 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

example.ts
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 toast upon successful creation of a new save list.
  • Updates the UI to reflect the creation of a new save list.
  • Calls getUserSaveLists to 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 myList and saveForLater should be declared and imported where necessary.

Copyright © 2026