diff --git a/readme.md b/readme.md index c8af2e4..c3edb31 100644 --- a/readme.md +++ b/readme.md @@ -66,6 +66,7 @@ In addition to the required `AIRTABLE_API_KEY` and `AIRTABLE_API_BASE_ID` variab - `AIRTABLE_API_VERSION` - Defaults to `v0`. - `PROXY_PREFIX` - Use this if your Cloudflare worker's routes are prefixed by something before the Airtable resource name. For example, you may want to call `mycustomdomain.com/api/posts` instead of `mycustomdomain.com/posts`. In this example, you would add `api` as a prefix. - `ALLOWED_TARGETS` - Use this to lock down your Airtable API to specific resources and methods. For example, a stringified JSON object like this: `'[{"resource":"posts","method":"GET,PUT"},{"resource":"comments","method":"*"}]'` will allow `GET` and `PUT` requests on the `posts` resource and all request methods on the `comments` resource. Allows all methods for all resources by default. +- `PROXY_CACHE_TIME` - Defaults to `0`. The number of seconds set on the `Cache-Control` header to use Cloudflare's caching. ## Contributing diff --git a/src/handler.js b/src/handler.js index 89951b9..b5be735 100644 --- a/src/handler.js +++ b/src/handler.js @@ -31,7 +31,7 @@ export async function handleRequest(req) { }); } - return fetch(target.airtableRequestUrl, { + const response = await fetch(target.airtableRequestUrl, { headers: { Authorization: `Bearer ${config.airtableApiKey}`, "Content-type": "application/json" @@ -39,6 +39,20 @@ export async function handleRequest(req) { method: method, body: req.body }); + + const body = await response.body; + + const headers = new Headers(); + for (const kv of response.headers.entries()) { + headers.append(kv[0], kv[1]); + } + headers.set("Cache-Control", "max-age=" + config.cacheTime); + + return new Response(body, { + status: response.status, + statusText: response.statusText, + headers: headers + }); } catch (e) { console.error(e); diff --git a/webpack.config.js b/webpack.config.js index 4515416..d6ceddf 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -10,6 +10,7 @@ module.exports = { airtableBaseId: JSON.stringify(process.env.AIRTABLE_API_BASE_ID || ''), airtableApiVersion: JSON.stringify(process.env.AIRTABLE_API_VERSION || 'v0'), airtableApiKey: JSON.stringify(process.env.AIRTABLE_API_KEY || ''), + cacheTime: JSON.stringify(process.env.PROXY_CACHE_TIME || 0), prefix: JSON.stringify(process.env.PROXY_PREFIX || ''), allowedTargets: JSON.stringify(process.env.ALLOWED_TARGETS || '*'), },