Skip to content
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
134 changes: 134 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# env
.env
env.js
192 changes: 192 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
import cors from "cors";
import * as dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
import Product from "./models/product.js";

dotenv.config();
mongoose.connect(process.env.DATABASE_URL).then(() => console.log("Connected to DB"));
const app = express();
app.use(cors());
const corsOptions = {
origin: ["http://127.0.0.1:3000", "https://panda-market.com"],
};
app.use(cors(corsOptions));
app.use(express.json());

const asyncHandler = (handler) => {
return async (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: "존재하지 않는 상품입니다." });
} else {
res.status(500).send({ message: "서버 에러입니다." });
}
}
};
};

// 상품 목록 조회
app.get(
"/products",
asyncHandler(async (req, res) => {
/**
* 쿼리 파라미터
* - offset : 가져올 데이터의 시작 지점
* - limit : 한 번에 가져올 데이터의 개수
* - orderBy : 정렬 기준 favorite, recent (기본값: recent)
* - keyword : 검색 키워드
*/
const offset = Number(req.query.offset) || 0;
const limit = Number(req.query.limit) || 10;
const orderBy = req.query.orderBy;
const keyword = req.query.keyword || "";

const sortOption = orderBy === "favorite" ? { favoriteCount: "desc" } : { createdAt: "desc" };

const query = keyword
? {
$or: [{ name: { $regex: keyword, $options: "i" } }, { description: { $regex: keyword, $options: "i" } }],
}
: {};

const products = await Product.find(query)
.select("_id name price images createdAt favoriteCount isFavorite")
.sort(sortOption)
.skip(offset)
.limit(limit);

const totalProducts = await Product.countDocuments(query);

res.send({
products,
totalProducts,
currentOffset: offset,
limit: limit,
});
})
);

// 상품 상세 조회
app.get(
"/products/:id",
asyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id).select("-updatedAt");
if (!product) {
res.status(404).send({ message: "존재하지 않는 상품입니다." });
return;
}

res.send(product);
})
);

// 상품 등록
app.post(
"/products",
asyncHandler(async (req, res) => {
const newProduct = await Product.create(req.body);
res.status(201).send(newProduct);
})
);

// 상품 수정
app.patch(
"/products/:id",
asyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id);

if (!product) {
res.status(404).send({ message: "존재하지 않는 상품입니다." });
return;
}
const disallowedFields = {
favoriteCount: true,
isFavorite: true,
ownerId: true,
};

Object.keys(req.body).forEach((key) => {
if (!disallowedFields[key]) {
product[key] = req.body[key];
}
});

await product.save();

res.send(product);
})
);

// 상품 삭제
app.delete(
"/products/:id",
asyncHandler(async (req, res) => {
const product = await Product.findByIdAndDelete(req.params.id);

if (!product) {
res.status(404).send({ message: "존재하지 않는 상품입니다." });
return;
}

res.sendStatus(204);
})
);

// 상품 좋아요
app.patch(
"/products/:id/like",
asyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id);

if (!product) {
res.status(404).send({ message: "존재하지 않는 상품입니다." });
return;
}

if (product.isFavorite) {
res.status(400).send({ message: "이미 좋아요 처리된 상품입니다." });
return;
}

product.favoriteCount += 1;
product.isFavorite = true;

await product.save();

res.send(product);
})
);

// 상품 좋아요 취소
app.patch(
"/products/:id/unlike",
asyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id);

if (!product) {
res.status(404).send({ message: "존재하지 않는 상품입니다." });
return;
}

if (!product.isFavorite) {
res.status(400).send({ message: "아직 좋아요 처리되지 않은 상품입니다." });
return;
}

if (product.favoriteCount > 0) {
product.favoriteCount -= 1;
}
product.isFavorite = false;

await product.save();

res.send(product);
})
);

app.listen(process.env.PORT || 3000, () => console.log("Server Started"));
24 changes: 24 additions & 0 deletions data/mock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const data = [
{
favoriteCount: 0,
ownerId: 1,
images: ["https://sitem.ssgcdn.com/62/11/49/item/1000559491162_i1_1100.jpg"],
tags: ["판다인형", "인형", "판다"],
price: 700000,
description: "판다인형 판다",
name: "판다인형",
},
{
favoriteCount: 2,
ownerId: 2,
images: [
"https://view01.wemep.co.kr/wmp-product/4/879/2515748794/pm_ebifv5nrjsyf.jpg?1683280710&f=webp&w=460&h=460",
],
tags: ["판다인형", "인형", "판다"],
price: 7000,
description: "판다인형 안판다",
name: "판다인형 안파는 판다",
},
];

export default data;
12 changes: 12 additions & 0 deletions data/seed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as dotenv from "dotenv";
import mongoose from "mongoose";
import Product from "../models/product.js";
import data from "./mock.js";

dotenv.config();
mongoose.connect(process.env.DATABASE_URL);

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

mongoose.connection.close();
Loading