nirkyy commited on
Commit
7f3a3f1
·
verified ·
1 Parent(s): 3caea19

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +1 -136
Dockerfile CHANGED
@@ -1,136 +1 @@
1
- # Gunakan image resmi Node.js versi LTS yang ringan
2
- FROM node:20-alpine
3
- # Install git jika diperlukan untuk instalasi package dari git, dan utilitas dasar
4
- RUN apk add --no-cache git
5
- # Buat direktori kerja di dalam container
6
- WORKDIR /app
7
- # Buat direktori api dan direktori publik untuk struktur awal
8
- RUN mkdir -p /app/api
9
- # Salin script server utama yang menggunakan konkatenasi biasa agar aman dari escape shell
10
- RUN cat << 'EOF' > server.js
11
- const express = require('express');
12
- const fs = require('fs');
13
- const path = require('path');
14
- const { execSync } = require('child_process');
15
- const app = express();
16
- const PORT = process.env.PORT || 7860;
17
- const API_DIR = path.join(__dirname, 'api');
18
- app.use(express.json());
19
- app.use(express.urlencoded({ extended: true }));
20
- // Fungsi sederhana untuk mendeteksi import/require dari sebuah file source code
21
- function extractDependencies(filePath) {
22
- const content = fs.readFileSync(filePath, 'utf8');
23
- const dependencies = new Set();
24
- // Regex untuk menangkap require('pkg') atau require("pkg")
25
- const requireRegex = /require\s*(\s*'"['"]\s*)/g;
26
- let match;
27
- while ((match = requireRegex.exec(content)) !== null) {
28
- const pkg = match[1];
29
- // Abaikan built-in modules Node.js atau relative path
30
- if (!pkg.startsWith('.') && !pkg.startsWith('/')) {
31
- const parts = pkg.split('/');
32
- // Gunakan konkatenasi string biasa untuk menghindari error escape
33
- const pkgName = pkg.startsWith('@') ? parts[0] + '/' + parts[1] : parts[0];
34
- dependencies.add(pkgName);
35
- }
36
- }
37
- // Regex untuk menangkap import ... from 'pkg' atau import 'pkg'
38
- const importRegex = /import\s+(?:[\w\s*{},]+from\s+)?'"['"]/g;
39
- while ((match = importRegex.exec(content)) !== null) {
40
- const pkg = match[1];
41
- if (!pkg.startsWith('.') && !pkg.startsWith('/')) {
42
- const parts = pkg.split('/');
43
- const pkgName = pkg.startsWith('@') ? parts[0] + '/' + parts[1] : parts[0];
44
- dependencies.add(pkgName);
45
- }
46
- }
47
- return Array.from(dependencies);
48
- }
49
- // Inisialisasi package.json dasar jika belum ada
50
- if (!fs.existsSync(path.join(__dirname, 'package.json'))) {
51
- fs.writeFileSync(path.join(__dirname, 'package.json'), JSON.stringify({
52
- name: "dynamic-api-server",
53
- version: "1.0.0",
54
- private: true,
55
- dependencies: {
56
- "express": "^4.19.2"
57
- }
58
- }, null, 2));
59
- }
60
- // Fungsi untuk memindai dan mendaftarkan endpoint secara dinamis
61
- async function registerApiRoutes() {
62
- if (!fs.existsSync(API_DIR)) {
63
- fs.mkdirSync(API_DIR, { recursive: true });
64
- }
65
- const files = fs.readdirSync(API_DIR);
66
- const allNeededDeps = new Set();
67
- // Langkah 1: Kumpulkan semua dependensi dari file di folder /api
68
- for (const file of files) {
69
- if (file.endsWith('.js') || file.endsWith('.mjs')) {
70
- const filePath = path.join(API_DIR, file);
71
- const deps = extractDependencies(filePath);
72
- deps.forEach(d => allNeededDeps.add(d));
73
- }
74
- }
75
- // Langkah 2: Cek dan install dependensi yang belum terinstal
76
- const packageJsonPath = path.join(__dirname, 'package.json');
77
- const pkgData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
78
- let needsInstall = false;
79
- for (const dep of allNeededDeps) {
80
- if (!pkgData.dependencies[dep]) {
81
- console.log('[*] Mendeteksi dependency baru: ' + dep);
82
- pkgData.dependencies[dep] = "*";
83
- needsInstall = true;
84
- }
85
- }
86
- if (needsInstall) {
87
- fs.writeFileSync(packageJsonPath, JSON.stringify(pkgData, null, 2));
88
- console.log("[*] Menginstal dependensi yang dibutuhkan...");
89
- execSync('npm install --production', { stdio: 'inherit' });
90
- }
91
- // Langkah 3: Daftarkan rute endpoint berdasarkan nama file
92
- for (const file of files) {
93
- if (file.endsWith('.js') || file.endsWith('.mjs')) {
94
- const fileNameWithoutExt = path.parse(file).name;
95
- const routePath = '/api/' + fileNameWithoutExt;
96
- const filePath = path.join(API_DIR, file);
97
- try {
98
- app.all(routePath, async (req, res) => {
99
- try {
100
- const fileUrl = require('url').pathToFileURL(filePath).href + '?update=' + Date.now();
101
- const importedModule = await import(fileUrl);
102
- const handler = importedModule.default || importedModule;
103
- if (typeof handler === 'function') {
104
- return await handler(req, res);
105
- } else {
106
- return res.status(500).json({ error: 'File ' + file + ' tidak mengekspor fungsi handler yang valid (req, res).' });
107
- }
108
- } catch (err) {
109
- console.error('[Error di endpoint ' + routePath + ']:', err);
110
- return res.status(500).json({ error: err.message, stack: err.stack });
111
- }
112
- });
113
- console.log('[+] Endpoint terdaftar: ' + routePath + ' (dari api/' + file + ')');
114
- } catch (err) {
115
- console.error('[-] Gagal memuat file api/' + file + ':', err.message);
116
- }
117
- }
118
- }
119
- }
120
- // Endpoint status server
121
- app.get('/', (req, res) => {
122
- res.json({ status: "Server Aktif", port: PORT, timestamp: new Date() });
123
- });
124
- // Jalankan registrasi rute dan jalankan server
125
- registerApiRoutes().then(() => {
126
- app.listen(PORT, () => {
127
- console.log('[🚀] Server berjalan di port ' + PORT);
128
- });
129
- });
130
- EOF
131
- # Install dependensi awal untuk server runner
132
- RUN npm install express
133
- # Ekspos port yang diminta
134
- EXPOSE 7860
135
- # Jalankan server
136
- CMD ["node", "server.js"]
 
1
+ FROM decolua/9router:latest