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//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//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//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