Skip to content

Commit

Permalink
Implement new_customer API.
Browse files Browse the repository at this point in the history
  • Loading branch information
David Griffin committed Dec 16, 2024
1 parent a9514c8 commit 922e294
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 18 deletions.
32 changes: 17 additions & 15 deletions ecommerce_app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,23 @@

@app.errorhandler(FaunaError)
def handle_fauna_exception(exc: FaunaError):
err_dict = {'http_status': exc.status_code, 'code': exc.code, 'message': exc.message}
if exc.code == 'document_not_found':
return jsonify({"message": f"Document not found at {request.path}", "status_code": 404}), 404
if hasattr(exc, 'summary'):
err_dict['summary'] = exc.summary
constraint_failures = []
if exc.constraint_failures:
for cf in exc.constraint_failures:
constraint_failures.append({'name': cf.name, 'message': cf.message, 'paths': cf.paths })
if constraint_failures:
err_dict['constraint_failures'] = constraint_failures
if exc.abort:
return jsonify({'message': exc.abort, 'status_code': exc.status_code}), exc.status_code
err_dict = {'http_status': exc.status_code, 'code': exc.code, 'message': exc.message}
if exc.code == 'document_not_found':
return jsonify({"message": f"Document not found at {request.path}", "status_code": 404}), 404
if hasattr(exc, 'summary'):
err_dict['summary'] = exc.summary
if exc.constraint_failures:
constraint_failures = []
for cf in exc.constraint_failures:
failure = {'message': cf.message, 'paths': cf.paths }
if cf.name:
failure['name'] = cf.name
constraint_failures.append(failure)
return jsonify(constraint_failures), 409
if exc.abort:
return jsonify({'message': exc.abort, 'status_code': exc.status_code}), exc.status_code

return jsonify(err_dict), exc.status_code
return jsonify(err_dict), exc.status_code

if __name__ == '__main__':
app.run(debug=True)
app.run(debug=True)
22 changes: 21 additions & 1 deletion ecommerce_app/customer_controller.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,34 @@
import dataclasses

from flask import jsonify, request
from fauna import fql
from fauna.client import Client
from fauna.errors import FaunaException
from fauna.encoding import QuerySuccess
import urllib.parse

from ecommerce_app.models.customer import Address, to_customer

# Initialize Fauna client
client = Client(typecheck=False)


def create_customer():
customer_data = request.get_json()
required = set(('name', 'email', 'address'))
difference = required - set(customer_data.keys())
if difference:
return jsonify({'message': f'Missing required field(s) {difference}'}), 400
try:
Address(**customer_data['address'])
except TypeError:
diff = set([field.name for field in dataclasses.fields(Address)]) - set(customer_data['address'].keys())
return jsonify({'message': f'Missing required field(s) {diff}'})
success = client.query(fql('let customer = Customer.create(${new_customer})\n${to_customer}',
new_customer=customer_data, to_customer=to_customer()))
return jsonify(success.data), 201


def add_item_to_cart(customer_id):
# Extract product name and quantity from the request body
data = request.get_json()
Expand Down Expand Up @@ -58,7 +79,6 @@ def add_item_to_cart(customer_id):

# Execute the query
res: QuerySuccess = client.query(query)
print(res.data)

# Return the updated cart as JSON
return jsonify(res.data), 200
Expand Down
8 changes: 6 additions & 2 deletions ecommerce_app/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from fauna.errors import AbortError
from flask import Blueprint, jsonify, request, Response

from ecommerce_app.customer_controller import add_item_to_cart, get_or_create_cart
from ecommerce_app.customer_controller import add_item_to_cart, get_or_create_cart, create_customer
from ecommerce_app.models.customer import Customer, to_customer
from ecommerce_app.models.order import Order, to_order
from ecommerce_app.models.product import Product, to_product
Expand Down Expand Up @@ -88,12 +88,16 @@ def order_by_id(identity):


@orders.route('/orders/<identity>', methods=['PATCH'])
def update_order_by_id(identity):
def update_order_by_id(identity: str):
"""Update an orders status, and optionally the payment method.
The valid status transitions are defined in collections.fsl.
"""
return update_order(identity)

@customers.route('/customers', methods=['POST'])
def new_customer():
return create_customer()


@customers.route('/customers/<identity>/cart', methods=['POST'])
def create_or_get_cart(identity: str):
Expand Down

0 comments on commit 922e294

Please sign in to comment.