Key Components
1. corsHeaders
CORS and content-type headers to allow requests from the Striae app domain and support JSON payloads.
2. authenticate(request, env)
Checks if the incoming request contains a valid X-Custom-Auth-Key
header matching the secret in the environment (env.USER_DB_AUTH
).
Throws: Error if authentication fails.
3. handleGetUser(env, userUid)
Fetches user data from the KV store by UID.
-
Returns 404 if the user is not found.
-
Returns 200 and the user data if found.
4. handleAddUser(request, env, userUid)
Creates or updates a user record in the KV store:
-
If the user exists, updates fields and preserves the
cases
array. -
If the user does not exist, creates a new record with an empty
cases
array. -
Returns 201 for creation, 200 for update.
5. handleDeleteUser(env, userUid)
Deletes a user record from the KV store by UID.
- Returns 200 on success.
6. handleAddCases(request, env, userUid)
Adds new cases to a user's cases
array:
-
Prevents duplicate case numbers.
-
Updates the
updatedAt
timestamp. -
Returns 200 and the updated user data.
7. handleDeleteCases(request, env, userUid)
Removes specified case numbers from a user's cases
array:
-
Updates the
updatedAt
timestamp. -
Returns 200 and the updated user data.
8. fetch(request, env)
The main entry point for the worker. Handles HTTP requests for user and case management.
Request Handling:
-
OPTIONS:
Returns CORS headers for preflight requests. -
Authentication:
Rejects requests without a validX-Custom-Auth-Key
header. -
User Operations:
-
GET /:uid
: Get user data. -
PUT /:uid
: Create or update user data. -
DELETE /:uid
: Delete user data.
-
-
Case Operations:
-
PUT /:uid/cases
: Add cases to a user. -
DELETE /:uid/cases
: Remove cases from a user.
-
-
Default:
Returns a 405 error for unsupported methods.
Usage
This worker is intended to be deployed on Cloudflare and used as a backend for secure, authenticated user and case management, with CORS enabled for the main application domain.