-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
158 lines (134 loc) · 4.74 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
const express = require('express');
const path = require('path');
const mysql = require('mysql2/promise');
const session = require('express-session');
const bodyParser = require('body-parser');
const passport = require('passport');
const bcrypt = require('bcryptjs');
const { generateToken, verifyToken } = require('./config/auth');
// const openai = require('./config/openaiconfig');
const paypalClient = require('./config/paypalconfig');
require('dotenv').config();
require('./config/passport')(passport);
const flash = require('connect-flash');
const cookieParser = require('cookie-parser');
const tenants = require('./middleware/tenancyMiddleware');
const asyncHandler = require('./middleware/asyncHandler');
const rateLimiter = require('./middleware/rateLimiter');
// Encode and Decode Example
const punycode = require('punycode/');
console.log('Encoded:', punycode.toASCII('localhost'));
console.log('Decoded:', punycode.toUnicode('localhost'));
// Initialize Express App
const app = express();
// Apply global rate limiter
app.use(rateLimiter);
// Example route with asyncHandler
app.get(
'/api/example',
asyncHandler(async (req, res) => {
// Your async code here
res.json({ success: true, data: 'Hello, World!' });
})
);
// Global error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
success: false,
message: 'Internal Server Error',
error: err.message,
});
});
// Session Configuration
app.use(
session({
secret: process.env.SESSION_SECRET || 'your-secret-key',
resave: false,
saveUninitialized: true,
cookie: { secure: false }, // Use true if HTTPS is enabled
})
);
app.use(flash());
// Middleware Setup
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
// Set View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Serve Static Files
app.use('/assets', express.static(path.join(__dirname, 'public', 'assets')));
app.use('/home_assets', express.static(path.join(__dirname, 'public', 'home_assets')));
// Routes to Serve Views
app.get('/', (req, res) => {
res.render('home/index', { title: 'Home' });
});
// PayPal Payment Example
app.post('/create-payment', verifyToken, async (req, res) => {
const order = {
intent: 'CAPTURE',
purchase_units: [{ amount: { value: req.body.amount } }],
application_context: {
return_url: 'http://localhost:5000/payment-success',
cancel_url: 'http://localhost:5000/payment-cancel',
},
};
const request = new paypalClient.orders.OrdersCreateRequest();
request.requestBody(order);
try {
const orderResponse = await paypalClient.execute(request);
res.json({ orderId: orderResponse.result.id });
} catch (error) {
console.error('PayPal Error:', error);
res.status(500).json({ error: 'Payment creation failed' });
}
});
// Import and Attach Additional Routes
const routes = {
auth: require('./routes/authRoute'),
dashboard: require('./routes/dashboardRoute'),
supplier: require('./routes/supplierRoute'),
invoice: require('./routes/invoiceRoute'),
sales: require('./routes/salesRoute'),
categoryReport: require('./routes/category-reportRoute'),
productReport: require('./routes/product-reportRoute'),
product: require('./routes/productRoute'),
chart: require('./routes/chartRoute'),
chartReport: require('./routes/chart-reportRoute'),
category: require('./routes/categoryRoute'),
customer: require('./routes/customerRoute'),
expense: require('./routes/expenseRoute'),
inventory: require('./routes/inventoryRoute'),
notification: require('./routes/notificationRoute'),
pageAccess: require('./routes/page-accessRoute'),
pay: require('./routes/payRoute'),
profile: require('./routes/userRoute.js'),
staff: require('./routes/staffRoute'),
subscription: require('./routes/subscriptionRoute'),
pdfRoute: require('./routes/pdfRoute'),
};
app.use('/auth', routes.auth);
Object.entries(routes).forEach(([name, route]) => {
if (name !== 'auth') app.use(`/${name}`, route);
});
// Cron Jobs
require('./cron/subscriptioncron');
// Error Handling
app.use((req, res) => {
res.status(404).json({ message: 'Route not found' });
});
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({ message: 'Internal Server Error', error: err.message });
});
// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
module.exports = app;