Created
March 11, 2020 02:17
-
-
Save nyancodeid/03a24d32cb4e25f018e446a2cf9443e2 to your computer and use it in GitHub Desktop.
QR Code API with Cloudflare 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
import { imageSync } from 'qr-image' | |
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
/** | |
* Respond with hello worker text | |
* @param {Request} request | |
*/ | |
async function handleRequest(request) { | |
if (request.method === 'GET') { | |
try { | |
const url = new URL(request.url) | |
const text = url.searchParams.get('text') | |
return generateQrCode({ text }) | |
} catch (err) { | |
return new Response('Internal Server Error', { | |
status: 500 | |
}) | |
} | |
} else { | |
return new Response('Method Not Allowed', { | |
status: 405 | |
}) | |
} | |
} | |
function generateQrCode({ | |
text | |
}) { | |
const image = imageSync(text || 'https://blog.nyandev.id') | |
return new Response(image, { | |
status: 200, | |
headers: { | |
'Content-Type': 'image/png', | |
'Cache-Control': 'public, max-age=31536000' | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment