File size: 2,182 Bytes
e02f7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from flask import Blueprint, request, jsonify
from src.models.user import db
from src.models.post import Post, Comment

post_bp = Blueprint('post', __name__)

@post_bp.route('/posts', methods=['GET'])
def get_posts():
    """ดึงโพสต์ทั้งหมด"""
    posts = Post.query.order_by(Post.created_at.desc()).all()
    return jsonify([post.to_dict() for post in posts])

@post_bp.route('/posts', methods=['POST'])
def create_post():
    """สร้างโพสต์ใหม่"""
    data = request.get_json()
    
    if not data or not data.get('name') or not data.get('note'):
        return jsonify({'error': 'Name and note are required'}), 400
    
    post = Post(
        name=data['name'],
        note=data['note'],
        youtube_link=data.get('youtube_link', '')
    )
    
    db.session.add(post)
    db.session.commit()
    
    return jsonify(post.to_dict()), 201

@post_bp.route('/posts/<int:post_id>/like', methods=['POST'])
def like_post(post_id):
    """ถูกใจโพสต์"""
    post = Post.query.get_or_404(post_id)
    post.likes += 1
    db.session.commit()
    
    return jsonify({'likes': post.likes})

@post_bp.route('/posts/<int:post_id>/comments', methods=['GET'])
def get_comments(post_id):
    """ดึงคอมเมนต์ของโพสต์"""
    comments = Comment.query.filter_by(post_id=post_id).order_by(Comment.created_at.asc()).all()
    return jsonify([comment.to_dict() for comment in comments])

@post_bp.route('/posts/<int:post_id>/comments', methods=['POST'])
def add_comment(post_id):
    """เพิ่มคอมเมนต์ในโพสต์"""
    data = request.get_json()
    
    if not data or not data.get('name') or not data.get('comment'):
        return jsonify({'error': 'Name and comment are required'}), 400
    
    # ตรวจสอบว่าโพสต์มีอยู่จริง
    post = Post.query.get_or_404(post_id)
    
    comment = Comment(
        post_id=post_id,
        name=data['name'],
        comment=data['comment']
    )
    
    db.session.add(comment)
    db.session.commit()
    
    return jsonify(comment.to_dict()), 201