app_store / server.js
rajesh9698's picture
Deploy stable Nexsonium app to Hugging Face Space πŸš€
e354ac3 verified
Raw History Blame Contribute Delete
9.16 kB
import express from 'express';
import cors from 'cors';
import pkg from '@prisma/client';
const { PrismaClient } = pkg;
import pg from 'pg';
import { PrismaPg } from '@prisma/adapter-pg';
import dotenv from 'dotenv';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
dotenv.config();
// Ensure uploads directory exists
const uploadDir = path.join(process.cwd(), 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
const app = express();
app.use(cors());
app.use(express.json());
app.use('/uploads', express.static('uploads'));
// Server-Sent Events (SSE) for Real-Time synchronization
let sseClients = []; // array of { res, clientId }
function getUniqueActiveUsersCount() {
const storefrontClients = sseClients.filter(c => c.source === 'storefront');
const uniqueIds = new Set(storefrontClients.map(c => c.clientId));
return uniqueIds.size;
}
function broadcastEvent(data) {
sseClients.forEach(client => {
try {
const connection = client.res || client;
connection.write(`data: ${JSON.stringify(data)}\n\n`);
} catch (e) {
// client disconnected
}
});
}
app.get('/api/events', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('Access-Control-Allow-Origin', '*');
res.flushHeaders();
const clientId = req.query.clientId || 'anonymous_' + Math.random().toString(36).substring(2, 9);
const source = req.query.source || 'storefront';
sseClients.push({ res, clientId, source });
// Broadcast updated connected users count to all clients
broadcastEvent({ type: 'ACTIVE_USERS', details: { count: getUniqueActiveUsersCount() } });
// Also send the initial registered users count to this client
try {
const totalUsers = await prisma.user.count();
res.write(`data: ${JSON.stringify({ type: 'USER_LOGIN', details: { count: totalUsers } })}\n\n`);
} catch (e) {
console.error(e);
}
req.on('close', () => {
sseClients = sseClients.filter(client => client.res !== res);
// Broadcast updated connected users count when client disconnects
broadcastEvent({ type: 'ACTIVE_USERS', details: { count: getUniqueActiveUsersCount() } });
});
});
// Upload APK endpoint
app.post('/api/upload-apk', upload.single('apk'), (req, res) => {
if (!req.file) {
return res.status(400).json({ error: "No file uploaded" });
}
const fileUrl = `/uploads/${req.file.filename}`;
res.json({ url: fileUrl });
});
// Upload Image endpoint
app.post('/api/upload-image', upload.single('image'), (req, res) => {
if (!req.file) {
return res.status(400).json({ error: "No image uploaded" });
}
const fileUrl = `/uploads/${req.file.filename}`;
res.json({ url: fileUrl });
});
// Apps endpoints
app.get('/api/apps', async (req, res) => {
try {
const apps = await prisma.app.findMany();
res.json(apps);
} catch (error) {
res.status(500).json({ error: "Database not connected yet" });
}
});
app.post('/api/apps', async (req, res) => {
try {
const {
name, developer, category, size, version, price,
downloads, totalRatings, rating, icon, apkUrl,
description, longDescription
} = req.body;
const newApp = await prisma.app.create({
data: {
name,
developer,
category,
size,
version,
icon,
apkUrl: apkUrl || null,
shortDesc: description || '',
longDesc: longDescription || '',
price: parseFloat(price || 0),
downloads: downloads || 0,
totalRatings: totalRatings || 0,
rating: rating || 0
}
});
broadcastEvent({ type: 'UPDATE' }); // Notify all listening clients instantly
res.json(newApp);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to create app" });
}
});
app.put('/api/apps/:id', async (req, res) => {
try {
const appBefore = await prisma.app.findUnique({ where: { id: req.params.id } });
const updatedApp = await prisma.app.update({
where: { id: req.params.id },
data: req.body
});
let eventType = 'UPDATE';
let details = null;
if (req.body.downloads && appBefore && req.body.downloads > appBefore.downloads) {
eventType = 'DOWNLOAD';
details = {
appName: updatedApp.name,
downloads: updatedApp.downloads
};
}
broadcastEvent({ type: eventType, details }); // Notify all listening clients instantly
res.json(updatedApp);
} catch (error) {
console.error(error);
res.status(404).json({ error: "App not found" });
}
});
app.post('/api/apps/:id/download', async (req, res) => {
try {
const updatedApp = await prisma.app.update({
where: { id: req.params.id },
data: {
downloads: {
increment: 1
}
}
});
broadcastEvent({
type: 'DOWNLOAD',
details: {
appName: updatedApp.name,
downloads: updatedApp.downloads
}
}); // Notify all listening clients instantly
res.json(updatedApp);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to register download" });
}
});
app.delete('/api/apps/:id', async (req, res) => {
try {
await prisma.review.deleteMany({ where: { appId: req.params.id } });
await prisma.app.delete({ where: { id: req.params.id } });
broadcastEvent({ type: 'UPDATE' }); // Notify all listening clients instantly
res.json({ success: true });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to delete app" });
}
});
// Users endpoints
app.post('/api/users/login', async (req, res) => {
try {
const { email, name, avatar } = req.body;
if (!email) {
return res.status(400).json({ error: "Email is required" });
}
// Upsert user (create or update if they already exist)
const user = await prisma.user.upsert({
where: { email },
update: { name, avatar: avatar || "πŸ‘€" },
create: { email, name, avatar: avatar || "πŸ‘€" }
});
// Get total unique registered users
const totalUsers = await prisma.user.count();
// Broadcast user login / total users update to all clients
broadcastEvent({
type: 'USER_LOGIN',
details: {
count: totalUsers,
userName: user.name
}
});
res.json(user);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to login user" });
}
});
app.get('/api/users/count', async (req, res) => {
try {
const count = await prisma.user.count();
res.json({ count });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to get user count" });
}
});
// Reviews endpoints
app.get('/api/reviews', async (req, res) => {
try {
const reviews = await prisma.review.findMany();
res.json(reviews);
} catch (error) {
res.status(500).json({ error: "Database not connected yet" });
}
});
app.post('/api/reviews', async (req, res) => {
try {
const { appId, userName, user, rating, comment, date } = req.body;
const newReview = await prisma.review.create({
data: {
appId,
user: user || userName || 'Anonymous',
rating: parseInt(rating || 5),
comment: comment || '',
date: date || new Date().toISOString().split('T')[0],
helpful: 0
}
});
// Recalculate average rating of target app
const appReviews = await prisma.review.findMany({ where: { appId: newReview.appId } });
const total = appReviews.length;
const sum = appReviews.reduce((s, r) => s + r.rating, 0);
const avg = parseFloat((sum / total).toFixed(1));
await prisma.app.update({
where: { id: newReview.appId },
data: { totalRatings: total, rating: avg }
});
const targetApp = await prisma.app.findUnique({ where: { id: newReview.appId } });
broadcastEvent({
type: 'REVIEW',
details: {
appName: targetApp ? targetApp.name : 'App',
rating: newReview.rating,
user: newReview.user,
comment: newReview.comment
}
}); // Notify all listening clients instantly
res.json(newReview);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to create review" });
}
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`πŸš€ Nexsonium API Server running on http://localhost:${PORT} with Prisma PostgreSQL`);
});