feat(infra): singular dockerfile with vite bundling

Using Vite as a bundler to allow easier builds, with shared library

Moved to a single dockerfile that takes an argument to specify which
service to use

moved some file around to faciliate bundling with vite

cried a lot
This commit is contained in:
Maieul BOYER 2025-07-30 21:27:56 +02:00 committed by Maix0
parent bdc4616106
commit 573af0bc4b
21 changed files with 1587 additions and 1062 deletions

View file

@ -1,18 +0,0 @@
# **************************************************************************** #
# #
# ::: :::::::: #
# Dockerfile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: maiboyer <maiboyer@student.42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2025/06/16 14:57:11 by maiboyer #+# #+# #
# Updated: 2025/07/29 13:53:21 by maiboyer ### ########.fr #
# #
# **************************************************************************** #
FROM trans_builder
# do extra stuff that is specific for this service here !
CMD ["node", "/src/icons/dist/run.js"]

View file

@ -9,12 +9,9 @@
"test": "test"
},
"scripts": {
"test": "npm run build:ts && tsc -p test/tsconfig.json && FASTIFY_AUTOLOAD_TYPESCRIPT=1 node --test --experimental-test-coverage --loader ts-node/esm test/**/*.ts",
"start": "npm run build:ts && fastify start -l info dist/app.js",
"build:ts": "tsc -d",
"watch:ts": "tsc -d -w",
"dev": "npm run build:ts && concurrently -k -p \"[{name}]\" -n \"TypeScript,App\" -c \"yellow.bold,cyan.bold\" \"npm:watch:ts\" \"npm:dev:start\"",
"dev:start": "fastify start --ignore-watch=.ts$ -w -l info -P dist/app.js"
"start": "npm run build && node dist/run.js",
"build": "vite build",
"build:prod": "vite build --outDir=/dist --minify=true --sourcemap=false"
},
"keywords": [],
"author": "",
@ -28,15 +25,13 @@
"fastify": "^5.0.0",
"fastify-cli": "^7.4.0",
"fastify-plugin": "^5.0.0",
"fastify-raw-body": "^5.0.0",
"raw-body": "^3.0.0",
"sharp": "^0.34.2"
},
"devDependencies": {
"@types/node": "^22.1.0",
"c8": "^10.1.2",
"concurrently": "^9.0.0",
"fastify-tsconfig": "^3.0.0",
"ts-node": "^10.4.0",
"typescript": "~5.8.2"
"rollup-plugin-node-externals": "^8.0.1",
"vite": "^7.0.6",
"vite-tsconfig-paths": "^5.1.4"
}
}

View file

@ -1,22 +1,12 @@
import * as path from 'node:path'
import AutoLoad, { AutoloadPluginOptions } from '@fastify/autoload'
import { FastifyPluginAsync } from 'fastify'
import { fileURLToPath } from 'node:url'
import fastifyFormBody from '@fastify/formbody'
import fastifyMultipart from '@fastify/multipart'
import { mkdir } from 'node:fs/promises'
import fp from 'fastify-plugin'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const plugins = import.meta.glob('./plugins/**/*.ts', { eager: true });
const routes = import.meta.glob('./routes/**/*.ts', { eager: true });
export type AppOptions = {
// Place your custom options for app below here.
} & Partial<AutoloadPluginOptions>
// Pass --options via CLI arguments in command to enable these options.
const options: AppOptions = {
}
// When using .decorate you have to specify added properties for Typescript
declare module 'fastify' {
@ -25,11 +15,17 @@ declare module 'fastify' {
}
}
const app: FastifyPluginAsync<AppOptions> = async (
const app: FastifyPluginAsync = async (
fastify,
opts
): Promise<void> => {
// Place here your custom code!
for (const plugin of Object.values(plugins)) {
void fastify.register(plugin, {});
}
for (const route of Object.values(routes)) {
void fastify.register(route, {});
}
//void fastify.register(MyPlugin, {})
void fastify.register(fastifyFormBody, {})
@ -43,30 +39,7 @@ const app: FastifyPluginAsync<AppOptions> = async (
await mkdir(fastify.image_store, { recursive: true })
}))
// Do not touch the following lines
// This loads all plugins defined in plugins
// those should be support plugins that are reused
// through your application
// eslint-disable-next-line no-void
void fastify.register(AutoLoad, {
dir: path.join(__dirname, 'plugins'),
options: opts,
forceESM: true
})
// This loads all plugins defined in routes
// define your routes in one of these
// eslint-disable-next-line no-void
void fastify.register(AutoLoad, {
dir: path.join(__dirname, 'routes'),
options: opts,
forceESM: true
})
}
export default app
export { app, options }
export { app }

View file

@ -1,29 +0,0 @@
# Routes Folder
Routes define the pathways within your application.
Fastify's structure supports the modular monolith approach, where your
application is organized into distinct, self-contained modules.
This facilitates easier scaling and future transition to a microservice architecture.
In the future you might want to independently deploy some of those.
In this folder you should define all the routes that define the endpoints
of your web application.
Each service is a [Fastify
plugin](https://fastify.dev/docs/latest/Reference/Plugins/), it is
encapsulated (it can have its own independent plugins) and it is
typically stored in a file; be careful to group your routes logically,
e.g. all `/users` routes in a `users.js` file. We have added
a `root.js` file for you with a '/' root added.
If a single file becomes too large, create a folder and add a `index.js` file there:
this file must be a Fastify plugin, and it will be loaded automatically
by the application. You can now add as many files as you want inside that folder.
In this way you can create complex routes within a single monolith,
and eventually extract them.
If you need to share functionality between routes, place that
functionality into the `plugins` folder, and share it via
[decorators](https://fastify.dev/docs/latest/Reference/Decorators/).
If you're a bit confused about using `async/await` to write routes, you would
better take a look at [Promise resolution](https://fastify.dev/docs/latest/Reference/Routes/#promise-resolution) for more details.

View file

@ -1,19 +1,23 @@
import { FastifyPluginAsync } from 'fastify'
import { join } from 'node:path'
import { open } from 'node:fs/promises'
import fastifyRawBody from 'fastify-raw-body'
import sharp from 'sharp'
import { newUUIDv7 } from '@shared/uuid'
import rawBody from 'raw-body'
const example: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
const route: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
// await fastify.register(authMethod, {});
// here we register plugins that will be active for the current fastify instance (aka everything in this function)
await fastify.register(fastifyRawBody, { encoding: false });
// we register a route handler for: `/<USERID_HERE>`
// it sets some configuration options, and set the actual function that will handle the request
fastify.post('/:userid', { config: { rawBody: true, encoding: false } }, async function(request, reply) {
fastify.addContentTypeParser('*', function(request, payload, done) {
done()
});
fastify.post('/:userid', async function(request, reply) {
let buffer = await rawBody(request.raw);
// this is how we get the `:userid` part of things
const userid: string | undefined = (request.params as any)['userid'];
if (userid === undefined) {
@ -22,14 +26,11 @@ const example: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
const image_store: string = fastify.getDecorator('image_store')
const image_path = join(image_store, userid)
//let raw_image_file = await open(image_path + ".raw", "w", 0o666)
//await raw_image_file.write(request.rawBody as Buffer);
//await raw_image_file.close()
try {
let img = sharp(request.rawBody as Buffer);
let img = sharp(buffer);
img.resize({
height: 512,
width: 512,
height: 128,
width: 128,
fit: 'fill',
})
const data = await img.png({ compressionLevel: 6 }).toBuffer()
@ -44,5 +45,5 @@ const example: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
})
}
export default example
export default route

View file

@ -4,7 +4,21 @@ import fastify, { FastifyInstance } from "fastify";
import app from './app.js'
const start = async () => {
const f: FastifyInstance = fastify({logger: true});
const envToLogger = {
development: {
transport: {
target: 'pino-pretty',
options: {
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname',
},
},
},
production: true,
test: false,
}
const f: FastifyInstance = fastify({ logger: envToLogger.development });
try {
await f.register(app, {});
await f.listen({ port: 80, host: '0.0.0.0' })

View file

@ -1,8 +1,5 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src"
},
"compilerOptions": {},
"include": ["src/**/*.ts"]
}

26
src/icons/vite.config.js Normal file
View file

@ -0,0 +1,26 @@
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
import nodeExternals from 'rollup-plugin-node-externals'
import path from 'node:path'
export default defineConfig({
root: __dirname, // service root
plugins: [tsconfigPaths(), nodeExternals()],
build: {
ssr: true,
outDir: 'dist',
emptyOutDir: true,
lib: {
entry: path.resolve(__dirname, 'src/run.ts'), // adjust main entry
formats: ['cjs'], // CommonJS for Node.js
fileName: () => 'index.js',
},
rollupOptions: {
external: [],
},
target: 'node24', // or whatever Node version you use
sourcemap: true,
minify: false, // for easier debugging
}
})