Skip to content

Commit

Permalink
feat: adopt swr
Browse files Browse the repository at this point in the history
  • Loading branch information
solufa committed Jul 19, 2024
1 parent 91991b9 commit 46480bc
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 17 deletions.
28 changes: 16 additions & 12 deletions client/features/tasks/TaskList.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import useAspidaSWR from '@aspida/swr';
import type { TaskDto } from 'common/types/task';
import { labelValidator } from 'common/validators/task';
import { Loading } from 'components/loading/Loading';
Expand All @@ -11,9 +12,9 @@ import styles from './taskList.module.css';

export const TaskList = () => {
const { setAlert } = useAlert();
const { lastMsg } = usePickedLastMsg(['taskCreated', 'taskUpdated']);
const { data: tasks, mutate: mutateTasks } = useAspidaSWR(apiClient.private.tasks);
const { lastMsg } = usePickedLastMsg(['taskCreated', 'taskUpdated', 'taskDeleted']);
const fileRef = useRef<HTMLInputElement | null>(null);
const [tasks, setTasks] = useState<TaskDto[]>();
const [label, setLabel] = useState('');
const [image, setImage] = useState<File>();
const [previewImageUrl, setPreviewImageUrl] = useState<string>();
Expand All @@ -30,7 +31,7 @@ export const TaskList = () => {

await apiClient.private.tasks
.$post({ body: { label: parsedLabel.data, image } })
.then((task) => setTasks((tasks) => [task, ...(tasks ?? [])]))
.then((task) => mutateTasks((tasks) => [task, ...(tasks ?? [])]))
.catch(catchApiErr);
setLabel('');
setImage(undefined);
Expand All @@ -42,30 +43,33 @@ export const TaskList = () => {
await apiClient.private.tasks
._taskId(task.id)
.$patch({ body: { done: !task.done } })
.then((task) => setTasks((tasks) => tasks?.map((t) => (t.id === task.id ? task : t))))
.then((task) => mutateTasks((tasks) => tasks?.map((t) => (t.id === task.id ? task : t))))
.catch(catchApiErr);
};
const deleteTask = async (task: TaskDto) => {
await apiClient.private.tasks
._taskId(task.id)
.$delete()
.then((task) => setTasks((tasks) => tasks?.filter((t) => t.id !== task.id)))
.then((task) => mutateTasks((tasks) => tasks?.filter((t) => t.id !== task.id)))
.catch(catchApiErr);
};

useEffect(() => {
if (tasks !== undefined) return;

apiClient.private.tasks.$get().then(setTasks).catch(catchApiErr);
}, [tasks]);

useEffect(() => {
if (lastMsg === undefined) return;

switch (lastMsg.type) {
case 'taskCreated':
mutateTasks((tasks) => [lastMsg.task, ...(tasks ?? [])], { revalidate: false });
return;
case 'taskUpdated':
console.log(lastMsg);
mutateTasks((tasks) => tasks?.map((t) => (t.id === lastMsg.task.id ? lastMsg.task : t)), {
revalidate: false,
});
return;
case 'taskDeleted':
mutateTasks((tasks) => tasks?.filter((t) => t.id !== lastMsg.taskId), {
revalidate: false,
});
return;
/* v8 ignore next 2 */
default:
Expand Down
23 changes: 23 additions & 0 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
},
"dependencies": {
"@aspida/axios": "^1.14.0",
"@aspida/swr": "^1.14.0",
"@aws-amplify/ui-react": "^6.1.13",
"aspida": "^1.14.0",
"aws-amplify": "^6.4.0",
Expand All @@ -29,6 +30,7 @@
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-use-websocket": "^4.8.1",
"swr": "^2.2.5",
"zod": "^3.23.8"
},
"devDependencies": {
Expand Down
10 changes: 5 additions & 5 deletions server/service/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { WebSocket } from 'ws';

let fastify: FastifyInstance;

const users: Record<DtoId['user'], WebSocket | undefined> = {};
const users: Record<DtoId['user'], WebSocket[] | undefined> = {};

const sendJson = (socket: WebSocket, data: WebSocketData): void => {
if (socket.readyState !== WebSocket.OPEN) return;
Expand All @@ -19,7 +19,7 @@ export const websocket = {
fastify = app;
},
add: (userId: DtoId['user'], socket: WebSocket): void => {
users[userId] = socket;
users[userId] = [socket, ...(users[userId] ?? [])];

socket.on('message', (msg) => {
if (socket.readyState !== WebSocket.OPEN) return;
Expand All @@ -28,16 +28,16 @@ export const websocket = {
});

socket.on('close', () => {
users[userId] = undefined;
users[userId] = users[userId]?.filter((s) => s !== socket);
});
},
send: (userId: DtoId['user'], data: WebSocketData): void => {
users[userId] && sendJson(users[userId], data);
users[userId]?.forEach((socket) => sendJson(socket, data));
},
broadcastToAuthedClients: (data: WebSocketData): void => {
Object.values(users)
.filter((user) => user !== undefined)
.forEach((socket) => sendJson(socket, data));
.forEach((sockets) => sockets.forEach((socket) => sendJson(socket, data)));
},
broadcast: (data: WebSocketData): void => {
fastify.websocketServer.clients.forEach((socket) => sendJson(socket, data));
Expand Down

0 comments on commit 46480bc

Please sign in to comment.