Spaces:
Runtime error
Runtime error
Download server.js from Huzaifa1313/hitech-api: direct link, hf CLI and curl.
- Browser
- Download file 24.1 kB
-
https://huggingface.co/spaces/Huzaifa1313/hitech-api/resolve/main/server.js
- Command line
-
hf download hf://spaces/Huzaifa1313/hitech-api/server.js
-
curl -L -o server.js https://huggingface.co/spaces/Huzaifa1313/hitech-api/resolve/main/server.js
24.1 kB
| const path = require('path'); | |
| const fs = require('fs'); | |
| const dns = require('dns'); | |
| const express = require('express'); | |
| const cors = require('cors'); | |
| const dotenv = require('dotenv'); | |
| const bcrypt = require('bcryptjs'); | |
| const jwt = require('jsonwebtoken'); | |
| const multer = require('multer'); | |
| const Datastore = require('@seald-io/nedb'); | |
| const { MongoClient, ObjectId } = require('mongodb'); | |
| // Load environment variables | |
| dotenv.config({ path: path.join(__dirname, '.env') }); | |
| dotenv.config({ path: path.join(__dirname, '..', '.env') }); | |
| const app = express(); | |
| const PORT = Number(process.env.PORT || 7860); // Hugging Face default port | |
| const JWT_SECRET = process.env.JWT_SECRET || 'hitech_secret_2025'; | |
| const MONGODB_URI = process.env.MONGODB_URI; | |
| const MONGODB_DB = process.env.MONGODB_DB || 'hitech_technologies'; | |
| const ROOT_DIR = __dirname; // Fixed for Hugging Face | |
| const PUBLIC_DIR = path.join(ROOT_DIR, 'public'); | |
| const UPLOADS_DIR = path.join(ROOT_DIR, 'uploads'); | |
| const LEGACY_DATA_DIR = path.join(ROOT_DIR, 'data'); | |
| let mongoClient; | |
| let mongoDb; | |
| const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); | |
| const collection = (name) => mongoDb.collection(name); | |
| const toObjectId = (value) => (ObjectId.isValid(value) ? new ObjectId(value) : null); | |
| function ensureDirs() { | |
| if (!fs.existsSync(UPLOADS_DIR)) fs.mkdirSync(UPLOADS_DIR, { recursive: true }); | |
| if (!fs.existsSync(LEGACY_DATA_DIR)) fs.mkdirSync(LEGACY_DATA_DIR, { recursive: true }); | |
| } | |
| function normalizeDoc(doc) { | |
| if (!doc) return doc; | |
| const id = String(doc._id); | |
| return { | |
| ...doc, | |
| _id: id, | |
| id, | |
| created_at: doc.createdAt, | |
| updated_at: doc.updatedAt, | |
| }; | |
| } | |
| const normalizeDocs = (docs) => (Array.isArray(docs) ? docs.map(normalizeDoc) : []); | |
| async function findDocs(name, query = {}, sort = {}) { | |
| let cursor = collection(name).find(query); | |
| if (Object.keys(sort).length) cursor = cursor.sort(sort); | |
| return normalizeDocs(await cursor.toArray()); | |
| } | |
| async function findOneDoc(name, query = {}) { | |
| return normalizeDoc(await collection(name).findOne(query)); | |
| } | |
| async function insertDoc(name, doc) { | |
| const result = await collection(name).insertOne(doc); | |
| return normalizeDoc({ ...doc, _id: result.insertedId }); | |
| } | |
| async function updateDoc(name, query, set, options = {}) { | |
| return collection(name).updateOne(query, { $set: set }, options); | |
| } | |
| async function upsertDoc(name, query, set) { | |
| return collection(name).updateOne(query, { $set: set }, { upsert: true }); | |
| } | |
| async function removeDoc(name, query) { | |
| return collection(name).deleteOne(query); | |
| } | |
| async function countDocs(name, query = {}) { | |
| return collection(name).countDocuments(query); | |
| } | |
| function deleteStoredFile(urlPath) { | |
| if (!urlPath || typeof urlPath !== 'string') return; | |
| const safeRelative = urlPath.replace(/^\//, ''); | |
| const fullPath = path.join(ROOT_DIR, safeRelative); | |
| if (!fullPath.startsWith(UPLOADS_DIR)) return; | |
| if (fs.existsSync(fullPath)) fs.unlinkSync(fullPath); | |
| } | |
| function legacyFile(name) { | |
| return path.join(LEGACY_DATA_DIR, `${name}.db`); | |
| } | |
| function loadLegacyDocs(filePath) { | |
| return new Promise((resolve, reject) => { | |
| if (!fs.existsSync(filePath)) return resolve([]); | |
| const store = new Datastore({ filename: filePath, autoload: true }); | |
| store.find({}).exec((err, docs) => { | |
| if (err) return reject(err); | |
| resolve(docs || []); | |
| }); | |
| }); | |
| } | |
| function legacyDocToMongo(doc) { | |
| if (!doc) return doc; | |
| const { _id, ...rest } = doc; | |
| return { | |
| ...rest, | |
| legacyId: _id ? String(_id) : undefined, | |
| createdAt: doc.createdAt ? new Date(doc.createdAt) : new Date(), | |
| updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : undefined, | |
| }; | |
| } | |
| function stripUndefined(doc) { | |
| return Object.fromEntries(Object.entries(doc).filter(([, value]) => value !== undefined)); | |
| } | |
| const DEFAULT_SETTINGS = { | |
| company_name: 'HiTech Technologies', | |
| tagline: "Pakistan's Leading Software Company", | |
| hero_title: 'Smart *Software* Solutions That *Scale* With You', | |
| hero_subtitle: 'From custom AI automation to enterprise-grade software systems - we build technology that transforms your business operations and delivers real results.', | |
| about_text: 'HiTech Technologies was founded with a clear mission: to make world-class software development accessible to businesses of every size in Pakistan and beyond. We specialize in custom software, AI automation, data science, mobile apps, web platforms, and enterprise management systems.', | |
| address: 'G-11, Islamabad, Pakistan', | |
| phone: '03345555362', | |
| email: 'info@hitechtech.pk', | |
| whatsapp: '03345555362', | |
| facebook: 'https://facebook.com/hitechtech', | |
| linkedin: 'https://linkedin.com/company/hitechtech', | |
| twitter: 'https://twitter.com/hitechtech', | |
| working_hours: 'Mon - Sat: 9:00 AM - 6:00 PM', | |
| footer_text: "Pakistan's trusted software development company. We build custom software, AI automation, and enterprise solutions for businesses of all sizes.", | |
| }; | |
| const DEFAULT_SERVICES = [ | |
| { name: 'AI Automation', description: 'Harness artificial intelligence to automate workflows, reduce manual tasks, and optimize operations. We build ML pipelines, chatbots, and intelligent systems that adapt to your business.', icon: 'fa-brain', features: 'Workflow Automation,ML Pipelines,Chatbot Development,Document AI,Predictive Analytics', status: 'active', sort_order: 1 }, | |
| { name: 'Data Science Services', description: 'Transform raw data into actionable insights. Custom dashboards, predictive models, and analytics pipelines that empower smarter, data-driven decisions across your organization.', icon: 'fa-chart-bar', features: 'Data Analytics,Custom Dashboards,Predictive Models,Business Intelligence,Data Engineering', status: 'active', sort_order: 2 }, | |
| { name: 'POS Software', description: 'Feature-rich Point-of-Sale systems for retail, restaurants, pharmacies, and all business types. Inventory control, fast billing, multi-branch support, and real-time reporting in one system.', icon: 'fa-cash-register', features: 'Inventory Control,Multi-Branch,Barcode Support,Sales Reports,Customer Loyalty', status: 'active', sort_order: 3 }, | |
| { name: 'App Development', description: 'Beautiful, high-performance mobile applications for iOS and Android. We develop native and cross-platform apps using Flutter and React Native with exceptional user experiences.', icon: 'fa-mobile-alt', features: 'iOS & Android,Flutter / React Native,UI/UX Design,API Integration,Push Notifications', status: 'active', sort_order: 4 }, | |
| { name: 'Web Development', description: 'Responsive, fast, and scalable web applications built with modern frameworks. From corporate websites to complex enterprise portals - we deliver exceptional digital experiences.', icon: 'fa-globe', features: 'React / Vue / Next.js,E-Commerce,Web Portals,REST APIs,SEO Optimized', status: 'active', sort_order: 5 }, | |
| { name: 'Custom Software', description: 'Bespoke software built from scratch to match your unique business processes. ERP systems, CRM solutions, billing platforms, and specialized industry tools tailored to your workflow.', icon: 'fa-code', features: 'ERP Systems,CRM Solutions,Billing Systems,HR & Payroll,API Development', status: 'active', sort_order: 6 }, | |
| ]; | |
| const DEFAULT_PRODUCTS = [ | |
| { name: 'School Management System', category: 'Education', description: 'A complete academic management platform for schools, colleges, and educational institutes. Manage everything from admissions to results in one centralized system with parent portal and SMS alerts.', features: 'Student Enrollment & Records,Attendance Tracking (Manual & Biometric),Fee Collection & Receipts,Grade Book & Result Management,Parent Portal & SMS Notifications,Teacher & Staff Management,Library Management,Timetable & Scheduling', banner_color: '#0D2B7A', status: 'active' }, | |
| { name: 'Patient Token System', category: 'Healthcare', description: 'Eliminate waiting room chaos with a smart patient queuing system for clinics, hospitals, and labs. Display tokens on screen, notify patients via SMS, and manage priorities with ease.', features: 'Auto Token Generation,Digital Display Screen,Priority Queue (Emergency),SMS & WhatsApp Notifications,Multiple Counter Support,Doctor-Wise Queuing,Daily Reports & Analytics,Multi-Branch Support', banner_color: '#C91F1F', status: 'active' }, | |
| { name: 'Gym Management System', category: 'Fitness', description: 'A powerful gym and fitness center management platform. Handle memberships, payments, staff, workout plans, and member check-in all in one comprehensive system.', features: 'Member Registration & Profiles,Subscription & Membership Plans,Automated Billing & Renewals,Biometric / Card Check-in,Staff & Trainer Management,Workout Plan Assignment,Expiry Alerts & Notifications,Revenue Reports & Analytics', banner_color: '#071B52', status: 'active' }, | |
| ]; | |
| async function seedDefaults() { | |
| const adminCount = await countDocs('admins'); | |
| if (adminCount === 0) { | |
| await insertDoc('admins', { | |
| username: 'Huzaifa', | |
| password_hash: bcrypt.hashSync('12345', 10), | |
| createdAt: new Date(), | |
| }); | |
| console.log('Seeded default admin: Huzaifa / 12345'); | |
| } | |
| const settingsCount = await countDocs('settings'); | |
| if (settingsCount === 0) { | |
| const docs = Object.entries(DEFAULT_SETTINGS).map(([key, value]) => ({ key, value })); | |
| await collection('settings').insertMany(docs); | |
| } | |
| const servicesCount = await countDocs('services'); | |
| if (servicesCount === 0) { | |
| const docs = DEFAULT_SERVICES.map((doc) => ({ ...doc, banner_url: null, createdAt: new Date() })); | |
| await collection('services').insertMany(docs); | |
| } | |
| const productsCount = await countDocs('products'); | |
| if (productsCount === 0) { | |
| const docs = DEFAULT_PRODUCTS.map((doc) => ({ ...doc, banner_url: null, createdAt: new Date() })); | |
| await collection('products').insertMany(docs); | |
| } | |
| } | |
| async function migrateLegacyCollection(collectionName, filePath, mapper = legacyDocToMongo) { | |
| const currentCount = await countDocs(collectionName); | |
| if (currentCount > 0) return; | |
| const docs = await loadLegacyDocs(filePath); | |
| if (!docs.length) return; | |
| const mapped = docs.map(mapper).map(stripUndefined); | |
| if (!mapped.length) return; | |
| await collection(collectionName).insertMany(mapped); | |
| console.log(`Migrated ${mapped.length} docs into ${collectionName}`); | |
| } | |
| async function bootstrapDatabase() { | |
| ensureDirs(); | |
| if (!MONGODB_URI) { | |
| throw new Error('MONGODB_URI is missing. Put it in .env or Hugging Face secret'); | |
| } | |
| console.log('MongoDB URI exists, attempting connection...'); | |
| const connectOptions = { | |
| serverSelectionTimeoutMS: 30000, | |
| socketTimeoutMS: 45000, | |
| connectTimeoutMS: 30000, | |
| family: 4, // Force IPv4 - important for Hugging Face | |
| }; | |
| const tryConnect = async () => { | |
| mongoClient = new MongoClient(MONGODB_URI, connectOptions); | |
| await mongoClient.connect(); | |
| mongoDb = mongoClient.db(MONGODB_DB); | |
| console.log('โ MongoDB Connected Successfully!'); | |
| }; | |
| try { | |
| await tryConnect(); | |
| } catch (error) { | |
| console.error('First connection attempt failed:', error.message); | |
| const isSrvUri = MONGODB_URI.startsWith('mongodb+srv://'); | |
| const isSrvLookupError = String(error?.message || '').includes('querySrv') || | |
| String(error?.code || '').includes('ECONNREFUSED'); | |
| if (isSrvUri && isSrvLookupError) { | |
| console.log('Attempting with DNS servers 1.1.1.1, 8.8.8.8...'); | |
| dns.setServers(['1.1.1.1', '8.8.8.8']); | |
| await tryConnect(); | |
| console.log('MongoDB connected after switching DNS resolvers'); | |
| } else { | |
| throw error; | |
| } | |
| } | |
| await migrateLegacyCollection('admins', legacyFile('admins')); | |
| await migrateLegacyCollection('settings', legacyFile('settings')); | |
| await migrateLegacyCollection('services', legacyFile('services')); | |
| await migrateLegacyCollection('products', legacyFile('products')); | |
| await migrateLegacyCollection('posts', legacyFile('posts')); | |
| await migrateLegacyCollection('contacts', legacyFile('contacts')); | |
| await seedDefaults(); | |
| } | |
| const auth = asyncHandler(async (req, res, next) => { | |
| const token = req.headers.authorization?.split(' ')[1]; | |
| if (!token) return res.status(401).json({ error: 'Unauthorized' }); | |
| try { | |
| req.user = jwt.verify(token, JWT_SECRET); | |
| next(); | |
| } catch { | |
| res.status(401).json({ error: 'Invalid token' }); | |
| } | |
| }); | |
| const storage = multer.diskStorage({ | |
| destination: (req, file, cb) => cb(null, UPLOADS_DIR), | |
| filename: (req, file, cb) => cb(null, `${Date.now()}-${Math.random().toString(36).slice(2)}${path.extname(file.originalname)}`), | |
| }); | |
| const upload = multer({ | |
| storage, | |
| limits: { fileSize: 10 * 1024 * 1024 }, | |
| fileFilter: (req, file, cb) => { | |
| if (/image/.test(file.mimetype)) cb(null, true); | |
| else cb(new Error('Images only')); | |
| }, | |
| }); | |
| app.use(cors()); | |
| app.use(express.json({ limit: '20mb' })); | |
| app.use(express.urlencoded({ extended: true })); | |
| app.use(express.static(PUBLIC_DIR)); | |
| app.use('/uploads', express.static(UPLOADS_DIR)); | |
| app.post('/api/auth/login', asyncHandler(async (req, res) => { | |
| const { username, password } = req.body; | |
| if (!username || !password) return res.status(400).json({ error: 'Username and password required' }); | |
| const user = await findOneDoc('admins', { username }); | |
| if (!user || !bcrypt.compareSync(password, user.password_hash)) { | |
| return res.status(401).json({ error: 'Invalid credentials' }); | |
| } | |
| const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' }); | |
| res.json({ token, username: user.username }); | |
| })); | |
| app.post('/api/auth/change-password', auth, asyncHandler(async (req, res) => { | |
| const { currentPassword, newPassword } = req.body; | |
| const user = await findOneDoc('admins', { _id: toObjectId(req.user.id) }); | |
| if (!user || !bcrypt.compareSync(currentPassword, user.password_hash)) { | |
| return res.status(401).json({ error: 'Current password incorrect' }); | |
| } | |
| await updateDoc('admins', { _id: toObjectId(req.user.id) }, { password_hash: bcrypt.hashSync(newPassword, 10) }); | |
| res.json({ success: true }); | |
| })); | |
| app.get('/api/settings', asyncHandler(async (req, res) => { | |
| const rows = await findDocs('settings'); | |
| const settings = {}; | |
| rows.forEach((row) => { | |
| settings[row.key] = row.value; | |
| }); | |
| res.json(settings); | |
| })); | |
| app.put('/api/settings', auth, asyncHandler(async (req, res) => { | |
| for (const [key, value] of Object.entries(req.body)) { | |
| await upsertDoc('settings', { key }, { key, value: value || '' }); | |
| } | |
| res.json({ success: true }); | |
| })); | |
| app.get('/api/services', asyncHandler(async (req, res) => { | |
| const query = req.query.all ? {} : { status: 'active' }; | |
| const docs = await findDocs('services', query, { sort_order: 1, createdAt: 1 }); | |
| res.json(docs); | |
| })); | |
| app.post('/api/services', auth, upload.single('banner'), asyncHandler(async (req, res) => { | |
| const { name, description, icon, features, status, sort_order } = req.body; | |
| if (!name) return res.status(400).json({ error: 'Name required' }); | |
| const banner_url = req.file ? `/uploads/${req.file.filename}` : null; | |
| const doc = await insertDoc('services', { | |
| name, | |
| description: description || '', | |
| icon: icon || 'fa-cog', | |
| banner_url, | |
| features: features || '', | |
| status: status || 'active', | |
| sort_order: Number.isFinite(Number(sort_order)) ? Number(sort_order) : 0, | |
| createdAt: new Date(), | |
| }); | |
| res.json(doc); | |
| })); | |
| app.put('/api/services/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => { | |
| const existingId = toObjectId(req.params.id); | |
| if (!existingId) return res.status(404).json({ error: 'Not found' }); | |
| const existing = await findOneDoc('services', { _id: existingId }); | |
| if (!existing) return res.status(404).json({ error: 'Not found' }); | |
| const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url; | |
| if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url); | |
| await updateDoc('services', { _id: existingId }, { | |
| name: req.body.name || existing.name, | |
| description: req.body.description ?? existing.description, | |
| icon: req.body.icon || existing.icon, | |
| banner_url, | |
| features: req.body.features ?? existing.features, | |
| status: req.body.status || existing.status, | |
| sort_order: Number.isFinite(Number(req.body.sort_order)) ? Number(req.body.sort_order) : existing.sort_order, | |
| updatedAt: new Date(), | |
| }); | |
| res.json({ success: true, banner_url }); | |
| })); | |
| app.delete('/api/services/:id', auth, asyncHandler(async (req, res) => { | |
| const id = toObjectId(req.params.id); | |
| if (!id) return res.status(404).json({ error: 'Not found' }); | |
| const service = await findOneDoc('services', { _id: id }); | |
| if (!service) return res.status(404).json({ error: 'Not found' }); | |
| if (service.banner_url) deleteStoredFile(service.banner_url); | |
| await removeDoc('services', { _id: id }); | |
| res.json({ success: true }); | |
| })); | |
| app.get('/api/products', asyncHandler(async (req, res) => { | |
| const query = req.query.all ? {} : { status: 'active' }; | |
| const docs = await findDocs('products', query, { createdAt: 1 }); | |
| res.json(docs); | |
| })); | |
| app.post('/api/products', auth, upload.single('banner'), asyncHandler(async (req, res) => { | |
| const { name, category, description, features, banner_color, status } = req.body; | |
| if (!name) return res.status(400).json({ error: 'Name required' }); | |
| const banner_url = req.file ? `/uploads/${req.file.filename}` : null; | |
| const doc = await insertDoc('products', { | |
| name, | |
| category: category || '', | |
| description: description || '', | |
| features: features || '', | |
| banner_url, | |
| banner_color: banner_color || '#0D2B7A', | |
| status: status || 'active', | |
| createdAt: new Date(), | |
| }); | |
| res.json(doc); | |
| })); | |
| app.put('/api/products/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => { | |
| const id = toObjectId(req.params.id); | |
| if (!id) return res.status(404).json({ error: 'Not found' }); | |
| const existing = await findOneDoc('products', { _id: id }); | |
| if (!existing) return res.status(404).json({ error: 'Not found' }); | |
| const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url; | |
| if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url); | |
| await updateDoc('products', { _id: id }, { | |
| name: req.body.name || existing.name, | |
| category: req.body.category ?? existing.category, | |
| description: req.body.description ?? existing.description, | |
| features: req.body.features ?? existing.features, | |
| banner_url, | |
| banner_color: req.body.banner_color || existing.banner_color, | |
| status: req.body.status || existing.status, | |
| updatedAt: new Date(), | |
| }); | |
| res.json({ success: true, banner_url }); | |
| })); | |
| app.delete('/api/products/:id', auth, asyncHandler(async (req, res) => { | |
| const id = toObjectId(req.params.id); | |
| if (!id) return res.status(404).json({ error: 'Not found' }); | |
| const product = await findOneDoc('products', { _id: id }); | |
| if (!product) return res.status(404).json({ error: 'Not found' }); | |
| if (product.banner_url) deleteStoredFile(product.banner_url); | |
| await removeDoc('products', { _id: id }); | |
| res.json({ success: true }); | |
| })); | |
| app.get('/api/posts', asyncHandler(async (req, res) => { | |
| const query = req.query.all ? {} : { status: 'published' }; | |
| const docs = await findDocs('posts', query, { createdAt: -1 }); | |
| res.json(docs); | |
| })); | |
| app.post('/api/posts', auth, upload.single('banner'), asyncHandler(async (req, res) => { | |
| const { title, content, excerpt, status } = req.body; | |
| if (!title) return res.status(400).json({ error: 'Title required' }); | |
| const banner_url = req.file ? `/uploads/${req.file.filename}` : null; | |
| const doc = await insertDoc('posts', { | |
| title, | |
| content: content || '', | |
| excerpt: excerpt || '', | |
| banner_url, | |
| status: status || 'published', | |
| createdAt: new Date(), | |
| }); | |
| res.json(doc); | |
| })); | |
| app.put('/api/posts/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => { | |
| const id = toObjectId(req.params.id); | |
| if (!id) return res.status(404).json({ error: 'Not found' }); | |
| const existing = await findOneDoc('posts', { _id: id }); | |
| if (!existing) return res.status(404).json({ error: 'Not found' }); | |
| const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url; | |
| if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url); | |
| await updateDoc('posts', { _id: id }, { | |
| title: req.body.title || existing.title, | |
| content: req.body.content ?? existing.content, | |
| excerpt: req.body.excerpt ?? existing.excerpt, | |
| banner_url, | |
| status: req.body.status || existing.status, | |
| updatedAt: new Date(), | |
| }); | |
| res.json({ success: true }); | |
| })); | |
| app.delete('/api/posts/:id', auth, asyncHandler(async (req, res) => { | |
| const id = toObjectId(req.params.id); | |
| if (!id) return res.status(404).json({ error: 'Not found' }); | |
| const post = await findOneDoc('posts', { _id: id }); | |
| if (!post) return res.status(404).json({ error: 'Not found' }); | |
| if (post.banner_url) deleteStoredFile(post.banner_url); | |
| await removeDoc('posts', { _id: id }); | |
| res.json({ success: true }); | |
| })); | |
| app.post('/api/contact', asyncHandler(async (req, res) => { | |
| const { name, email, phone, service_interest, budget, message } = req.body; | |
| if (!name || !message) return res.status(400).json({ error: 'Name and message required' }); | |
| await insertDoc('contacts', { | |
| name, | |
| email: email || '', | |
| phone: phone || '', | |
| service_interest: service_interest || '', | |
| budget: budget || '', | |
| message, | |
| is_read: false, | |
| createdAt: new Date(), | |
| }); | |
| res.json({ success: true, message: 'Your message has been received! We will contact you within 24 hours.' }); | |
| })); | |
| app.get('/api/contacts', auth, asyncHandler(async (req, res) => { | |
| const docs = await findDocs('contacts', {}, { createdAt: -1 }); | |
| res.json(docs); | |
| })); | |
| app.put('/api/contacts/:id/read', auth, asyncHandler(async (req, res) => { | |
| const id = toObjectId(req.params.id); | |
| if (!id) return res.status(404).json({ error: 'Not found' }); | |
| await updateDoc('contacts', { _id: id }, { is_read: true, updatedAt: new Date() }); | |
| res.json({ success: true }); | |
| })); | |
| app.delete('/api/contacts/:id', auth, asyncHandler(async (req, res) => { | |
| const id = toObjectId(req.params.id); | |
| if (!id) return res.status(404).json({ error: 'Not found' }); | |
| await removeDoc('contacts', { _id: id }); | |
| res.json({ success: true }); | |
| })); | |
| app.get('/api/admin/stats', auth, asyncHandler(async (req, res) => { | |
| const [services, products, posts, contacts, unread] = await Promise.all([ | |
| countDocs('services', { status: 'active' }), | |
| countDocs('products', { status: 'active' }), | |
| countDocs('posts', { status: 'published' }), | |
| countDocs('contacts'), | |
| countDocs('contacts', { is_read: false }), | |
| ]); | |
| res.json({ services, products, posts, contacts, unread }); | |
| })); | |
| app.get('/api/health', asyncHandler(async (req, res) => { | |
| const adminCount = await countDocs('admins'); | |
| res.json({ | |
| status: 'OK', | |
| message: 'Server is running!', | |
| mongodb: 'Connected', | |
| db: MONGODB_DB, | |
| admins: adminCount, | |
| }); | |
| })); | |
| // Serve admin panel and frontend | |
| app.get('/admin', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'admin.html'))); | |
| app.get('*', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'index.html'))); | |
| // Error handler | |
| app.use((err, req, res, next) => { | |
| console.error(err); | |
| if (err && err.message === 'Images only') { | |
| return res.status(400).json({ error: 'Images only' }); | |
| } | |
| res.status(500).json({ error: err?.message || 'Server error' }); | |
| }); | |
| // Start server | |
| bootstrapDatabase() | |
| .then(() => { | |
| app.listen(PORT, '0.0.0.0', () => { | |
| console.log(`\n๐ HiTech Technologies (MongoDB) - http://localhost:${PORT}`); | |
| console.log(`๐ Admin Panel - http://localhost:${PORT}/admin`); | |
| console.log(`๐ฆ MongoDB DB - ${MONGODB_DB}`); | |
| }); | |
| }) | |
| .catch((error) => { | |
| console.error('Failed to bootstrap application:', error); | |
| process.exit(1); | |
| }); |