I need to integrate my worker code with durable objects (the variable name is MY_DURABLE_OBJECT_CLASS, and the corresponding class name is AuthClass) for secondary development. The specific development requirements are:
-
After handling the preflight code, add a function to replace the authorization header, that is, when the client authorization header Authorization value is Bearer sk-kkkk111122223333, use a polling algorithm to replace the following keys in order:
Bearer sk-1xxxxxxxxx
Bearer sk-2bbbbbbbbbb
Bearer sk-3wwwwwwwwww
Bearer sk-4eeeeeeeeee
Bearer sk-5rrrrrrrrrr -
When the client authorization header Authorization value is not Bearer sk-kkkk111122223333, return a 401 error reminder: The API key you entered is incorrect, please re-enter.
Here is my worker code:
addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})
/**
- Respond to the request
-
@param {Request} request
/
async function handleRequest(request) {
// Modify request url to the target url
let url = new URL(request.url)
url.hostname = "api.***.com"
// Create a new request with the modified url
let newRequest = new Request(url, request)
// Add CORS headers to the request
let corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS",
"Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers"),
"Access-Control-Max-Age": "1728000"
}
// Handle preflight requests
if (request.method === "OPTIONS") {
return new Response(null, {
headers: corsHeaders
})
}
// Fetch the response from the target url
let response = await fetch(newRequest)
// Clone the response so we can modify the headers
let modifiedResponse = new Response(response.body, response)
// Add CORS headers to the response
for (let header in corsHeaders) {
modifiedResponse.headers.set(header, corsHeaders[header])
}
// Return the modified response
return modifiedResponse
}
Please understand my requirements and provide your quote.