From 4c1be89be208145d7e5d28db44ce612353acb032 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?der=C3=86ndi?= <3369983+deraendi@users.noreply.github.com> Date: Sun, 23 Nov 2025 10:48:26 +0000 Subject: [PATCH 1/5] settings MCP server --- .vscode/settings.json | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..51a564d --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "chat.tools.autoApprove": true, + "chat.agent.maxRequests": 100 +} \ No newline at end of file From 7b5d2fcd46d63bf1424aef65e241cc7f361e9431 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?der=C3=86ndi?= <3369983+deraendi@users.noreply.github.com> Date: Sun, 23 Nov 2025 10:56:35 +0000 Subject: [PATCH 2/5] add beast mode --- .github/chatmodes/4.1-Beast.chatmode.md | 152 ++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 .github/chatmodes/4.1-Beast.chatmode.md diff --git a/.github/chatmodes/4.1-Beast.chatmode.md b/.github/chatmodes/4.1-Beast.chatmode.md new file mode 100644 index 0000000..20bec84 --- /dev/null +++ b/.github/chatmodes/4.1-Beast.chatmode.md @@ -0,0 +1,152 @@ +--- +description: 'GPT 4.1 as a top-notch coding agent.' +model: GPT-4.1 +title: '4.1 Beast Mode v3.1' +--- + +You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. + +Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough. + +You MUST iterate and keep going until the problem is solved. + +You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me. + +Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn. + +THE PROBLEM CAN NOT BE SOLVED WITHOUT EXTENSIVE INTERNET RESEARCH. + +You must use the fetch_webpage tool to recursively gather all information from URL's provided to you by the user, as well as any links you find in the content of those pages. + +Your knowledge on everything is out of date because your training date is in the past. + +You CANNOT successfully complete this task without using Google to verify your understanding of third party packages and dependencies is up to date. You must use the fetch_webpage tool to search google for how to properly use libraries, packages, frameworks, dependencies, etc. every single time you install or implement one. It is not enough to just search, you must also read the content of the pages you find and recursively gather all relevant information by fetching additional links until you have all the information you need. + +Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why. + +If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is. + +Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Use the sequential thinking tool if available. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided. + +You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully. + +You MUST keep working until the problem is completely solved, and all items in the todo list are checked off. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead of just saying that you will do it. + +You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input. + +# Workflow +1. Fetch any URL's provided by the user using the `fetch_webpage` tool. +2. Understand the problem deeply. Carefully read the issue and think critically about what is required. Use sequential thinking to break down the problem into manageable parts. Consider the following: + - What is the expected behavior? + - What are the edge cases? + - What are the potential pitfalls? + - How does this fit into the larger context of the codebase? + - What are the dependencies and interactions with other parts of the code? +3. Investigate the codebase. Explore relevant files, search for key functions, and gather context. +4. Research the problem on the internet by reading relevant articles, documentation, and forums. +5. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using emojis to indicate the status of each item. +6. Implement the fix incrementally. Make small, testable code changes. +7. Debug as needed. Use debugging techniques to isolate and resolve issues. +8. Test frequently. Run tests after each change to verify correctness. +9. Iterate until the root cause is fixed and all tests pass. +10. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete. + +Refer to the detailed sections below for more information on each step. + +## 1. Fetch Provided URLs +- If the user provides a URL, use the `functions.fetch_webpage` tool to retrieve the content of the provided URL. +- After fetching, review the content returned by the fetch tool. +- If you find any additional URLs or links that are relevant, use the `fetch_webpage` tool again to retrieve those links. +- Recursively gather all relevant information by fetching additional links until you have all the information you need. + +## 2. Deeply Understand the Problem +Carefully read the issue and think hard about a plan to solve it before coding. + +## 3. Codebase Investigation +- Explore relevant files and directories. +- Search for key functions, classes, or variables related to the issue. +- Read and understand relevant code snippets. +- Identify the root cause of the problem. +- Validate and update your understanding continuously as you gather more context. + +## 4. Internet Research +- Use the `fetch_webpage` tool to search google by fetching the URL `https://www.google.com/search?q=your+search+query`. +- After fetching, review the content returned by the fetch tool. +- You MUST fetch the contents of the most relevant links to gather information. Do not rely on the summary that you find in the search results. +- As you fetch each link, read the content thoroughly and fetch any additional links that you find within the content that are relevant to the problem. +- Recursively gather all relevant information by fetching links until you have all the information you need. + +## 5. Develop a Detailed Plan +- Outline a specific, simple, and verifiable sequence of steps to fix the problem. +- Create a todo list in markdown format to track your progress. +- Each time you complete a step, check it off using `[x]` syntax. +- Each time you check off a step, display the updated todo list to the user. +- Make sure that you ACTUALLY continue on to the next step after checking off a step instead of ending your turn and asking the user what they want to do next. + +## 6. Making Code Changes +- Before editing, always read the relevant file contents or section to ensure complete context. +- Always read 2000 lines of code at a time to ensure you have enough context. +- If a patch is not applied correctly, attempt to reapply it. +- Make small, testable, incremental changes that logically follow from your investigation and plan. +- Whenever you detect that a project requires an environment variable (such as an API key or secret), always check if a .env file exists in the project root. If it does not exist, automatically create a .env file with a placeholder for the required variable(s) and inform the user. Do this proactively, without waiting for the user to request it. + +## 7. Debugging +- Use the `get_errors` tool to check for any problems in the code +- Make code changes only if you have high confidence they can solve the problem +- When debugging, try to determine the root cause rather than addressing symptoms +- Debug for as long as needed to identify the root cause and identify a fix +- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening +- To test hypotheses, you can also add test statements or functions +- Revisit your assumptions if unexpected behavior occurs. + +# How to create a Todo List +Use the following format to create a todo list: +```markdown +- [ ] Step 1: Description of the first step +- [ ] Step 2: Description of the second step +- [ ] Step 3: Description of the third step +``` + +Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above. Always wrap the todo list in triple backticks so that it is formatted correctly and can be easily copied from the chat. + +Always show the completed todo list to the user as the last item in your message, so that they can see that you have addressed all of the steps. + +# Communication Guidelines +Always communicate clearly and concisely in a casual, friendly yet professional tone. + +"Let me fetch the URL you provided to gather more information." +"Ok, I've got all of the information I need on the LIFX API and I know how to use it." +"Now, I will search the codebase for the function that handles the LIFX API requests." +"I need to update several files here - stand by" +"OK! Now let's run the tests to make sure everything is working correctly." +"Whelp - I see we have some problems. Let's fix those up." + + +- Respond with clear, direct answers. Use bullet points and code blocks for structure. - Avoid unnecessary explanations, repetition, and filler. +- Always write code directly to the correct files. +- Do not display code to the user unless they specifically ask for it. +- Only elaborate when clarification is essential for accuracy or user understanding. + +# Memory +You have a memory that stores information about the user and their preferences. This memory is used to provide a more personalized experience. You can access and update this memory as needed. The memory is stored in a file called `.github/instructions/memory.instruction.md`. If the file is empty, you'll need to create it. + +When creating a new memory file, you MUST include the following front matter at the top of the file: +```yaml +--- +applyTo: '**' +--- +``` + +If the user asks you to remember something or add something to your memory, you can do so by updating the memory file. + +# Writing Prompts +If you are asked to write a prompt, you should always generate the prompt in markdown format. + +If you are not writing the prompt in a file, you should always wrap the prompt in triple backticks so that it is formatted correctly and can be easily copied from the chat. + +Remember that todo lists must always be written in markdown format and must always be wrapped in triple backticks. + +# Git +If the user tells you to stage and commit, you may do so. + +You are NEVER allowed to stage and commit files automatically. From fced30b353e105faf3c233769f5c8fc3f9b98fa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?der=C3=86ndi?= <3369983+deraendi@users.noreply.github.com> Date: Sun, 23 Nov 2025 11:00:15 +0000 Subject: [PATCH 3/5] analyse requirement and generate openapi yml --- openapi.yaml | 334 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 334 insertions(+) create mode 100644 openapi.yaml diff --git a/openapi.yaml b/openapi.yaml new file mode 100644 index 0000000..ff90124 --- /dev/null +++ b/openapi.yaml @@ -0,0 +1,334 @@ +openapi: 3.0.1 +info: + title: Simple Social Media Application API + version: 1.0.0 + description: API for a basic social networking service with posts, comments, and likes. +servers: + - url: http://localhost:8080/api +paths: + /posts: + get: + summary: List all posts + responses: + '200': + description: List of posts + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Post' + '500': + $ref: '#/components/responses/Error' + post: + summary: Create a new post + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PostCreate' + responses: + '201': + description: Post created + content: + application/json: + schema: + $ref: '#/components/schemas/Post' + '400': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + /posts/{postId}: + parameters: + - name: postId + in: path + required: true + schema: + type: string + get: + summary: Get a single post + responses: + '200': + description: Post details + content: + application/json: + schema: + $ref: '#/components/schemas/Post' + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + patch: + summary: Update a post + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PostUpdate' + responses: + '200': + description: Post updated + content: + application/json: + schema: + $ref: '#/components/schemas/Post' + '400': + $ref: '#/components/responses/Error' + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + delete: + summary: Delete a post + responses: + '204': + description: Post deleted + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + /posts/{postId}/comments: + parameters: + - name: postId + in: path + required: true + schema: + type: string + get: + summary: List comments for a post + responses: + '200': + description: List of comments + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Comment' + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + post: + summary: Create a comment + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CommentCreate' + responses: + '201': + description: Comment created + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '400': + $ref: '#/components/responses/Error' + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + /posts/{postId}/comments/{commentId}: + parameters: + - name: postId + in: path + required: true + schema: + type: string + - name: commentId + in: path + required: true + schema: + type: string + get: + summary: Get a specific comment + responses: + '200': + description: Comment details + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + patch: + summary: Update a comment + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CommentUpdate' + responses: + '200': + description: Comment updated + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '400': + $ref: '#/components/responses/Error' + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + delete: + summary: Delete a comment + responses: + '204': + description: Comment deleted + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + /posts/{postId}/likes: + parameters: + - name: postId + in: path + required: true + schema: + type: string + post: + summary: Like a post + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LikeCreate' + responses: + '201': + description: Like added + '400': + $ref: '#/components/responses/Error' + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' + delete: + summary: Unlike a post + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LikeDelete' + responses: + '204': + description: Like removed + '404': + $ref: '#/components/responses/Error' + '500': + $ref: '#/components/responses/Error' +components: + schemas: + Post: + type: object + properties: + id: + type: string + username: + type: string + content: + type: string + createdAt: + type: string + format: date-time + updatedAt: + type: string + format: date-time + likes: + type: integer + comments: + type: integer + PostCreate: + type: object + required: + - username + - content + properties: + username: + type: string + content: + type: string + PostUpdate: + type: object + required: + - username + - content + properties: + username: + type: string + content: + type: string + Comment: + type: object + properties: + id: + type: string + postId: + type: string + username: + type: string + content: + type: string + createdAt: + type: string + format: date-time + updatedAt: + type: string + format: date-time + CommentCreate: + type: object + required: + - username + - content + properties: + username: + type: string + content: + type: string + CommentUpdate: + type: object + required: + - username + - content + properties: + username: + type: string + content: + type: string + LikeCreate: + type: object + required: + - username + properties: + username: + type: string + LikeDelete: + type: object + required: + - username + properties: + username: + type: string + Error: + type: object + properties: + message: + type: string + code: + type: integer + responses: + Error: + description: Error response + content: + application/json: + schema: + $ref: '#/components/schemas/Error' From bff611694f637475360ba348e866e67556ccdf88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?der=C3=86ndi?= <3369983+deraendi@users.noreply.github.com> Date: Sun, 23 Nov 2025 11:09:56 +0000 Subject: [PATCH 4/5] error with version --- openapi.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openapi.yaml b/openapi.yaml index ff90124..d4dbe79 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -1,4 +1,4 @@ -openapi: 3.0.1 +openapi: 3.1.0 info: title: Simple Social Media Application API version: 1.0.0 From f4fac3952c253ca6d337316caf329478231697f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?der=C3=86ndi?= <3369983+deraendi@users.noreply.github.com> Date: Sun, 23 Nov 2025 15:33:06 +0000 Subject: [PATCH 5/5] first 2 steps of python backend --- python/main.py | 329 ++++++++++++++++++++++++++++++++++++++++++++++ python/sns_api.db | Bin 0 -> 28672 bytes 2 files changed, 329 insertions(+) create mode 100644 python/main.py create mode 100644 python/sns_api.db diff --git a/python/main.py b/python/main.py new file mode 100644 index 0000000..85e38ec --- /dev/null +++ b/python/main.py @@ -0,0 +1,329 @@ +import os +from fastapi import FastAPI, HTTPException, Request, Response, status +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import FileResponse, JSONResponse +from fastapi.openapi.docs import get_swagger_ui_html +from pydantic import BaseModel, Field +from typing import List, Optional +import sqlite3 +from datetime import datetime + +DB_PATH = os.path.join(os.path.dirname(__file__), "sns_api.db") +OPENAPI_PATH = os.path.join(os.path.dirname(__file__), "../openapi.yaml") + +app = FastAPI(openapi_url=None, docs_url=None, redoc_url=None) + +# Enable CORS from everywhere +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +def get_db(): + conn = sqlite3.connect(DB_PATH) + conn.row_factory = sqlite3.Row + return conn + +def init_db(): + conn = get_db() + c = conn.cursor() + # Posts table + c.execute(""" + CREATE TABLE IF NOT EXISTS posts ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL, + content TEXT NOT NULL, + createdAt TEXT NOT NULL, + updatedAt TEXT NOT NULL + ) + """) + # Comments table + c.execute(""" + CREATE TABLE IF NOT EXISTS comments ( + id TEXT PRIMARY KEY, + postId TEXT NOT NULL, + username TEXT NOT NULL, + content TEXT NOT NULL, + createdAt TEXT NOT NULL, + updatedAt TEXT NOT NULL + ) + """) + # Likes table + c.execute(""" + CREATE TABLE IF NOT EXISTS likes ( + postId TEXT NOT NULL, + username TEXT NOT NULL, + PRIMARY KEY (postId, username) + ) + """) + conn.commit() + conn.close() + +@app.on_event("startup") +def startup_event(): + init_db() + +# Serve Swagger UI at default endpoint +@app.get("/", include_in_schema=False) +def swagger_ui(): + return get_swagger_ui_html(openapi_url="/openapi.yaml", title="Simple Social Media Application API") + +# Serve exact OpenAPI YAML at default endpoint +@app.get("/openapi.yaml", include_in_schema=False) +def openapi_yaml(): + return FileResponse(OPENAPI_PATH, media_type="application/yaml") + +# ...existing code for endpoints will be added here... +# --- Pydantic Models --- +class Post(BaseModel): + id: str + username: str + content: str + createdAt: str + updatedAt: str + likes: int + comments: int + +class PostCreate(BaseModel): + username: str + content: str + +class PostUpdate(BaseModel): + username: str + content: str + +class Comment(BaseModel): + id: str + postId: str + username: str + content: str + createdAt: str + updatedAt: str + +class CommentCreate(BaseModel): + username: str + content: str + +class CommentUpdate(BaseModel): + username: str + content: str + +class LikeCreate(BaseModel): + username: str + +class LikeDelete(BaseModel): + username: str + +class Error(BaseModel): + message: str + code: int + +# --- Utility Functions --- +def error_response(message: str, code: int): + return JSONResponse(status_code=code, content={"message": message, "code": code}) + +# --- Endpoints --- +# List Posts +@app.get("/posts", response_model=List[Post]) +def list_posts(): + conn = get_db() + c = conn.cursor() + posts = c.execute("SELECT * FROM posts").fetchall() + result = [] + for post in posts: + post_id = post["id"] + likes = c.execute("SELECT COUNT(*) FROM likes WHERE postId=?", (post_id,)).fetchone()[0] + comments = c.execute("SELECT COUNT(*) FROM comments WHERE postId=?", (post_id,)).fetchone()[0] + result.append(Post(**dict(post), likes=likes, comments=comments)) + conn.close() + return result + +# Create Post +@app.post("/posts", response_model=Post, status_code=201) +def create_post(data: PostCreate): + conn = get_db() + c = conn.cursor() + post_id = os.urandom(8).hex() + now = datetime.utcnow().isoformat() + try: + c.execute("INSERT INTO posts (id, username, content, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)", + (post_id, data.username, data.content, now, now)) + conn.commit() + likes = 0 + comments = 0 + post = Post(id=post_id, username=data.username, content=data.content, createdAt=now, updatedAt=now, likes=likes, comments=comments) + return post + except Exception as e: + return error_response("Could not create post", 400) + finally: + conn.close() + +# Get Single Post +@app.get("/posts/{postId}", response_model=Post) +def get_post(postId: str): + conn = get_db() + c = conn.cursor() + post = c.execute("SELECT * FROM posts WHERE id=?", (postId,)).fetchone() + if not post: + conn.close() + return error_response("Post not found", 404) + likes = c.execute("SELECT COUNT(*) FROM likes WHERE postId=?", (postId,)).fetchone()[0] + comments = c.execute("SELECT COUNT(*) FROM comments WHERE postId=?", (postId,)).fetchone()[0] + result = Post(**dict(post), likes=likes, comments=comments) + conn.close() + return result + +# Update Post +@app.patch("/posts/{postId}", response_model=Post) +def update_post(postId: str, data: PostUpdate): + conn = get_db() + c = conn.cursor() + post = c.execute("SELECT * FROM posts WHERE id=?", (postId,)).fetchone() + if not post: + conn.close() + return error_response("Post not found", 404) + now = datetime.utcnow().isoformat() + try: + c.execute("UPDATE posts SET username=?, content=?, updatedAt=? WHERE id=?", + (data.username, data.content, now, postId)) + conn.commit() + likes = c.execute("SELECT COUNT(*) FROM likes WHERE postId=?", (postId,)).fetchone()[0] + comments = c.execute("SELECT COUNT(*) FROM comments WHERE postId=?", (postId,)).fetchone()[0] + result = Post(id=postId, username=data.username, content=data.content, createdAt=post["createdAt"], updatedAt=now, likes=likes, comments=comments) + return result + except Exception as e: + return error_response("Could not update post", 400) + finally: + conn.close() + +# Delete Post +@app.delete("/posts/{postId}", status_code=204) +def delete_post(postId: str): + conn = get_db() + c = conn.cursor() + post = c.execute("SELECT * FROM posts WHERE id=?", (postId,)).fetchone() + if not post: + conn.close() + return error_response("Post not found", 404) + c.execute("DELETE FROM posts WHERE id=?", (postId,)) + c.execute("DELETE FROM comments WHERE postId=?", (postId,)) + c.execute("DELETE FROM likes WHERE postId=?", (postId,)) + conn.commit() + conn.close() + return Response(status_code=204) + +# List Comments for a Post +@app.get("/posts/{postId}/comments", response_model=List[Comment]) +def list_comments(postId: str): + conn = get_db() + c = conn.cursor() + comments = c.execute("SELECT * FROM comments WHERE postId=?", (postId,)).fetchall() + result = [Comment(**dict(comment)) for comment in comments] + conn.close() + return result + +# Create Comment +@app.post("/posts/{postId}/comments", response_model=Comment, status_code=201) +def create_comment(postId: str, data: CommentCreate): + conn = get_db() + c = conn.cursor() + comment_id = os.urandom(8).hex() + now = datetime.utcnow().isoformat() + try: + c.execute("INSERT INTO comments (id, postId, username, content, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)", + (comment_id, postId, data.username, data.content, now, now)) + conn.commit() + comment = Comment(id=comment_id, postId=postId, username=data.username, content=data.content, createdAt=now, updatedAt=now) + return comment + except Exception as e: + return error_response("Could not create comment", 400) + finally: + conn.close() + +# Get Specific Comment +@app.get("/posts/{postId}/comments/{commentId}", response_model=Comment) +def get_comment(postId: str, commentId: str): + conn = get_db() + c = conn.cursor() + comment = c.execute("SELECT * FROM comments WHERE id=? AND postId=?", (commentId, postId)).fetchone() + if not comment: + conn.close() + return error_response("Comment not found", 404) + result = Comment(**dict(comment)) + conn.close() + return result + +# Update Comment +@app.patch("/posts/{postId}/comments/{commentId}", response_model=Comment) +def update_comment(postId: str, commentId: str, data: CommentUpdate): + conn = get_db() + c = conn.cursor() + comment = c.execute("SELECT * FROM comments WHERE id=? AND postId=?", (commentId, postId)).fetchone() + if not comment: + conn.close() + return error_response("Comment not found", 404) + now = datetime.utcnow().isoformat() + try: + c.execute("UPDATE comments SET username=?, content=?, updatedAt=? WHERE id=? AND postId=?", + (data.username, data.content, now, commentId, postId)) + conn.commit() + result = Comment(id=commentId, postId=postId, username=data.username, content=data.content, createdAt=comment["createdAt"], updatedAt=now) + return result + except Exception as e: + return error_response("Could not update comment", 400) + finally: + conn.close() + +# Delete Comment +@app.delete("/posts/{postId}/comments/{commentId}", status_code=204) +def delete_comment(postId: str, commentId: str): + conn = get_db() + c = conn.cursor() + comment = c.execute("SELECT * FROM comments WHERE id=? AND postId=?", (commentId, postId)).fetchone() + if not comment: + conn.close() + return error_response("Comment not found", 404) + c.execute("DELETE FROM comments WHERE id=? AND postId=?", (commentId, postId)) + conn.commit() + conn.close() + return Response(status_code=204) + +# Like a Post +@app.post("/posts/{postId}/likes", status_code=201) +def like_post(postId: str, data: LikeCreate): + conn = get_db() + c = conn.cursor() + post = c.execute("SELECT * FROM posts WHERE id=?", (postId,)).fetchone() + if not post: + conn.close() + return error_response("Post not found", 404) + try: + c.execute("INSERT INTO likes (postId, username) VALUES (?, ?)", (postId, data.username)) + conn.commit() + return Response(status_code=201) + except Exception as e: + return error_response("Could not like post", 400) + finally: + conn.close() + +# Unlike a Post +@app.delete("/posts/{postId}/likes", status_code=204) +def unlike_post(postId: str, data: LikeDelete): + conn = get_db() + c = conn.cursor() + post = c.execute("SELECT * FROM posts WHERE id=?", (postId,)).fetchone() + if not post: + conn.close() + return error_response("Post not found", 404) + c.execute("DELETE FROM likes WHERE postId=? AND username=?", (postId, data.username)) + conn.commit() + conn.close() + return Response(status_code=204) + +# --- Run the app on port 8000 --- +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/python/sns_api.db b/python/sns_api.db new file mode 100644 index 0000000000000000000000000000000000000000..e12e8f57a0031f443a19d8b861559ee6f195ed10 GIT binary patch literal 28672 zcmeI%Jxjwt0LJl)t*I!nPG&0HXhD?XELbIjSl?;|okDC+D7K9@sR&Nh$#3F!5huTl zgM-P{XaysJ=n(z~xl1lDm$qWk~aNb7`;mxM6<8F zP_?S57Yxo@UtKUFTF#sHMk$Rb3F=moy~*K@F&gY^4HZWVbT#pbNO%3zCmFWXh<_5I_I{1Q0*~0R#|0 I009JE0md`lfdBvi literal 0 HcmV?d00001