项目作者: nikhiljohn10

项目描述 :
API Worker template to create cloudflare worker using wrangler
高级语言: JavaScript
项目地址: git://github.com/nikhiljohn10/api-worker-template.git
创建时间: 2020-05-08T13:00:22Z
项目社区:https://github.com/nikhiljohn10/api-worker-template

开源协议:MIT License

下载


API Worker Template

API Worker Template for Cloudflare Workers

wrangler
npm
node
ubuntu

Worker template to create an API with cloudflare worker and wrangler

Wrangler

You can use wrangler to generate a new Cloudflare Workers project based on this template by running the following command from your terminal:

  1. 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:

  1. wrangler publish

Routing

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.

How to manage API

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.

Publisher script

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.

  1. Publish from remote storage and observe file changes
  2. Usage: ./publisher [-h|-n|-s DIR]
  3. Options:
  4. -h|--help Displays this help
  5. -n|--no-npm-install Publish without npm install
  6. -s|--source-dir [DIR] Source directory name
  7. -w|--wait [NUMBER] Waiting time in seconds (default: 2 seconds)

Serverless

To deploy using serverless add a serverless.yml file.