Skip to content
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

Hw 1 #8

Open
wants to merge 6 commits into
base: main
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
22 changes: 22 additions & 0 deletions client/package-lock.json

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

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@types/react": "^18.0.6",
"@types/react-dom": "^18.0.2",
"axios": "^0.26.1",
"cors": "^2.8.5",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-router-dom": "^6.3.0",
Expand Down
12 changes: 7 additions & 5 deletions client/src/pages/account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,24 @@ import {SAPIBase} from "../tools/api";
import "./css/account.css";

const AccountPage = () => {
const [ SAPIKEY, setSAPIKEY ] = React.useState<string>("");
const [ ID, setID ] = React.useState<string>("");
const [ PW, setPW ] = React.useState<string>("");
const [ NBalance, setNBalance ] = React.useState<number | "Not Authorized">("Not Authorized");
const [ NTransaction, setNTransaction ] = React.useState<number>(0);

const getAccountInformation = () => {
const asyncFun = async() => {
interface IAPIResponse { balance: number };
const { data } = await axios.post<IAPIResponse>(SAPIBase + '/account/getInfo', { credential: SAPIKEY });
const { data } = await axios.post<IAPIResponse>(SAPIBase + '/account/getInfo', { id:ID, pw:PW });
setNBalance(data.balance);
}
asyncFun().catch((e) => window.alert(`AN ERROR OCCURED: ${e}`));
asyncFun().catch((e) => alert(`AN ERROR OCCURED: ${e}`));
}

const performTransaction = ( amount: number ) => {
const asyncFun = async() => {
interface IAPIResponse { success: boolean, balance: number, msg: string };
const { data } = await axios.post<IAPIResponse>(SAPIBase + '/account/transaction', { credential: SAPIKEY, amount: NBalance });
const { data } = await axios.post<IAPIResponse>(SAPIBase + '/account/transaction', { id:ID, pw:PW, amount: amount });
setNTransaction(0);
if (!data.success) {
window.alert('Transaction Failed:' + data.msg);
Expand All @@ -39,7 +40,8 @@ const AccountPage = () => {
<Header/>
<h2>Account</h2>
<div className={"account-token-input"}>
Enter API Key: <input type={"text"} value={SAPIKEY} onChange={e => setSAPIKEY(e.target.value)}/>
Enter ID: <input type={"text"} value={ID} onChange={e => setID(e.target.value)}/>
Enter PW: <input type={"text"} value={PW} onChange={e => setPW(e.target.value)}/>
<button onClick={e => getAccountInformation()}>GET</button>
</div>
<div className={"account-bank"}>
Expand Down
51 changes: 47 additions & 4 deletions client/src/pages/feed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { SAPIBase } from "../tools/api";
import Header from "../components/header";
import "./css/feed.css";

interface IAPIResponse { id: number, title: string, content: string }
interface IAPIResponse { id: number, title: string, content: string, toggle:boolean }

const FeedPage = (props: {}) => {
const [ LAPIResponse, setLAPIResponse ] = React.useState<IAPIResponse[]>([]);
const [ NPostCount, setNPostCount ] = React.useState<number>(0);
const [ NPostCount, setNPostCount ] = React.useState<number>(1); // 처음에 example 들어있음
const [ SNewPostTitle, setSNewPostTitle ] = React.useState<string>("");
const [ SNewPostContent, setSNewPostContent ] = React.useState<string>("");

Expand All @@ -17,7 +17,6 @@ const FeedPage = (props: {}) => {
const asyncFun = async () => {
const { data } = await axios.get<IAPIResponse[]>( SAPIBase + `/feed/getFeed?count=${ NPostCount }`);
console.log(data);
// const data = [ { id: 0, title: "test1", content: "Example body" }, { id: 1, title: "test2", content: "Example body" }, { id: 2, title: "test3", content: "Example body" } ].slice(0, NPostCount);
if (BComponentExited) return;
setLAPIResponse(data);
};
Expand All @@ -27,7 +26,7 @@ const FeedPage = (props: {}) => {

const createNewPost = () => {
const asyncFun = async () => {
await axios.post( SAPIBase + '/feed/addFeed', { title: SNewPostTitle, content: SNewPostContent } );
await axios.post( SAPIBase + '/feed/addFeed', { title: SNewPostTitle, content: SNewPostContent, toggle:false } );
setNPostCount(NPostCount + 1);
setSNewPostTitle("");
setSNewPostContent("");
Expand All @@ -44,6 +43,38 @@ const FeedPage = (props: {}) => {
asyncFun().catch(e => window.alert(`AN ERROR OCCURED! ${e}`));
}

const modifyPost = (id: string, altTitle: string, altContent: string) => {
const asyncFun = async() => {
await axios.post( SAPIBase + '/feed/modifyFeed', { id: id, title: altTitle, content: altContent} );
setLAPIResponse(() => (
LAPIResponse.map((value) => {
const match = (value.id === parseInt(id));
if (match) {
return {id: value.id, title: altTitle, content: altContent, toggle:value.toggle};
}
return value;
})));

}
asyncFun().catch(e => window.alert(`AN ERROR OCCURED! ${e}`));
}

const togglePost = (id: string) => {
const asyncFun = async () => {
// One can set X-HTTP-Method header to DELETE to specify deletion as well
await axios.post( SAPIBase + '/feed/toggleFeed', { id: id } );
setLAPIResponse(() => (
LAPIResponse.map((value) => {
const match = (value.id === parseInt(id));
if (match) {
return {id: value.id, title: value.title, content: value.content, toggle:!value.toggle};
}
return value;
})));
}
asyncFun().catch(e => window.alert(`AN ERROR OCCURED! ${e}`));
}

return (
<div className="Feed">
<Header/>
Expand All @@ -57,9 +88,21 @@ const FeedPage = (props: {}) => {
<div className={"feed-list"}>
{ LAPIResponse.map( (val, i) =>
<div key={i} className={"feed-item"}>
<p onClick={(e) => togglePost(`${val.id}`)}>{val.toggle?"★":"☆"}</p> {/* ?"★":"☆" */}
<div className={"delete-item"} onClick={(e) => deletePost(`${val.id}`)}>ⓧ</div>
<h3 className={"feed-title"}>{ val.title }</h3>
<p className={"feed-body"}>{ val.content }</p>
<button onClick={(e) => {
const altTitle=window.prompt("enter new title",val.title);
const altContent=window.prompt("enter new context",val.content);

console.log(LAPIResponse);

if(altTitle && altContent){
modifyPost(`${val.id}`,`${altTitle}`,`${altContent}`);
}
}}>수정</button>

</div>
) }
<div className={"feed-item-add"}>
Expand Down
2 changes: 2 additions & 0 deletions seminar/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const cors = require('cors');

const statusRouter = require('./routes/status');
const feedRouter = require('./routes/feed');
const accountRouter = require('./routes/account');

const app = express();
const port = 8080;
Expand All @@ -23,6 +24,7 @@ app.use(cors(corsOptions));

app.use('/status', statusRouter);
app.use('/feed', feedRouter);
app.use('/account', accountRouter);

app.listen(port, () => {
console.log(`Example App Listening @ http://localhost:${ port }`);
Expand Down
13 changes: 13 additions & 0 deletions seminar/src/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const authMiddleware = (req, res, next) => {
key=process.env.API_KEY || process.env.USER;
if (req.body.id === key && req.body.pw === key) {
console.log("[AUTH-MIDDLEWARE] Authorized User");
next();
}
else {
console.log("[AUTH-MIDDLEWARE] Not Authorized User");
res.status(401).json({ error: "Not Authorized" });
}
}

module.exports = authMiddleware;
50 changes: 50 additions & 0 deletions seminar/src/routes/account.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const express = require('express');
const authMiddleware = require('../middleware/auth');

const router = express.Router();

class BankDB {
static _inst_;
static getInst = () => {
if ( !BankDB._inst_ ) BankDB._inst_ = new BankDB();
return BankDB._inst_;
}

#total = 10000;

constructor() { console.log("[Bank-DB] DB Init Completed"); }

getBalance = () => {
return { success: true, data: this.#total };
}

transaction = ( amount ) => {
this.#total += amount;
return { success: true, data: this.#total };
}
}

const bankDBInst = BankDB.getInst();

router.post('/getInfo', authMiddleware, (req, res) => {
try {
const { success, data } = bankDBInst.getBalance();
if (success) return res.status(200).json({ balance: data });
else return res.status(500).json({ error: data });
} catch (e) {
return res.status(500).json({ error: e });
}
});

router.post('/transaction', authMiddleware, (req, res) => {
try {
const { amount } = req.body;
const { success, data } = bankDBInst.transaction( parseInt(amount) );
if (success) res.status(200).json({ success: true, balance: data, msg: "Transaction success" });
else res.status(500).json({ error: data })
} catch (e) {
return res.status(500).json({ error: e });
}
})

module.exports = router;
55 changes: 53 additions & 2 deletions seminar/src/routes/feed.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class FeedDB {
return FeedDB._inst_;
}

#id = 1; #itemCount = 1; #LDataDB = [{ id: 0, title: "test1", content: "Example body" }];
#id = 1; #itemCount = 1; #LDataDB = [{ id: 0, title: "test1", content: "Example body", toggle: false }];

constructor() { console.log("[Feed-DB] DB Init Completed"); }

Expand All @@ -21,7 +21,7 @@ class FeedDB {

insertItem = ( item ) => {
const { title, content } = item;
this.#LDataDB.push({ id: this.#id, title, content });
this.#LDataDB.push({ id: this.#id, title, content, toggle:false });
this.#id++; this.#itemCount++;
return true;
}
Expand All @@ -36,6 +36,34 @@ class FeedDB {
if (BItemDeleted) id--;
return BItemDeleted;
}

modifyItem = (item) => {
const { id, title, content } = item;
let BItemModified = false;

this.#LDataDB = this.#LDataDB.map((value) => {
const match = (value.id === parseInt(id));
if (match) {
BItemModified=true;
return {id: value.id, title, content, toggle: value.toggle};
}
return value;
});
return BItemModified;
}

toggleItem = (id) => {
let BItemToggled = false;
this.#LDataDB = this.#LDataDB.map((value) => {
const match = (value.id === id);
if (match) {
BItemToggled=true;
return {id: value.id, title: value.title, content:value.content, toggle: !value.toggle};
}
return value;
});
return BItemToggled;
}
}

const feedDBInst = FeedDB.getInst();
Expand All @@ -62,6 +90,7 @@ router.post('/addFeed', (req, res) => {
}
});


router.post('/deleteFeed', (req, res) => {
try {
const { id } = req.body;
Expand All @@ -73,4 +102,26 @@ router.post('/deleteFeed', (req, res) => {
}
})

router.post('/modifyFeed', (req, res) => {
try {
const { id, title, content } = req.body;
const modifyResult=feedDBInst.modifyItem({id, title,content});
if (!modifyResult) return res.status(500).json({ error: "Failed to modify" })
else return res.status(200).json({ isOK: true });
} catch (e) {
return res.status(500).json({ error: e });
}
})

router.post('/toggleFeed', (req, res) => {
try{
const {id} = req.body;
const toggleResult = feedDBInst.toggleItem(parseInt(id));
if (!toggleResult) return res.status(500).json({ error: "No item deleted" })
else return res.status(200).json({ isOK: true });
} catch (e) {
return res.status(500).json({error: e });
}
})

module.exports = router;