Skip to content

Commit

Permalink
Add decorator for ensuring payload config are set
Browse files Browse the repository at this point in the history
  • Loading branch information
m453h committed Dec 12, 2024
1 parent 460ad21 commit c7f9cca
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
33 changes: 33 additions & 0 deletions server/util/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,36 @@ def wrapper(*args, **kwargs):

def safely_read_arg(arg_name, default=None):
return request.args[arg_name] if arg_name in request.args else default


def api_require_payload_config(config):
"""
Validates Payload API configuration before executing a controller method.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Check if config is passed and is a dictionary
if not config:
errorMessage = "No configuration provided"
logger.error(errorMessage)
return json_error_response(errorMessage)

base_url = config.get("PAYLOAD_API_URL")
api_key = config.get("PAYLOAD_API_KEY")

if not base_url:
errorMessage = "Missing PAYLOAD_API_URL in configuration"
logger.error(errorMessage)
return json_error_response(errorMessage)

if not api_key:
errorMessage = "Missing PAYLOAD_API_KEY in configuration"
logger.error(errorMessage)
return json_error_response(errorMessage)

return func(*args, **kwargs)

return wrapper

return decorator
11 changes: 4 additions & 7 deletions server/views/cms/cms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,15 @@
import html

from server import app
from server.util.request import api_error_handler
from server.util.request import api_error_handler, api_require_payload_config

logger = logging.getLogger(__name__)
BASE_URL = app.config['PAYLOAD_API_URL']
API_KEY = app.config['PAYLOAD_API_KEY']

if not BASE_URL:
logger.error("Missing PAYLOAD_API_URL")

if not API_KEY:
logger.error("Missing PAYLOAD_API_KEY")

@app.route('/api/cms/pages', methods=['GET'])
@api_error_handler
@api_require_payload_config(app.config)
def api_fetch_page_content():
application_name = html.escape(request.headers.get('cs-app') or '')
url = f"{BASE_URL}/{application_name}-pages"
Expand All @@ -36,6 +31,7 @@ def api_fetch_page_content():

@app.route('/api/cms/collections', methods=['GET'])
@api_error_handler
@api_require_payload_config(app.config)
def api_fetch_collections():
collection = html.escape(request.args.get('collection'))
url = f"{BASE_URL}/{collection}"
Expand All @@ -55,6 +51,7 @@ def api_fetch_collections():

@app.route('/api/cms/globals', methods=['GET'])
@api_error_handler
@api_require_payload_config(app.config)
def api_fetch_globals():
application_name = html.escape(request.headers.get('cs-app'))
url = f"{BASE_URL}/globals/settings-{application_name}-site"
Expand Down

0 comments on commit c7f9cca

Please sign in to comment.