-
Notifications
You must be signed in to change notification settings - Fork 22
[조원정] Sprint6 #118
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
The head ref may contain hidden characters: "react-\uC870\uC6D0\uC815-sprint6"
[조원정] Sprint6 #118
Changes from all commits
949fa09
88dde41
f71adb2
1b8b5dd
00e56e0
1d1a7fa
bc3472e
5cd89ba
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "hash": "e2ef4e8a", | ||
| "configHash": "d66f52f1", | ||
| "lockfileHash": "6d86ea89", | ||
| "browserHash": "dff7af04", | ||
| "optimized": {}, | ||
| "chunks": {} | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| { | ||
| "type": "module" | ||
| } |
| 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 |
| 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) => { | ||
| 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")); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| const data = [ | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. mock 데이터를 작성하셔서 대략적인 데이터 구조를 알 수 있어 좋았습니다. |
||
| { | ||
| name: "로봇 청소기", | ||
| description: "상품 상세 설명입니다.", | ||
| price: 1500000, | ||
| tags: ["전자기기", "청소기"], | ||
| favoriteCount: 240, | ||
| }, | ||
| ]; | ||
|
|
||
| export default data; | ||
| 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(); |
| 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"; |
| 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; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
asyncHandler를 통해 비동기를 통합 관리하신 점이 좋네요!