Skip to content
Merged
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Binary file added .DS_Store
Binary file not shown.
56 changes: 0 additions & 56 deletions .gitignore

This file was deleted.

8 changes: 8 additions & 0 deletions .vite/deps/_metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"hash": "e2ef4e8a",
"configHash": "d66f52f1",
"lockfileHash": "6d86ea89",
"browserHash": "dff7af04",
"optimized": {},
"chunks": {}
}
3 changes: 3 additions & 0 deletions .vite/deps/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "module"
}
3 changes: 3 additions & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
DATABASE_URL =
"mongodb+srv://wonj2087:zJvGgAiFnAHS8Ea0@cluster0.auvqpaw.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
PORT=3000
99 changes: 99 additions & 0 deletions backend/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
//import { DATABASE_URL } from './env.js';
import * as dotenv from "dotenv";
dotenv.config();
import Products from "./models/Products.js";

const app = express();
app.use(cors());
app.use(express.json());

//mongoose.connect(DATABASE_URL).then(() => console.log('Connected to DB'));
mongoose
.connect(process.env.DATABASE_URL)
.then(() => console.log("Connected to DB"));

function asyncHandler(handler) {
// 라우터에 들어가는 핸들러 함수를 파라미터로 받아서
return async function (req, res) {
// 새로운 핸들러 함수를 반환한다. -> 파라미터로 받는 핸들러 함수와 동일하나 오류처리가 된 상태
try {
await handler(req, res);
} catch (e) {
// 각 오류에 맞는 오류 메세지를 보여준다
if (e.name === "ValidationError") {
res.status(400).send({ message: e.message });
} else if (e.name === "CastError") {
res.status(404).send({ message: "Cannot find given id." });
} else {
res.status(500).send({ message: e.message });
}
}
};
}

app.get("/items", async (req, res) => {
const sort = req.query.sort;
const count = Number(req.query.count) || 0;

const sortOption = { createdAt: sort === "oldest" ? "asc" : "desc" };
const products = await Products.find().sort(sortOption).limit(count);

res.send(products); // JS 객체를 받으면 자동으로 JSON으로 변환해서 돌려준다.
});

app.get("/items/:id", async (req, res) => {
const id = req.params.id;
const product = await Products.findById(id); //mongo DB 에서 제공하는 함수(id는 string을 이용)
if (product) {
res.send(product);
} else {
// status 메소드를 이용해서 status 코드 설정가능
res.status(404).send({ message: "Cannot find given id" });
}
});

// 비동기 오류 처리를 위해 asyncHandler 함수로 감싸기
app.post(
"/items",
asyncHandler(async (req, res) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

asyncHandler를 통해 비동기를 통합 관리하신 점이 좋네요!

const product = await Products.create(req.body);
res.status(201).send(product);
})
);

app.patch(
"/items/:id",
asyncHandler(async (req, res) => {
const id = req.params.id;
const product = await Products.findById(id);
if (product) {
// product 있다면 req로 들어온 body의 정보로 덮어씌워야함
Object.keys(req.body).forEach((key) => {
product[key] = req.body[key]; // 기존의 task 값을 body 값으로 변경
});
await product.save(); // DB에 저장
res.send(product);
} else {
res.status(404).send({ message: "Cannot find given id" });
}
})
);

app.delete(
"/items/:id",
asyncHandler(async (req, res) => {
const id = req.params.id;
const product = await Products.findByIdAndDelete(id); // 객체를 찾아서 삭제까지 해주는 함수. 삭제를 한 객체, 없다면 null 반환
if (product) {
res.sendStatus(204); // 바디 없이 상태코드만 반환
} else {
res.status(404).send({ message: "Cannot find given id" });
}
})
);

// app.listen(3000, () => console.log('server started!'));
app.listen(process.env.PORT || 3000, () => console.log("Server Started"));
11 changes: 11 additions & 0 deletions backend/data/mock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const data = [
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mock 데이터를 작성하셔서 대략적인 데이터 구조를 알 수 있어 좋았습니다.

{
name: "로봇 청소기",
description: "상품 상세 설명입니다.",
price: 1500000,
tags: ["전자기기", "청소기"],
favoriteCount: 240,
},
];

export default data;
14 changes: 14 additions & 0 deletions backend/data/seed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import mongoose from "mongoose";
import data from './mock.js';
import Products from "../models/Products.js";
//import { DATABASE_URL } from "../env.js";
import * as dotenv from 'dotenv';
dotenv.config();

//mongoose.connect(DATABASE_URL);
mongoose.connect(process.env.DATABASE_URL);

await Products.deleteMany({});
await Products.insertMany(data);

mongoose.connection.close();
2 changes: 2 additions & 0 deletions backend/env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const DATABASE_URL =
"mongodb+srv://wonj2087:zJvGgAiFnAHS8Ea0@cluster0.auvqpaw.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
32 changes: 32 additions & 0 deletions backend/models/Products.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import mongoose from "mongoose";

const ProductsShema = new mongoose.Schema(
{
name: {
type: String,
required: true,
maxLenth: 30,
},
description: {
type: String,
},
price: {
type: Number,
required: true,
min: 0,
},
tags: {
type: [String],
},
favoriteCount: {
type: Number,
},
},
{
timestamps: true,
}
);

const Products = mongoose.model("Products", ProductsShema);

export default Products;
1 change: 1 addition & 0 deletions backend/node_modules/.bin/nodemon

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

1 change: 1 addition & 0 deletions backend/node_modules/.bin/nodetouch

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

1 change: 1 addition & 0 deletions backend/node_modules/.bin/semver

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

Loading