From d35821b915f4f79cc9d64bc7664786741f1b474f Mon Sep 17 00:00:00 2001 From: nzambello Date: Mon, 25 Mar 2024 11:17:19 +0200 Subject: [PATCH] first commit --- .dockerignore | 4 + .editorConfig | 12 +++ .gitea/workflows/publish.yml | 63 +++++++++++++ .gitignore | 175 +++++++++++++++++++++++++++++++++++ Dockerfile | 6 ++ README.md | 67 ++++++++++++++ bun.lockb | Bin 0 -> 15908 bytes docker-compose.yml | 10 ++ index.ts | 99 ++++++++++++++++++++ package.json | 17 ++++ tsconfig.json | 7 ++ 11 files changed, 460 insertions(+) create mode 100644 .dockerignore create mode 100644 .editorConfig create mode 100644 .gitea/workflows/publish.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100755 bun.lockb create mode 100644 docker-compose.yml create mode 100644 index.ts create mode 100644 package.json create mode 100644 tsconfig.json diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..75ab70a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +node_modules +docs +data +.gitea diff --git a/.editorConfig b/.editorConfig new file mode 100644 index 0000000..afbd9e3 --- /dev/null +++ b/.editorConfig @@ -0,0 +1,12 @@ +[*] +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +charset = utf-8 + +[{*.css,*.scss,*.less,*.overrides,*.variables}] +indent_size = 4 + +[{*.js,*.jsx,*.json,*.ts,*.tsx}] +indent_size = 2 \ No newline at end of file diff --git a/.gitea/workflows/publish.yml b/.gitea/workflows/publish.yml new file mode 100644 index 0000000..2d9b43b --- /dev/null +++ b/.gitea/workflows/publish.yml @@ -0,0 +1,63 @@ +name: Docker CI + +on: + push: + branches: + - main + +env: + node-version: 20.x + +jobs: + release: + runs-on: ubuntu-latest + container: + image: catthehacker/ubuntu:act-latest + env: + DOCKER_ORG: nzambello + DOCKER_LATEST: nightly + permissions: + contents: read + packages: write + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Docker meta + id: meta + uses: docker/metadata-action@v4 + with: + images: | + git.nzambello.dev/nzambello/resize-img-api + labels: | + org.label-schema.docker.cmd=docker run -d -p 8787:8787 git.nzambello.dev/nzambello/resize-img-api:latest + flavor: latest=false + tags: | + type=ref,event=branch + type=sha + type=raw,value=latest,enable={{is_default_branch}} + + - name: Login to Container Registry + uses: docker/login-action@v2 + with: + registry: git.nzambello.dev + username: ${{ gitea.repository_owner }} + password: ${{ secrets.ACTIONS_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + - name: Build and push + uses: docker/build-push-action@v4 + with: + context: . + file: ./Dockerfile + platforms: linux/amd64,linux/arm64 + push: ${{ gitea.event_name != 'pull_request' }} + tags: | + git.nzambello.dev/nzambello/resize-img-api:latest + labels: $${{ steps.meta.outputs.labels }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9b1ee42 --- /dev/null +++ b/.gitignore @@ -0,0 +1,175 @@ +# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore + +# Logs + +logs +_.log +npm-debug.log_ +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Caches + +.cache + +# Diagnostic reports (https://nodejs.org/api/report.html) + +report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json + +# Runtime data + +pids +_.pid +_.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover + +lib-cov + +# Coverage directory used by tools like istanbul + +coverage +*.lcov + +# nyc test coverage + +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) + +.grunt + +# Bower dependency directory (https://bower.io/) + +bower_components + +# node-waf configuration + +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) + +build/Release + +# Dependency directories + +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) + +web_modules/ + +# TypeScript cache + +*.tsbuildinfo + +# Optional npm cache directory + +.npm + +# Optional eslint cache + +.eslintcache + +# Optional stylelint cache + +.stylelintcache + +# Microbundle cache + +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history + +.node_repl_history + +# Output of 'npm pack' + +*.tgz + +# Yarn Integrity file + +.yarn-integrity + +# dotenv environment variable files + +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) + +.parcel-cache + +# Next.js build output + +.next +out + +# Nuxt.js build / generate output + +.nuxt +dist + +# Gatsby files + +# Comment in the public line in if your project uses Gatsby and not Next.js + +# https://nextjs.org/blog/next-9-1#public-directory-support + +# public + +# vuepress build output + +.vuepress/dist + +# vuepress v2.x temp and cache directory + +.temp + +# Docusaurus cache and generated files + +.docusaurus + +# Serverless directories + +.serverless/ + +# FuseBox cache + +.fusebox/ + +# DynamoDB Local files + +.dynamodb/ + +# TernJS port file + +.tern-port + +# Stores VSCode versions used for testing VSCode extensions + +.vscode-test + +# yarn v2 + +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +# IntelliJ based IDEs +.idea + +# Finder (MacOS) folder config +.DS_Store diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6b247cd --- /dev/null +++ b/Dockerfile @@ -0,0 +1,6 @@ +FROM oven/bun:alpine +WORKDIR /app +COPY . . +RUN bun install --production --frozen-lockfile +CMD ["bun", "start"] +EXPOSE 8787 diff --git a/README.md b/README.md new file mode 100644 index 0000000..5b840bd --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# resize-img-api + +The structure of the API path is: + +``` +/api/imgresize/:width/:height/:url +``` + +Where `:width` and `:height` can be numbers in pixels or `auto`. + +The `:url` is the URL of the image to be resized and should be URL encoded, which can be done in JS with `encodeURIComponent`(). See [MDN ref](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent). + +Example encoded URL for [https://memori.ai/logo.png](https://memori.ai/logo.png): + +``` +https%3A%2F%2Fmemori.ai%2Flogo.png +``` + +Then call the API as, for example: + +``` +/api/imgresize/200/200/https%3A%2F%2Fmemori.ai%2Flogo.png +``` + +You can also specify a format using the querystring `?format=` and indicating one of the following: avif, gif, heif, jpeg, jpg, jp2, pdf, png, svg, tiff, webp. + +## Docker + +To build the Docker image: + +```bash +docker build -t resize-img-api . +``` + +To run the Docker container: + +```bash +docker run -p 8787:8787 resize-img-api +``` + +Using the published image: + +```bash +docker run -p 8787:8787 git.nzambello.dev/nzambello/resize-img-api:latest +``` + +## Development + +To install dependencies: + +```bash +bun install +``` + +To run: + +```bash +bun start +``` + +Or in development mode with hot reloading: + +```bash +bun dev +``` + +This project was created using `bun init` in bun v1.0.26. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime. diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000000000000000000000000000000000000..11294b041737cd549e0a37fd48f6505fb414b61d GIT binary patch literal 15908 zcmeHO2{_c-`ycL96N#j>sUekQ#xf}+aZBBBg|vvuU@&4ZGxpT9+(^4Np@mSz#An^M1~I-m`qqIrC0`ZNo5; z(9nx7FyslsnOAs$kD1O_eU_7&E`CdWiw3%y0LLneMDWfqy;S!Q21*mjq8cibd=L$n0r4Q9;K)M_7 zZouily8!R|1C6E%Tr3LYdqKGx1sbgfq-OwU0>28p7jR49I>7URBMuXIAK=@8cL%Nr zyf5%XS-KLiFg*v-SpF=ev3w42E#OOm_X8dQ9PRN0t_fVk3kv56X|x#~X*BqgL~#QH z`64lG63CSy?HwE#3}TwA5{=dg(%HbVogaXsd<$^+lZ=CZD!~1N1;J1p+eGCL1|`Ie zl<^?osP_~&{7C?dDz|3&@MEhZ*2I-mY`eI;A?2NYgo2&(%QCf)EUUcvF;6z%J<+Xx z;Z6Ta{?_!)dFtx6V>g#)r)wU0+o$)tB~={N5^cKbmI~M0`%kBqukCENU(?gorALkH z5yyFdC=QyqKr#0EKL3^ZDSukMUt-gLPVt7Y11Hk=4O6emjH&T@)@i|x^q&M7W9nz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d zEb0}5v!WGk>iq*c6la;h=EUR+8glNXMl0#d#``nRySpRvzz626pd!eXUZYs=1aDL3lOz3;G|^` zjrw&Ui#lE6N*E{%V|jDE{abr;G?oGV#?LHjQ~rg;RJLOWJ=rG~wPF8)mfYqHH04t8 z-ht`$1#Rm54SE!Z`rzn|8q%b9umHBEVrc^Qim=sf#cT4#8WE*hFhtB@f8Pi!;0D1y zH7Eprm@10kM@I*?=FsK^0l9ew^e>z?5SuT86+y_2;*0!SF;lJ-V9BL$pnUO#Cv7C! z-`GS#F-4sT zTB)wFj7*y w-<$u%hR7EK82KcNI`)}TE}_n5((_m=UTHd10aQ~0fQCvZkMyMW|L_0*0kWgWC;$Ke literal 0 HcmV?d00001 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ff559ae --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,10 @@ +version: "3.8" + +services: + resize-image-api: + image: nzambello/resize-image-api:latest + build: + context: . + dockerfile: Dockerfile + ports: + - "8787:8787" diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..33840ab --- /dev/null +++ b/index.ts @@ -0,0 +1,99 @@ +import { Hono } from "hono"; +import { cors } from "hono/cors"; +import { etag } from "hono/etag"; +import { logger } from "hono/logger"; +import { prettyJSON } from "hono/pretty-json"; +import { html } from "hono/html"; +import sharp from "sharp"; + +const homepage = html` + + + + + + + + + Resize Images API + + + + + +
+

Resize images API

+ + +
+

The structure of the API path is:

+

/api/imgresize/:width/:height/:url

+

Where width and height can be numbers in pixels or auto.

+

The URL should be URL encoded, which can be done in JS with encodeURIComponent. See MDN ref.

+

Example for https://memori.ai/logo.png:

+

https%3A%2F%2Fmemori.ai%2Flogo.png

+

Then call the API as, for example:

+

/api/imgresize/200/200/https%3A%2F%2Fmemori.ai%2Flogo.png

+

You can also specify a format using the querystring ?format= and indicating one of the following: avif, gif, heif, jpeg, jpg, jp2, pdf, png, svg, tiff, webp.

+
+
+ + +`; + +const app = new Hono(); +app.use(prettyJSON()); +app.use(etag(), logger()); + +app.use("/api/*", cors()); + +app.get("/", (c) => { + return c.html(homepage); +}); + +app.get("/api/imgresize/:width/:height/:url", async (c) => { + const { width, height, url } = c.req.param(); + const format = c.req.query("format"); + + c.header("Cache-Control", "s-maxage=31536000, stale-while-revalidate"); + c.header("Content-Type", `image/jpeg`); + + const decodedUrl = decodeURIComponent(url as string); + + const readStream = await fetch(decodedUrl, { cache: "no-cache" }); + const input = Buffer.from(await readStream.arrayBuffer()); + + const w = width && width !== "auto" ? Number(width) : undefined; + const h = height && height !== "auto" ? Number(height) : undefined; + + const outputBuffer = await sharp(input) + // outputBuffer contains JPEG image data + // no wider and no higher than w and h pixels + // and no larger than the input image + .resize({ + width: w, + height: h, + fit: sharp.fit.inside, + withoutEnlargement: true, + }) + .toFormat( + format && sharp.format[format as keyof typeof sharp.format] !== undefined + ? sharp.format[format as keyof typeof sharp.format] + : sharp.format.jpeg + ) + .toBuffer(); + + c.status(200); + return c.body(outputBuffer); +}); + +export default { + port: Bun.env.PORT || 8787, + fetch: app.fetch, +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..72eafa7 --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "resize-img-api", + "scripts": { + "dev": "bun run --hot index.ts", + "start": "bun run index.ts" + }, + "dependencies": { + "hono": "^4.1.4", + "sharp": "^0.33.3" + }, + "devDependencies": { + "@types/bun": "latest" + }, + "peerDependencies": { + "typescript": "^5.0.0" + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..9136c14 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "strict": true, + "jsx": "react-jsx", + "jsxImportSource": "hono/jsx" + } +}