diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..287ef6d --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,29 @@ +name: Build + +on: + push: + branches: + - main + pull_request: + branches: + - main + repository_dispatch: + inputs: + environment: + description: 'Choose an environment to deploy to: ' + required: true + default: 'prod' + +jobs: + deploy: + runs-on: ubuntu-latest + name: Deploy + steps: + - uses: actions/checkout@master + - name: Publish app + uses: cloudflare/wrangler-action@1.3.0 + with: + apiToken: ${{ secrets.CF_API_TOKEN }} + environment: ${{ github.event.inputs.environment }} + env: + CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5d31b45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ + +node_modules + + +## OS Files +# Windows +Thumbs.db +ehthumbs.db +Desktop.ini +$RECYCLE.BIN/ + +# OSX +.DS_Store + +# env config +.env + +dist +worker diff --git a/README.md b/README.md new file mode 100644 index 0000000..03facaa --- /dev/null +++ b/README.md @@ -0,0 +1,128 @@ +--- +# getbarcode-workers +--- + +## [getbarcode.app](https://getbarcode.app) + +--- + +## Simple on-the-fly QR Code Generator using Cloudlfare Workers + +getbarcode-workers is a serverless, no-code QR code image generator. It generates and returns QR code images 'on-the-fly' in PNG, SVG, EPS or PDF format super-fast in 200+ edge locations, powered by Cloudflare Workers. + +Usage is as simple as making a HTTP GET request to the relevant URL. Source QR code images directly from our CDN in your web apps, or download results to do whatever you need. QR code images are generated on-the-fly on Cloudflare's highly scalable, globally distributed Cloudflare Workers service and cached on their global CDN. + +Need to embed a QR code in your app? Just source your image URL from our CDN. + +https://getbarcode.app/qr/png/123456.png + +Returns.. + +![Scan me](https://getbarcode.app/qr/png/123456.png) + +Use our free hosted service at https://getbarcode.app - or deploy it yourself at the click of a button: + +[![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/jontybrook/getbarcode-workers) + +Features: + +- **100% Free** - Free unlimited usage, no strings attached. +- **Scalable** - This service operates on Cloudflare Workers. Our code runs globally, providing exceptional performance, reliability, and scale. +- **Fast** - Your QR code images are generated super fast on-the-fly at a datacenter location nearest to your users. +- **Global CDN** - Results are globally cached on Cloudflare's CDN for sub-millisecond TTFB responses and massive scalability. +- **Multiple File Formats** - Supports SVG, PNG, PDF and EPS image formats. +- **Vector Formats** - Use SVG or EPS formats in order to produce sharp images at any size. + +## Quickstart + +Usage couldn't be simpler. Just construct your source URL with the format you want your image to be and the payload you want the resulting QR code to parse to when scanned. URLs follow this format: + + https://getbarcode.app/qr/[image_type]/[qr_payload][optional_suffix] + +Here's a simple HTML example sourcing a PNG QR directly from our CDN: + + QR Code + +The result: +![Example QR Code](https://getbarcode.app/qr/png/ThatWasEasy.png) + +### Examples + +To get a QR code image in SVG format which parses to `123456` when scanned using any QR code scanner, use any of the following URLs: + +With suffix: + +> `https://getbarcode.app/qr/svg/123456.svg` + +Without suffix: + +> `https://getbarcode.app/qr/png/123456` + +Using query parameters: + +> `https://getbarcode.app/qr/svg/my-svg.svg?text=123456` + +Or for the same in PNG format: + +> `https://getbarcode.app/qr/png/123456.png` + +Or PDF format: + +> `https://getbarcode.app/qr/pdf/123456.pdf` + +## QR Code Endpoints - /qr/\*\* + +You can use this endpoint in the following ways: + +#### GET `/qr/[format]/[payload]` + +Include your payload at the end of the URL. + +> Example: `https://getbarcode.app/qr/png/123456.png` will return a PNG image that parses to `123456` when scanned. + +> NOTE: This works even if you include "/" characters in your payload, for example `https://getbarcode.app/qr/png/MYCODE/12/456789` will parse to `MYCODE/12/456789`. The same applies if you include a suffix. + +#### GET `/qr/[format]/[payload].[file_extension]` + +Optionally include a file extension suffix (eg .png) in your request URL. This will be stripped from the QR payload automatically. This is useful for use cases such as caching or downloading where you want the file extension. + +> NOTE: As the file extension is stripped from the payload during generation, it is possible to generate a file with an invalid extension for it's MIME type. For example, `https://getbarcode.app/qr/png/thisisnotapdf.pdf` will generate a PNG file with a .pdf file extension. You probably don't want to do that. + +#### GET `/qr/[format]/[file_name][file_suffix]?text=[payload]` + +Use URL **query parameter** `text` to specify the QR code payload. In this case, the filename is ignored. This is useful if you want your file name to be different from the QR payload. + +## Good to know + +- Our responses include the correct MIME type in the `Content-Type` HTTP header. This is particularly important for caching efficiently via CDNs. These are: + +| File Type | MIME Type | +| --------- | --------------- | +| SVG | image/svg+xml | +| PNG | image/png | +| PDF | application/pdf | +| EPS | image/eps | + +- Whilst output is generated on-the-fly, caching of the result is encouraged and we cache all results in our CDN indefinitely to minimise repeat computation. + +- Not keen on relying on a third-party service like https://getbarcode.app? We get it, and encourage you to deploy this project on your own domain using Cloudflare Workers in less than 5 minutes! Just click the magic button: + +[![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/jontybrook/getbarcode-workers) + +## Roadmap + +Contributions / pull requests are welcomed. + +- [ ] Generate other types of barcode (CODE-128, DataMatrix, etc) +- [ ] Custom image dimensions for PNG outputs. +- [ ] Advanced styling (colour, branding, etc). + +## License + +Copyright 2021 Jonty Brook + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/index.js b/index.js new file mode 100644 index 0000000..732ec45 --- /dev/null +++ b/index.js @@ -0,0 +1,63 @@ +import { Router } from "itty-router"; +import qr from "qr-image"; + +// Create express-like router using itty-router +const router = Router(); + +// GET QR code +router.get("/qr/:format/:payload", async ({ params, query }) => { + let { format, payload } = params; + const { text } = query; // Optional query string text will take precidence over params payload + + let mimeType = ""; + let fileExtension = ""; + switch (format) { + case "svg": + mimeType = "image/svg+xml"; + fileExtension = ".svg"; + break; + case "eps": + mimeType = "image/eps"; + fileExtension = ".eps"; + break; + case "png": + mimeType = "image/png"; + fileExtension = ".png"; + break; + case "pdf": + mimeType = "application/pdf"; + fileExtension = ".pdf"; + break; + } + + let qrPayload = payload; + if (text) { + // If payload text query parameter is included in request, use that and ignore the file/URI path + qrPayload = JSON.stringify(text); + } else { + // Otherwise we will take the payload for the QR code from the URL path + // If the requested URL includes a file suffix (eg .svg), remove it from the payload of the resulting QR code + if (qrPayload.endsWith(fileExtension)) { + qrPayload = qrPayload.substr(0, qrPayload.length - 4); + } + } + + // Log + console.log( + `Generating QR code in ${format} format with payload ${qrPayload}` + ); + + // Generate the QR code + const img = await qr.imageSync(qrPayload, { type: format }); + + // Return response with relevant Content-Type header + return new Response(img, { headers: { "Content-Type": mimeType } }); +}); + +// 404 for everything else +router.all("*", () => new Response("Route not found", { status: 404 })); + +// attach the router "handle" to the event handler +addEventListener("fetch", (event) => + event.respondWith(router.handle(event.request)) +); diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..88f7ab4 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,40 @@ +{ + "name": "getbarcode-workers", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "getbarcode-workers", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "itty-router": "^2.4.8", + "qr-image": "^3.2.0" + }, + "devDependencies": {} + }, + "node_modules/itty-router": { + "version": "2.4.8", + "resolved": "https://registry.npmjs.org/itty-router/-/itty-router-2.4.8.tgz", + "integrity": "sha512-VpAHeAN+/ABLqT/zEnwMomNCDh8eRrs06C8HRR8OxjVwGhXtvzoJbggjUnjAeNGxqjV4w7pp87Iu8jzEpr92fg==" + }, + "node_modules/qr-image": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/qr-image/-/qr-image-3.2.0.tgz", + "integrity": "sha1-n6gpW+rlDEoUnPn5CaHbRkqGcug=" + } + }, + "dependencies": { + "itty-router": { + "version": "2.4.8", + "resolved": "https://registry.npmjs.org/itty-router/-/itty-router-2.4.8.tgz", + "integrity": "sha512-VpAHeAN+/ABLqT/zEnwMomNCDh8eRrs06C8HRR8OxjVwGhXtvzoJbggjUnjAeNGxqjV4w7pp87Iu8jzEpr92fg==" + }, + "qr-image": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/qr-image/-/qr-image-3.2.0.tgz", + "integrity": "sha1-n6gpW+rlDEoUnPn5CaHbRkqGcug=" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..6ff79a9 --- /dev/null +++ b/package.json @@ -0,0 +1,30 @@ +{ + "private": false, + "name": "getbarcode-workers", + "version": "1.0.0", + "description": "Generate QR code images on-the-fly simply by requesting a URL, using serverless Cloudflare Workers", + "author": "Jonty Brook (https://jonty.app)", + "license": "MIT", + "keywords": [ + "qrcode", + "qr", + "barcode", + "cloudflare workers", + "serverless" + ], + "repository": { + "type": "git", + "url": "git://github.com/jontybrook/getbarcode-workers" + }, + "main": "index.js", + "scripts": { + "dev": "nuxi dev", + "build": "nuxi build", + "start": "node .output/server/index.mjs" + }, + "devDependencies": {}, + "dependencies": { + "qr-image": "^3.2.0", + "itty-router": "^2.4.8" + } +} diff --git a/wrangler.toml b/wrangler.toml new file mode 100644 index 0000000..3371bc7 --- /dev/null +++ b/wrangler.toml @@ -0,0 +1,7 @@ +name = "getbarcode-workers" +type = "webpack" +workers_dev = true +route = "" +zone_id = "9691c03870184fd7f28508f6cb39314d" +account_id = "42fc4977c90b94558000e7d89df12599" +compatibility_date = "2022-01-09"