[WIP] An easy-way to build REST API in Cloudflare Workers
Build production-ready Cloudflare Workers apps.
You can build fast and scalable API server or web apps that runs on Cloudflare Workers with Worter in no time ๐ฅ.
TODO: Build site with link to this markdown, the site should be deployed on cloudflare workers.
Add to existing project:
npm i worter --save-exact
or start new Worter project:
$ wrangler generate my-app https://github.com/pyk/worter-template
$ cd my-app/
$ npm install
Start the development server using the following command:
$ wrangler dev
And you are ready to go! ๐
Continue read the guide below to learn more about the Worter.
import { Worter } from "worter";
const app = new Worter();
app.get("/", (request, response) => {
return response.json({ message: "Hello from Worter ๐บ!" });
});
addEventListener("fetch", (event) => {
event.respondWith(app.serve(event.request));
});
Run the app on your local machine with the following command:
$ wrangler dev
The wrangler
starts a server and listens on port 8787 for connections. The app
responds with the following JSON formatted string:
{
"message": "Hello from Worter ๐บ!"
}
for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.
Next, let's talk about the basic routing mechanism in Worter apps.
Routing refers to determining how an application responds to a request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
Each route can have one handler function, which are executed when the route is matched.
In Worter, route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Where:
app
is an instance of Worter.METHOD
is an HTTP request method, in lowercase. For example app.get
,app.post
and so on.PATH
is a specified path to handle.HANDLER
is the function executed when the route is matched.It is highly-inpired by express.js.
The following examples illustrate defining simple routes.
Respond with Hi!
on the homepage:
app.get("/", (request, response) => {
return response.text("Hi!");
});
Respond to POST
request on the root route (/
), the applicationโs home page:
app.post("/", (request, response) => {
return response.text("POST request accepted");
});
Respond to a PUT
request to the /product
route:
app.put("/product", (request, response) => {
return response.text("PUT request accepted");
});
Respond to a DELETE
request to the /product
route:
app.delete("/product", (request, response) => {
return response.text("DELETE request accepted");
});
For more details about routing, see the routing guide.