Skip to content

Commit

Permalink
examples: add "cors" demo
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeed committed Apr 1, 2021
1 parent c2e83e7 commit 13c27bf
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
9 changes: 9 additions & 0 deletions examples/workers/cors/cfw.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "worktop-demo-cors",
"zoneid": "<YOUR ZONE ID>",
"profile": "personal",
"entry": "index.ts",
"routes": [
"<YOUR DOMAIN>/*"
]
}
49 changes: 49 additions & 0 deletions examples/workers/cors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Router, listen } from 'worktop';
import * as CORS from 'worktop/cors';

const API = new Router();

// TODO: Replace this with persistent layer
// Example – KV, Durable Object, or third-party
let counter = 0;

/**
* Handles `OPTIONS` requests using the same settings.
* NOTE: Call `CORS.preflight` per-route for inidivual settings.
*/
API.prepare = CORS.preflight({
origin: '*', // allow any `Origin` to connect
headers: ['Cache-Control', 'Content-Type', 'X-Count'],
methods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE'],
});

API.add('GET', '/', (req, res) => {
res.setHeader('X-Count', counter);
res.send(200, counter);
});

API.add('POST', '/', (req, res) => {
counter += 1;
res.setHeader('X-Count', counter);
res.send(200, counter);
});

API.add('PUT', '/', async (req, res) => {
try {
var next = Number(await req.body<string|number>());
if (next * 0 !== 0) return res.send(400, 'Invalid number!');
} catch (err) {
return res.send(400, 'Error parsing request');
}
counter = next;
res.setHeader('X-Count', counter);
res.send(200, counter);
});

API.add('DELETE', '/', (req, res) => {
counter -= 1;
res.setHeader('X-Count', counter);
res.send(200, counter);
});

listen(API.run);
14 changes: 14 additions & 0 deletions examples/workers/cors/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Example: CORS

> [View in Playground](https://cloudflareworkers.com/#955c634d65e1ebcb97be610f087be973:https://tutorial.cloudflareworkers.com/)
Configures [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) headers for multiple endpoints in this example:

* `GET /` – displays the current `counter` value
* `POST /` – increment the `counter` & return its new value
* `PUT /` – set the `counter` value (via request body) & return its new value
* `DELETE /` - decrement the `counter` & return its new value

## License

MIT

0 comments on commit 13c27bf

Please sign in to comment.