Skip to content

Step 5: infrastructure services & dependency injection #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: step-4-domain-layer
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
553 changes: 552 additions & 1 deletion package-lock.json

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"dev:client": "vite",
"dev:server": "tsx watch --ignore server/public server",
"build": "tsc && vite build",
"test": "echo 'No tests specified'",
"test": "vitest src",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"prettier": "prettier ./src --check",
"types": "tsc --noEmit",
Expand Down Expand Up @@ -58,6 +58,8 @@
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"fetch-blob": "^4.0.0",
"formdata-node": "^6.0.3",
"husky": "^9.0.11",
"lint-staged": "^15.2.2",
"npm-run-all": "^4.1.5",
Expand All @@ -66,6 +68,7 @@
"tailwindcss": "^3.4.3",
"tsx": "^4.7.2",
"typescript": "^5.4.5",
"vite": "^5.2.8"
"vite": "^5.2.8",
"vitest": "^1.6.0"
}
}
1 change: 0 additions & 1 deletion src/api/feed/index.ts

This file was deleted.

15 changes: 0 additions & 15 deletions src/api/media/api.ts

This file was deleted.

1 change: 0 additions & 1 deletion src/api/media/index.ts

This file was deleted.

1 change: 0 additions & 1 deletion src/api/shout/index.ts

This file was deleted.

1 change: 0 additions & 1 deletion src/api/user/index.ts

This file was deleted.

8 changes: 4 additions & 4 deletions src/components/header/header.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

import AuthApi from "@/api/auth";
import UserApi from "@/api/user";
import { LoginDialog } from "@/components/login-dialog";
import { Button } from "@/components/ui/button";
import { Me } from "@/domain";
import AuthService from "@/infrastructure/auth";
import UserService from "@/infrastructure/user";

export function Header() {
const [isLoadingMe, setIsLoadingMe] = useState(true);
Expand All @@ -14,15 +14,15 @@ export function Header() {
const [hasError, setHasError] = useState(false);

useEffect(() => {
UserApi.getMe()
UserService.getMe()
.then((me) => setMe(me))
.catch(() => setHasError(true))
.finally(() => setIsLoadingMe(false));
}, []);

async function logout() {
setIsLoadingLogout(true);
await AuthApi.logout();
await AuthService.logout();
setIsLoadingLogout(false);
window.location.reload();
}
Expand Down
4 changes: 2 additions & 2 deletions src/components/login-dialog/login-dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useState } from "react";

import AuthApi from "@/api/auth";
import { Button } from "@/components/ui/button";
import {
Dialog,
Expand All @@ -13,6 +12,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import AuthService from "@/infrastructure/auth";

interface LoginFormElements extends HTMLFormControlsCollection {
username: HTMLInputElement;
Expand All @@ -37,7 +37,7 @@ export function LoginDialog({ children }: LoginDialogProps) {
const username = event.currentTarget.elements.username.value;
const password = event.currentTarget.elements.password.value;

await AuthApi.login({ username, password });
await AuthService.login({ username, password });

setIsLoading(false);
setOpen(false);
Expand Down
14 changes: 7 additions & 7 deletions src/components/shout/reply-dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { useEffect, useState } from "react";

import MediaApi from "@/api/media";
import ShoutApi from "@/api/shout";
import UserApi from "@/api/user";
import { LoginDialog } from "@/components/login-dialog";
import { Button } from "@/components/ui/button";
import {
Expand All @@ -17,6 +14,9 @@ import {
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import MediaService from "@/infrastructure/media";
import ShoutService from "@/infrastructure/shout";
import UserService from "@/infrastructure/user";

interface ReplyFormElements extends HTMLFormControlsCollection {
message: HTMLTextAreaElement;
Expand All @@ -39,7 +39,7 @@ export function ReplyDialog({ children, shoutId }: ReplyDialogProps) {
const [hasError, setHasError] = useState(false);

useEffect(() => {
UserApi.getMe()
UserService.getMe()
.then((me) => setIsAuthenticated(Boolean(me)))
.catch(() => setHasError(true))
.finally(() => setIsLoading(false));
Expand All @@ -58,15 +58,15 @@ export function ReplyDialog({ children, shoutId }: ReplyDialogProps) {

let image;
if (files?.length) {
image = await MediaApi.uploadImage(files[0]);
image = await MediaService.saveImage(files[0]);
}

const newShout = await ShoutApi.createShout({
const newShout = await ShoutService.createShout({
message,
imageId: image?.id,
});

await ShoutApi.createReply({
await ShoutService.createReply({
shoutId,
replyId: newShout.id,
});
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
10 changes: 10 additions & 0 deletions src/infrastructure/feed/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { apiClient } from "../client";

import { FeedResponse } from "./dto";

async function getFeed() {
const response = await apiClient.get<FeedResponse>("/feed");
return response.data;
}

export default { getFeed };
File renamed without changes.
1 change: 1 addition & 0 deletions src/infrastructure/feed/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "./service";
165 changes: 165 additions & 0 deletions src/infrastructure/feed/service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import { describe, it, expect, vitest } from "vitest";

import FeedService from "./service";

const feedApiMock = {
getFeed: vitest.fn().mockResolvedValue({
data: [
{
id: "shout-1",
type: "shout",
createdAt: 1717045146970,
attributes: {
authorId: "user-1",
text: "The world sucks!!!!",
likes: 5,
reshouts: 0,
},
relationships: {
replies: ["shout-2"],
},
},
{
id: "shout-2",
type: "shout",
createdAt: 1717038768844,
attributes: {
authorId: "user-3",
text: "The world sucks!!!!",
likes: 1000,
reshouts: 666,
},
relationships: {
replies: [],
},
},
],
included: [
{
id: "user-1",
type: "user",
attributes: {
handle: "darklord",
avatar: "/cdn/avatars/darklord.jpeg",
info: "I am the dark lord, the root of all evil. 'Tis I who brought the world to its knees. In blood I was born, and in blood I shall have my vengeance.",
blockedUserIds: ["user-2"],
followsUserIds: ["user-3"],
},
relationships: {
followerIds: ["user-3"],
me: {
attributes: {
isBlocked: true,
isFollowing: false,
},
},
},
},
{
id: "user-2",
type: "user",
attributes: {
handle: "prettypinkpony",
avatar: "/cdn/avatars/prettypinkpony.jpeg",
info: "I like colors. I'm a colorful person (although I'm pretty white *giggles*). I'd like to make this world a better place. And sometimes I feel like the only one who can...",
blockedUserIds: ["user-1"],
followsUserIds: ["user-3"],
},
relationships: {
followerIds: ["user-3"],
me: {
attributes: {
isBlocked: false,
isFollowing: false,
},
},
},
},
{
id: "user-3",
type: "user",
attributes: {
handle: "fcku",
avatar: "/cdn/avatars/fcku.jpeg",
blockedUserIds: [],
followsUserIds: ["user-1", "user-2"],
},
relationships: {
followerIds: ["user-1", "user-2"],
me: {
attributes: {
isBlocked: false,
isFollowing: true,
},
},
},
},
{
id: "image-1",
type: "image",
attributes: {
url: "https://media.giphy.com/media/dG7ZiL6ImLyNO/giphy.gif",
},
},
],
}),
};

describe("FeedService", () => {
it("should return shouts, users, and images from the feed", async () => {
const result = await FeedService.getFeed(feedApiMock);

expect(feedApiMock.getFeed).toHaveBeenCalled();
expect(result.shouts).toEqual([
{
authorId: "user-1",
createdAt: 1717045146970,
id: "shout-1",
imageId: undefined,
likes: 5,
replies: ["shout-2"],
reshouts: 0,
text: "The world sucks!!!!",
},
{
authorId: "user-3",
createdAt: 1717038768844,
id: "shout-2",
imageId: undefined,
likes: 1000,
replies: [],
reshouts: 666,
text: "The world sucks!!!!",
},
]);
expect(result.users).toEqual([
{
avatar: "/cdn/avatars/darklord.jpeg",
followerIds: ["user-3"],
handle: "darklord",
id: "user-1",
info: "I am the dark lord, the root of all evil. 'Tis I who brought the world to its knees. In blood I was born, and in blood I shall have my vengeance.",
},
{
avatar: "/cdn/avatars/prettypinkpony.jpeg",
followerIds: ["user-3"],
handle: "prettypinkpony",
id: "user-2",
info: "I like colors. I'm a colorful person (although I'm pretty white *giggles*). I'd like to make this world a better place. And sometimes I feel like the only one who can...",
},
{
avatar: "/cdn/avatars/fcku.jpeg",
followerIds: ["user-1", "user-2"],
handle: "fcku",
id: "user-3",
info: undefined,
},
]);
expect(result.images).toEqual([
{
id: "image-1",
url: "https://media.giphy.com/media/dG7ZiL6ImLyNO/giphy.gif",
},
]);
});
});
13 changes: 6 additions & 7 deletions src/api/feed/api.ts → src/infrastructure/feed/service.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { apiClient } from "../client";
import { ImageDto } from "../media/dto";
import { dtoToImage } from "../media/transform";
import { dtoToShout } from "../shout/transform";
import { UserDto } from "../user/dto";
import { dtoToUser } from "../user/transform";

import { FeedResponse } from "./dto";
import FeedApi from "./api";

async function getFeed() {
const response = await apiClient.get<FeedResponse>("/feed");
const shouts = response.data.data.map(dtoToShout);
const users = response.data.included
async function getFeed(api = FeedApi) {
const response = await api.getFeed();
const shouts = response.data.map(dtoToShout);
const users = response.included
.filter((u): u is UserDto => u.type === "user")
.map(dtoToUser);
const images = response.data.included
const images = response.included
.filter((i): i is ImageDto => i.type === "image")
.map(dtoToImage);
return { shouts, users, images };
Expand Down
10 changes: 10 additions & 0 deletions src/infrastructure/media/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { apiClient } from "../client";

import { ImageDto } from "./dto";

async function uploadImage(formData: FormData) {
const response = await apiClient.post<{ data: ImageDto }>("/image", formData);
return response.data;
}

export default { uploadImage };
File renamed without changes.
1 change: 1 addition & 0 deletions src/infrastructure/media/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "./service";
Loading