Skip to content

Instantly share code, notes, and snippets.

@nyancodeid
Created March 11, 2020 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyancodeid/03a24d32cb4e25f018e446a2cf9443e2 to your computer and use it in GitHub Desktop.
Save nyancodeid/03a24d32cb4e25f018e446a2cf9443e2 to your computer and use it in GitHub Desktop.
QR Code API with Cloudflare Worker
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