🌖 The Art of React part2
🎄 アイテムのクリーンアップ
🔥 コード#コード#
// post/index.js
import Router from 'koa-router';
import * as postsCtrl from './posts.ctrl';
const posts = new Router();
posts.get('/', postsCtrl.list);
posts.post('/', postsCtrl.write);
const post = new Router(); // /api/posts/:id
post.get('/', postsCtrl.read);
post.delete('/', postsCtrl.remove);
post.patch('/', postsCtrl.update);
posts.use('/:id', postsCtrl.checkObjectId, post.routes());
export default posts;
// posts.ctrl.js
import Post from "../../models/post"
import mongoose from "mongoose";
import Joi from "joi"
const { ObjectId } = mongoose.Types;
export const checkObjectId = (ctx, next) => {
const { id } = ctx.params;
if (!ObjectId.isValid(id)) {
ctx.status = 400;
return;
}
return next();
}
export const write = async ctx => {
// 객체 검증을 수월하게 해주는 joi가 있음
const schema = Joi.object().keys({
title: Joi.string().required(),
body: Joi.string().required(),
tags: Joi.array().items(Joi.string()).required()
})
// const result = Joi.validate(body, schema);
// const validation = schema.validate(body);
const result = schema.validate(ctx.request.body);
if (result.error) {
ctx.status = 400;
ctx.body = result.error;
return;
}
const { title, body, tags } = ctx.request.body;
const post = new Post({ title, body, tags });
try {
await post.save();
ctx.body = post;
} catch (e) {
ctx.throw(500, e)
}
};
export const list = async ctx => {
const page = parseInt(ctx.query.page || "1", 10);
if (page < 1) {
ctx.status = 400;
return;
}
try {
//lean 함수는 처으ㅁ부터 데이터를 조회할 때 JSON 형태로 조회 가능
const posts = await Post.find()
.sort({ _id: -1 })
.limit(10)
.skip((page - 1) * 10)
.lean()
.exec();
const postCount = await Post.countDocuments().exec();
ctx.set('Last-Page', Math.ceil(postCount / 10));
ctx.body = posts.map(post => ({
...post, body: post.body.length < 200 ? post.body : `${post.body.slice(0, 200)}...`
}))
} catch (e) {
ctx.throw(500, e)
}
};
export const read = async ctx => {
const { id } = ctx.params;
try {
const post = await Post.findById(id).exec();
console.log(id)
if (!post) {
ctx.status = 404;
return;
}
ctx.body = post
} catch (e) {
ctx.throw(500, e)
}
};
export const remove = async ctx => {
const { id } = ctx.params;
try {
await Post.findByIdAndRemove(id).exec();
ctx.status = 204;
} catch (e) {
ctx.throw(500, e)
}
};
export const update = async ctx => {
const { id } = ctx.params;
const schema = Joi.object().keys({
title: Joi.string(),
body: Joi.string(),
tags: Joi.array().items(Joi.string())
})
const result = schema.validate(ctx.request.body);
//검증하고 나서 검증 실패인 경우 에러 처리
if (result.error) {
ctx.status = 400;
ctx.body = result.error;
return;
}
try {
const post = await Post.findByIdAndUpdate(id, ctx.request.body, {
new: true
}).exec();
if (!post) {
ctx.status = 404;
return;
}
ctx.body = post
} catch (e) {
ctx.throw(500, e)
}
};
Reference
この問題について(🌖 The Art of React part2), 我々は、より多くの情報をここで見つけました https://velog.io/@pluviabc1/The-Art-of-React-part2テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol