All files / layers / L1 entityHooks.ts

58.26% Statements 134/230
46.58% Branches 75/161
53.33% Functions 32/60
64.39% Lines 123/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609            187x 187x 4x 4x     4x 4x   187x           1140x 202x 202x 202x         866x 96x 96x                                                           3x 2x 2x   4x   1x       1140x 1140x 1140x       1140x     186x 186x 118x       1140x 1140x 1140x       1140x 202x 202x 202x 202x   202x 98x 98x       1140x                       866x     18x 15x   11x   15x       866x 866x                 646x 646x 646x 646x   1x                       1x 1x 1x 1x 1x 1x       1x     1x 1x       1x     646x 646x                                                     646x 646x   1x                             1x 1x 1x     1x 11x     1x     646x   1x                 1x               224x 224x 224x 224x 224x 224x 224x 224x 160x 160x 160x 160x 160x   160x 160x 160x 160x 160x 661x   160x 160x         160x 31x 31x 31x 31x 31x       31x 31x 31x   160x               160x         160x           160x                             160x 160x 160x 160x 143x 143x 143x 143x 143x                         224x               148x     1140x     866x     646x     224x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useEffect, useRef } from 'react'
import { apiClient } from '@/lib/axios'
import type {
  ApiContract,
  EntityHooks,
  ListResult,
  DetailResult,
  MutationHandle,
  ISubscriptionHandle,
  QueryParams,
  ListQueryOptions,
} from '../interfaces'
import {
  addPendingDelete,
  getPendingDeletes,
  normalizeFilters,
  removePendingDelete,
} from './mutationQueue'
import { addToOutbox } from '@/lib/mutationOutbox'
 
export function resolveEndpointTemplate(
 I template: string,
 E params: QueryParams,
): { url: string; remainingParams: QueryParams } {
  const remainingParams: QueryParams = { ...params }
  const url = template.replace(/\{(\w+)\}/g, (_match, token) => {
    const value = params[token]
    if (value === undefined) {
      throw new Error(
 E       `Missing required template parameter "${token}" ` +
        `for endpoint "${template}". ` +
        `Available params: ${Object.keys(params).join(', ') || '(none)'}`
      )
    }
    delete remainingParams[token]
    return String(value)
  })
  return { url, remainingParams }
}

function extractArray<T extends { id: string }>(cached: unknown): T[] {
  if (!cached) return []
  if (Array.isArray(cached)) return cached as T[]
  if (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    Array.isArray((cached as { data: unknown[] }).data)
  ) {
    return (cached as { data: T[] }).data
  }
  return []
}
 
function extractSingle<T extends { id: string }>(cached: unknown): T | null {
  if (!cached) return null
  if (
    typeof cached === 'object' &&
    cached !== null &&
    'id' in cached
  ) {
 I   return cached as T
  }
  if (
    cached &&
    typeof cached === 'object' &&
 E   'data' in cached &&
    typeof (cached as { data: unknown }).data === 'object' &&
    (cached as { data: unknown }).data !== null
  ) {
    return (cached as { data: T }).data
  }
  return null
}
 
function patchEntityInResponse<T extends { id: string }>(
  cached: unknown,
  updated: T,
): unknown {
  if (!cached) return cached
  if (Array.isArray(cached))
    return cached.map((x) => (x.id === updated.id ? updated : x))
  if (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    Array.isArray((cached as { data: unknown[] }).data)
  )
    return {
      ...(cached as object),
      data: (cached as { data: T[] }).data.map((x) =>
        x.id === updated.id ? updated : x,
      ),
  E  }
  iEf (
    cached &&
    typeof cached === 'object' &&
    'id' in cached &&
    (cached as T).id === updated.id
  )
    return updated
  return cached
}
 
function insertEntityInResponse<T extends { id: string }>(
  cached: unknown,
  entity: T,
): unknown {
  if (!cached) return cached
  if (Array.isArray(cached))
    return cached.some((x: T) => x.id === entity.id)
      ? cached
      : [entity, ...cached]
  if (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    Array.isArray((cached as { data: unknown[] }).data)
  ) {
    const arr = (cached as { data: T[] }).data
    return arr.some((x) => x.id === entity.id)
      ? cached
      : { ...(cached as object), data: [entity, ...arr] }
  }
  return cached
}
 
function removeEntityFromResponse<T extends { id: string }>(
  cached: unknown,
  id: string,
): unknown {
  if (!cached) return cached
  if (Array.isArray(cached)) return (cached as T[]).filter((x) => x.id !== id)
  if (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    Array.isArray((cached as { data: unknown[] }).data)
  )
    return {
      ...(cached as object),
      data: (cached as { data: T[] }).data.filter((x) => x.id !== id),
   I }
  if (
    cached &&
    typeof cached === 'object' &&
    'id' in cached &&
    (cached as { id: string }).id === id
  )
    return null
  return cached
}

function useEntityListImpl<
  TEEntity extends { id: string },
  TCreateBody,
  TUpdateBody,
  TListQuery extends QueryParams,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>,
  params: TListQuery,
  options?: ListQueryOptions,
): ListResult<TEntity> {
  const normalized = normalizeFilters(params)
  const entityPath = contract.entityPath
 
  cEonst effectiveParams =
    Object.keys(normalized).length === 0 && contract.defaultListQuery
      ? { ...normalizeFilters(contract.defaultListQuery), ...normalized }
      : normalized
 
  const query = useQuery({
    queryKey: [entityPath, effectiveParams],
    queryFn: async () => {
      const { url, remainingParams } = resolveEndpointTemplate(
        contract.endpoints.list,
        effectiveParams,
      )
      const { data } = await apiClient.get(url, {
        params: remainingParams,
      })
      return data
    },
    staleTime: options?.queryMode === 'live' ? 0 : undefined,
  })
 
  const pendingIds = getPendingDeletes(entityPath)
  const rawData = extractArray<TEntity>(query.data)
  const filteredData =
    pendingIds.size > 0
      ? rawData.filter((item) => !pendingIds.has(contract.idOf(item)))
      : rawData

  let total: number | undefined
  let hasMore: boolean | undefined
  let totalEstimate: number | undefined

  if (
    query.data &&
    typeof query.data === 'object' &&
    'meta' in query.data
  ) {
    const meta = (query.data as { meta?: Record<string, unknown> }).meta
    if (meta) {
      if (typeof meta.has_more === 'boolean') {
   I     hasMore = meta.has_more
      }
      if (typeof meta.total_estimate === 'number') {
        totalEstimate = meta.total_estimate
        total = totalEstimate -
          (pendingIds.size > 0
            ? rawData.length - filteredData.length
            : 0)
      }
    }
  }
 
  return {
    data: filteredData,
    total,
   E hasMore,
    totalEstimate,
    isLoading: query.isLoading,
    isFetching: query.isFetching,
    error: query.error,
    refetch: () => query.refetch(),
  }
}
 
function useEntityDetailImpl<
  TEntity extends { id: string },
  TCreateBody,
  TUpdateBody,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody>,
  id: string,
): DetailResult<TEntity> {
  const query = useQuery({
    queryKey: [contract.entityPath, id],
    queryFn: async () => {
      const { data } = await apiClient.get(contract.endpoints.detail(id))
      if (data && typeof data === 'object' && !('id' in data)) {
        ;(data as Record<string, unknown>).id = contract.idOf(data as TEntity)
      }
      return data
    },
    enabled: !!id,
  })
 
  const data = extractSingle<TEntity>(query.data)
 
  return {
    data,
    isLoading: query.isLoading,
    isFetching: query.isFetching,
    error: query.error,
    refetch: () => query.refetch(),
  }
}
 
function useMutationImpl<
  TEntity extends { id: string },
  TCreateBody,
  TUpdateBody,
  TListQuery extends QueryParams,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>,
): IMutationHandle<TEntity, TCreateBody, TUpdateBody> {
  const qc = useQueryClient()
  const entityPath = contract.entityPath
E
  let createPendingKey: string | null = null
 
  const createMutation = useMutation({
    mutationFn: async ({ input, context }: { input: TCreateBody; context?: QueryParams }) => {
      if (!navigator.onLine) {
        if (!createPendingKey) createPendingKey = crypto.randomUUID()
        await addToOutbox({
          id: crypto.randomUUID(),
          entityPath,
          op: 'CREATE',
    I      payload: input,
          idempotencyKey: createPendingKey,
    I      createdAt: Date.now(),
        })
        return null
      }
      if (!createPendingKey) createPendingKey = crypto.randomUUID()
      const key = createPendingKey
      const body = contract.request?.create
        ? contract.request.create(input)
        : input
      const pathParams = contract.createPathParams
        ? contract.createPathParams(body, context)
        : (context ?? {})
      const { url, remainingParams } = resolveEndpointTemplate(
        contract.endpoints.create,
        pathParams,
      )
      const { data } = await apiClient.post(url, body, {
        headers: { 'Idempotency-Key': key },
        params: Object.keys(remainingParams).length > 0 ? remainingParams : undefined,
      })
      return data
    },
    onSuccess: (data) => {
      if (data) {
        qc.invalidateQueries({ queryKey: [entityPath] })
      }
    },
    onSettled: () => {
      createPendingKey = null
    },
  })

  let updatePendingKey: string | null = null

  const updateMutation = useMutation({
    mutationFn: async (variables: { id: string; input: TUpdateBody }) => {
      if (!navigator.onLine) {
        if (!updatePendingKey) updatePendingKey = crypto.randomUUID()
        await addToOutbox({
          id: crypto.randomUUID(),
          entityPath,
          op: 'UPDATE',
          payload: { id: variables.id, ...variables.input },
          idempotencyKey: updatePendingKey,
          createdAt: Date.now(),
        })
        return null
      }
      if (!updatePendingKey) updatePendingKey = crypto.randomUUID()
      const key = updatePendingKey
      const body = contract.request?.update
        ? contract.request.update(variables.input)
        : variables.input
      const { data } = await apiClient.put(
        contract.endpoints.update(variables.id),
        body,
        {
          headers: { 'Idempotency-Key': key },
        },
      )
      return data
    },
    onSettled: () => {
      updatePendingKey = null
    },
  })

  let removePendingKey: string | null = null
 
  const removeMutation = useMutation({
    mutationFn: async (id: string) => {
      if (!navigator.onLine) {
        if (!removePendingKey) removePendingKey = crypto.randomUUID()
        const key = removePendingKey
        addPendingDelete(entityPath, id)
        qc.getQueryCache()
          .getAll()
          .filter((q) => q.queryKey[0] === entityPath)
          .forEach((q) =>
            qc.setQueryData(
              q.queryKey,
              removeEntityFromResponse(q.state.data, id),
            ),
          )
        await addToOutbox({
          id: crypto.randomUUID(),
          entityPath,
          op: 'DELETE',
          payload: { id },
          idempotencyKey: key,
          createdAt: Date.now(),
        })
        return
      }
      if (!removePendingKey) removePendingKey = crypto.randomUUID()
      const key = removePendingKey
      await apiClient.delete(contract.endpoints.remove(id), {
        headers: { 'Idempotency-Key': key },
      })
    },
    onSuccess: (_data, id) => {
      addPendingDelete(entityPath, id)
      qc.getQueryCache()
        .getAll()
        .filter((q) => q.queryKey[0] === entityPath)
        .forEach((q) =>
          qc.setQueryData(
            q.queryKey,
            removeEntityFromResponse(q.state.data, id),
          ),
        )
    },
    onSettled: () => {
      removePendingKey = null
    },
  })
 
  return {
    create: (input, context?) => {
      createMutation.mutate({ input, context })
    },
    update: (id, input) => updateMutation.mutate({ id, input }),
    remove: (id) => removeMutation.mutate(id),
    isPending:
      createMutation.isPending ||
      updateMutation.isPending ||
      removeMutation.isPending,
    isError:
      createMutation.isError ||
      updateMutation.isError ||
      removeMutation.isError,
    error:
      createMutation.error ||
      updateMutation.error ||
      removeMutation.error,
    lastMutationData: (createMutation.data ?? updateMutation.data ?? null) as TEntity | null,
  }
}
 
function useSubscriptionImpl<
  TEntity extends { id: string },
  TCreateBody,
  TUpdateBody,
  TListQuery extends QueryParams,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>,
  params: TListQuery,
): SubscriptionHandle {
  const queryClient = useQueryClient()
  const normalized = normalizeFilters(params)
  const normalizedKey = JSON.stringify(normalized)
  const { entityPath } = contract
  const { ssePath, entityName } = contract.subscription
 
  const [isConnectionLost, setIsConnectionLost] = useState(false)
  const openRef = useRef<() => void>(() => {})
 
  useEffect(() => {
    let source: EventSource | null = null
    let backoffMs = 1_000
    let failureCount = 0
    const MAX_FAILURES = 5
    const pendingTimeouts = new Set<ReturnType<typeof setTimeout>>()
 
    function open() {
      source?.close()
      source = null
      if (!navigator.onLine) return
 
      const qs = new URLSearchParams()
      for (const [k, v] of Object.entries(normalized)) {
        if (v !== undefined) qs.set(k, String(v))
      }
      source = new EventSource(`${ssePath}?${qs}`, {
        withCredentials: true,
      })
 
      source.onopen = () => {
        setIsConnectionLost(false)
        backoffMs = 1_000
        failureCount = 0
      }
 
      source.onerror = () => {
        source?.close()
        source = null
        if (!navigator.onLine) return
        failureCount++
        if (failureCount >= MAX_FAILURES) {
          setIsConnectionLost(true)
          return
        }
        const id = setTimeout(open, backoffMs)
        pendingTimeouts.add(id)
        backoffMs = Math.min(backoffMs * 2, 30_000)
      }
 
      source.addEventListener(`${entityName}.created`, (e) => {
        const entity = JSON.parse((e as MessageEvent).data) as TEntity
        const sortKey = normalized.sort as string | undefined
        const sortOrder = normalized.order as string | undefined
        const isNewestFirst =
          (!sortKey || sortKey === 'created_at') && sortOrder !== 'asc'
        if (!isNewestFirst) return
 
        queryClient
          .getQueryCache()
          .getAll()
          .filter((q) => q.queryKey[0] === entityPath)
          .forEach((q) =>
            queryClient.setQueryData(
              q.queryKey,
              insertEntityInResponse(q.state.data, entity),
            ),
          )
      })
 
      source.addEventListener(`${entityName}.updated`, (e) => {
        const updated = JSON.parse((e as MessageEvent).data) as TEntity
        if (getPendingDeletes(entityPath).has(contract.idOf(updated))) return
        queryClient
          .getQueryCache()
          .getAll()
          .filter((q) => q.queryKey[0] === entityPath)
          .forEach((q) =>
            queryClient.setQueryData(
              q.queryKey,
              patchEntityInResponse(q.state.data, updated),
            ),
          )
      })
 
      source.addEventListener(`${entityName}.deleted`, (e) => {
        const { id } = JSON.parse((e as MessageEvent).data) as { id: string }
        removePendingDelete(entityPath, id)
        queryClient
          .getQueryCache()
          .getAll()
          .filter((q) => q.queryKey[0] === entityPath)
          .forEach((q) =>
            queryClient.setQueryData(
              q.queryKey,
              removeEntityFromResponse(q.state.data, id),
            ),
          )
      })
    }
 
    openRef.current = open
 
    function handleOffline() {
      source?.close()
      source = null
      pendingTimeouts.forEach(clearTimeout)
      pendingTimeouts.clear()
      backoffMs = 1_000
      failureCount = 0
    }
 
    function handleOnline() {
      backoffMs = 1_000
      failureCount = 0
      setIsConnectionLost(false)
      open()
    }
 
    window.addEventListener('offline', handleOffline)
    window.addEventListener('online', handleOnline)
    open()
 
    return () => {
      source?.close()
      pendingTimeouts.forEach(clearTimeout)
      pendingTimeouts.clear()
      window.removeEventListener('offline', handleOffline)
      window.removeEventListener('online', handleOnline)
    }
  }, [
    queryClient,
    entityPath,
    ssePath,
    entityName,
    contract,
    normalizedKey,
    normalized,
    normalized.sort,
    normalized.order,
  ])
 
  return {
    isConnectionLost,
    reconnect: () => {
      openRef.current()
    },
  }
}
 
export function createEntityHooks<
  TEntity extends { id: string },
  TCreateBody = Partial<TEntity>,
  TUpdateBody = Partial<TEntity>,
  TListQuery extends QueryParams = QueryParams,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>,
): EntityHooks<TEntity, TCreateBody, TUpdateBody, TListQuery> {
  return {
    apiContract: contract,
 
    useEntityList(params, options?) {
      return useEntityListImpl(contract, params, options)
    },
 
    useEntityDetail(id) {
      return useEntityDetailImpl(contract, id)
    },
 
    useMutation() {
      return useMutationImpl(contract)
    },
 
    useSubscription(params) {
      return useSubscriptionImpl(contract, params)
    },
  }
}