Worker template to create an API with cloudflare worker and wrangler
You can use wrangler to generate a new Cloudflare Workers project based on this template by running the following command from your terminal:
wrangler generate myapp https://github.com/nikhiljohn10/api-worker-template
Before publishing your code you need to edit wrangler.toml
file and add your Cloudflare account_id
- more information about publishing your code can be found in the documentation.
Once you are ready, you can publish your code by running the following command:
wrangler publish
index.js
have the code const app = new App('/api/v1')
. This will set the base path to /api/v1
. This means, your base url will be example.com/api/v1
/user/:userId
matchs "https://example.com/api/v1/users/nikhiljohn10"
and respond with { userId: "nikhiljohn10"}
app.method_name(url_path, handler_method)
is the route loader method. method_name
can be connect, delete, head, options, patch, post, put, trace
, url_path
is a regular expression and handler_method
is executed by passing request and worker response object as arguments. So handler should be taking those parameters. Eg: (req, res) => res.json(req)
will send back the request object received as json.
Structure:
./index.js
: This is the entry point for the API
./api/app.js
: This file helpwith the logical routing and execution
./api/controllers.js
: This file contains methods that are attached to routes
./api/response.js
: This file have various response models
./api/routes.js
: This file contain and loads all the routes in to API
You can use controllers.js
and routes.js
to easily create an API.
If you are working directly on the system where wrangler is executed, then use wrangler publish
If you need the code to be auto published when you save a file in the working directory or you are executing inside a network directory, you will have to use the following.
Publish from remote storage and observe file changes
Usage: ./publisher [-h|-n|-s DIR]
Options:
-h|--help Displays this help
-n|--no-npm-install Publish without npm install
-s|--source-dir [DIR] Source directory name
-w|--wait [NUMBER] Waiting time in seconds (default: 2 seconds)
To deploy using serverless add a serverless.yml
file.