Skip to content

Commit

Permalink
Create user API fix: return code for existing user
Browse files Browse the repository at this point in the history
  • Loading branch information
leechwort committed Dec 2, 2023
1 parent 271885d commit fbe8e4d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
8 changes: 5 additions & 3 deletions app/api/web_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,11 @@ def api_add_user():

user = User(user_data["name"], user_data["key"], user_data.get("slack_id"))

user.save()

return jsonify({"message": "User added successfully"})
number_of_new_user_added = user.save()
if number_of_new_user_added == 1:
return jsonify({"message": "User added successfully"}), 201
if number_of_new_user_added == 0:
return jsonify({"message": "User already exists"}), 303


@web_api.route("/api/users/<user_key>", methods=["DELETE"])
Expand Down
7 changes: 6 additions & 1 deletion app/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,17 @@ def get_by_key(cls, key):
return None

def save(self):
"""
Returns number of new user added
"""
# Connect to the database
conn = sqlite3.connect(app.config["DATABASE_URI"])
cursor = conn.cursor()

# Check if user already exists
cursor.execute("SELECT * FROM users WHERE key = ?", (self.key,))
existing_user = cursor.fetchone()

number_of_new_user = 0
if existing_user:
# Update existing user data
cursor.execute(
Expand All @@ -39,10 +42,12 @@ def save(self):
"INSERT INTO users (name, key, slack_id) VALUES (?, ?, ?)",
(self.name, self.key, self.slack_id),
)
number_of_new_user = 1
conn.commit()

# Close the connection
conn.close()
return number_of_new_user

def delete(self):
# Connect to the database
Expand Down

0 comments on commit fbe8e4d

Please sign in to comment.