2023-10-23 23:33:39 +02:00
|
|
|
import type { SetItems } from "../hooks/usePagination"
|
|
|
|
import type { CacheKey } from "./cache"
|
|
|
|
import { savePaginationCache } from "./cache"
|
2022-01-13 18:21:45 +01:00
|
|
|
|
|
|
|
export interface Item {
|
|
|
|
id: number
|
|
|
|
[key: string]: any
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface SocketData<T extends Item = Item> {
|
2023-10-23 23:33:39 +02:00
|
|
|
action: "create" | "update" | "delete"
|
2022-01-13 18:21:45 +01:00
|
|
|
item: T
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface HandleSocketDataOptions<T extends Item = Item> {
|
|
|
|
setItems: SetItems<T>
|
|
|
|
data: SocketData<T>
|
2022-08-24 17:22:55 +02:00
|
|
|
cacheKey?: CacheKey
|
2022-01-13 18:21:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export type SocketListener = (data: SocketData) => void
|
|
|
|
|
|
|
|
export const handleSocketData = <T extends Item = Item>(
|
2023-10-23 23:33:39 +02:00
|
|
|
options: HandleSocketDataOptions<T>,
|
2022-01-13 18:21:45 +01:00
|
|
|
): void => {
|
2022-08-24 17:22:55 +02:00
|
|
|
const { data, setItems, cacheKey } = options
|
2023-10-23 23:33:39 +02:00
|
|
|
console.log("socket.io data received: ", data)
|
2022-01-13 18:21:45 +01:00
|
|
|
|
|
|
|
setItems((oldItems) => {
|
|
|
|
const newItems = [...oldItems]
|
|
|
|
switch (data.action) {
|
2023-10-23 23:33:39 +02:00
|
|
|
case "create": {
|
2022-01-13 18:21:45 +01:00
|
|
|
newItems.push(data.item)
|
|
|
|
break
|
|
|
|
}
|
2023-10-23 23:33:39 +02:00
|
|
|
case "delete": {
|
2022-08-31 21:44:33 +02:00
|
|
|
const itemIndex = newItems.findIndex((item) => {
|
|
|
|
return item.id === data.item.id
|
|
|
|
})
|
2022-01-13 18:21:45 +01:00
|
|
|
if (itemIndex !== -1) {
|
|
|
|
newItems.splice(itemIndex, 1)
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
2023-10-23 23:33:39 +02:00
|
|
|
case "update": {
|
2022-08-31 21:44:33 +02:00
|
|
|
const itemIndex = newItems.findIndex((item) => {
|
|
|
|
return item.id === data.item.id
|
|
|
|
})
|
2022-01-13 18:21:45 +01:00
|
|
|
if (itemIndex !== -1) {
|
2022-03-05 18:22:30 +01:00
|
|
|
newItems[itemIndex] = {
|
|
|
|
...newItems[itemIndex],
|
2023-10-23 23:33:39 +02:00
|
|
|
...data.item,
|
2022-03-05 18:22:30 +01:00
|
|
|
}
|
2022-01-13 18:21:45 +01:00
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2022-08-24 17:22:55 +02:00
|
|
|
if (cacheKey != null) {
|
|
|
|
savePaginationCache(cacheKey, newItems)
|
|
|
|
}
|
2022-01-13 18:21:45 +01:00
|
|
|
return newItems
|
|
|
|
})
|
|
|
|
}
|