export function makeWebsocketParameters()

in src/pages/Home/Home.utils.ts [43:85]


export function makeWebsocketParameters(
  params: Record<string, string>,
  runGroups: Record<string, Run[]>,
  isLastPage: boolean,
): Record<string, string> {
  const { status, _page, _group, _limit, _group_limit, _order, ...rest } = params;
  let newparams = rest;

  const groupKeys = Object.keys(runGroups);
  // We need to remove status filter for websocket messages since we want to be able to track if
  // status changes from running to failed or completed even when we have status filter on
  if (params.status && params.status !== 'running') {
    newparams = { ...newparams, status };
  }

  // If we are grouping by user or flow, we want to subscribe only to visible groups. So we add parameter
  // user:lte or flow_id:lte with last group. (lower than or equal works since groups are in alphabetical order)
  if (params._group) {
    newparams = {
      ...newparams,
      ...(groupKeys.length > 0 && !isLastPage
        ? { [params._group === 'user' ? 'user:le' : 'flow_id:le']: groupKeys[groupKeys.length - 1] }
        : {}),
    };
  } else {
    const data = runGroups['undefined'];

    if (data?.length > 0 && _order && !isLastPage) {
      const lastItem = data[data.length - 1];
      const [dir, key] = parseOrderParam(_order);
      const firstOrderKey = key.split(',')[0];
      const value = lastItem[firstOrderKey as keyof Run];
      if (value) {
        newparams = {
          ...newparams,
          [`${firstOrderKey}:${dir === 'up' ? 'le' : 'ge'}`]: value as string,
        };
      }
    }
  }

  return newparams;
}