Last active
October 3, 2022 17:11
-
-
Save chientrm/b914859df8b548ce6011a130cb8471b2 to your computer and use it in GitHub Desktop.
Sample CF Worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const | |
_ = { | |
author : 'chientrm', | |
title : 'TODO list with CF Worker', | |
description : 'This project is done via quick edit only', | |
year : '2022', | |
keywords : 'cloudflare, worker, quick, edit', | |
license : 'MIT', | |
}, | |
_________________________CONSTANTS_____________________________=_, | |
_________________________CONSTANTS_STRINGS_____________________=_, | |
NOT_FOUND = 'Not found', | |
_________________________CONSTANTS_TYPES_______________________=_, | |
APP_JSON = { 'Content-Type': 'application/json' }, | |
TEXT_HTML = { 'Content-Type': 'text/html' }, | |
_________________________HELPERS_______________________________=_, | |
_________________________HELPERS_RESPONSES_____________________=_, | |
json = data => new Response( | |
JSON.stringify(data), | |
{ headers: APP_JSON }, | |
), | |
html = ({head, body}) => new Response( | |
`<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="viewport" content="width=device-width" /> | |
${head ?? ''} | |
</head> | |
<body> | |
${body ?? ''} | |
</body> | |
</html>`, | |
{ headers: TEXT_HTML } | |
), | |
not_found = _ => new Response( | |
JSON.stringify({ message: NOT_FOUND }), | |
{ status: 404, headers: APP_JSON } | |
), | |
_________________________HELPERS_UTILS_________________________=_, | |
pathname = req => new URL(req.url).pathname, | |
_________________________ROUTER________________________________=_, | |
routes = [ | |
{ | |
pattern: /\//g, | |
handle: _ => html({ body: 'Hello World' }) | |
}, | |
{ | |
pattern: /\/name/g, | |
handle: async req => | |
json({ name: await DRIVE.get('name') }), | |
}, | |
{ | |
pattern: /.*/g, | |
handle: not_found, | |
} | |
], | |
handle = async (req) => | |
routes.find(({ pattern }) => | |
pathname(req) | |
.match(pattern) | |
).handle(req), | |
_________________________END___________________________________=_; | |
addEventListener("fetch", (event) => | |
event.respondWith(handle(event.request)) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment