munch2024 / munch

2 stars 11 forks source link

Complex Code Issue #65

Closed mitshelle closed 8 months ago

mitshelle commented 8 months ago

The code snippet loads data asynchronously based on certain requirements and returns a Promise. It does not include any explanations and its purpose is not clear at first glance. It is just a bunch of code in one function

The code includes a complexity which is asynchronously getting data and making sure there are no errors. There are a lot of things the one function does, which gives it poor readability and possibly poor efficiency.

Goals for Refactoring:

  1. Improve readability and efficiency by breaking the function into smaller components.
  2. Allow for more uses of the smaller components

Below is the code snippet .

export async function loadDataSource(props: IDataSourceProps): Promise<IRow[]> {
    const { dataSourceId } = props;

    return new Promise((resolve, reject) => {
        const data = new Array<IRow>();
        const TIMEOUT_DURATION = 100_000;
        let timer = setTimeout(timeout, TIMEOUT_DURATION);

        const timeout = () => {
            reject("timeout");
        };

        const onmessage = (ev: MessageEvent<MessagePayload>) => {
            if (Object.is(ev.data.dataSourceId, dataSourceId)) {
                clearTimeout(timer);
                timer = setTimeout(timeout, TIMEOUT_DURATION);

                if (ev.data.action === "postData") {
                    handlePostData(ev.data);
                } else if (ev.data.action === "finishData") {
                    handleFinishData();
                }
            }
        };

        window.addEventListener("message", onmessage);
    });
}

const handlePostData = (eventData: MessagePayload) => {
    commonStore.setInitModalOpen(true);
    commonStore.setInitModalInfo({
        total: eventData.total,
        curIndex: eventData.curIndex,
        title: "Loading Data",
    });
    for (const row of eventData.data ?? []) {
        data.push(row);
    }
};

const handleFinishData = () => {
    window.removeEventListener("message", onmessage);
    resolve(data);
};