๐ DIP(Dependency inversion principle)๋?
์์๋ชจ๋์ ํ์๋ชจ๋์ ์์กดํด์๋ ์๋๋ค.
์ฆ ๊ตฌํ์ฒด์ ์์กดํ์ง ๋ง๊ณ ์ธํฐํ์ด์ค์ ์์กดํด์ผํ๋ค ์ด๋ค
๐ง Web - Client ์ DIP
์น ํด๋ผ์ด์ธํธ์์ ์๋ก ๊ตฌํ์ฒด์ ์์กดํ์ง ์์์ผ ํ๋ค
index.html <-> main.js <-> auth-service.js <-> api-client.js <-> fetch
| ํ์ผ | ์ญํ |
| index.html | view |
| main.js | UI/์ฌ์ฉ์ ํ๋ฆ |
| auth-service.js | ๋น์ฆ๋์ค ๋ก์ง |
| api-client.js | HTTP ์ถ์ํ |
| fetch | ์ค์ ๊ตฌํ ๊ธฐ์ |
api-client.js
import { mapHttpError, mapUnknownError } from "./errors/error-mapper.js";
export async function post(url, data) {
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const error = mapHttpError(response);
if (error) {
throw error;
}
return await response.json();
} catch (e) {
throw mapUnknownError(e);
}
}
api-client์ http๋ฅผ ์ถ์ํ ํ๊ฒ์ด๋ค.
post๋ฅผ ํธ์ถ์์ fetch๋ฅผ ํธ์ถํ๊ณ , http error๊ฐ ๋ฐ์ํ๋ฉด ์ต์ข ์ ์ผ๋ก mapUnknownError์์ ์ฒ๋ฆฌํ๋ค.
auth-service.js
import { post } from "./app-client.js";
export const authService = {
async login(email, password) {
return await post("http://localhost:3000/login", {
email,
password,
});
},
};
์์์ http๋ฅผ ์ถ์ํ ํ์๋ค.
auth-service.js์์๋ post๋ฅผ ํธ์ถํ์ฌ, "/login"์ ํธ์ถํ๋ค.
auth-service.js์์๋ fetch๋ฅผ ์ง์ ์ฌ์ฉํ์ง ์๋ ๋ค๋๊ฒ์์ ์ถ์ํ๋์๋ค๊ณ ๋ณผ ์ ์๋ค.
main.js
import { authService } from "./auth-service.js";
const loginBtn = document.querySelector("button#loginBtn");
const email = document.querySelector("input#email");
const password = document.querySelector("input#password");
function validate() {
if (!email.value || !password.value) {
throw new Error("๊ฐ์ ์
๋ ฅํด์ฃผ์ธ์");
}
}
loginBtn.addEventListener("click", async () => {
try {
validate();
await authService.login(email.value, password.value);
alert("๋ก๊ทธ์ธ ์ฑ๊ณต");
} catch (error) {
alert(error.message);
}
});
main.js์์๋ ๋ก๊ทธ์ธ ๋ฒํผ ์ด๋ฒคํธ์ ๋ํ ๊ธฐ๋ฅ์ด๋ค.
main.js์์๋ fetch์ ์กด์ฌ๋ ๋ชจ๋ฅด๊ณ , http status code๋ ๋ชจ๋ฅธ๋ค.
๊ทธ๋ฌํ ๊ด์ ์์๋ ์ถ์ํ๊ฐ ์ด๋ฃจ์ด์ก๋ค๊ณ ๋ณผ ์ ์๋ค.
'Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| ๐ DIP (0) | 2026.05.11 |
|---|---|
| Queue์ผ๋ก ์์ ์คํ (0) | 2025.05.19 |
| ๐ฟ ์ํ ํจํด (0) | 2024.11.25 |
| โ๏ธ ์ ๋ต ํจํด (1) | 2024.11.19 |
| โ๏ธ ์ปค๋ง (0) | 2024.05.29 |
๋๊ธ