-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
172 lines (154 loc) · 4.45 KB
/
app.js
File metadata and controls
172 lines (154 loc) · 4.45 KB
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/**
* Express Application Configuration
* Configures and exports the Express app instance
*/
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import swaggerUi from 'swagger-ui-express';
import yaml from 'js-yaml';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import mongoose from 'mongoose';
// Import middleware
import errorHandler from './middleware/errorHandler.js';
import { requestLogger } from './middleware/logger.js';
import requestId from './middleware/requestId.js';
// Import centralized routes
import routes from './routes/index.js';
// Import constants
import { API_VERSION } from './config/constants.js';
// Load Swagger YAML
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const swaggerDocument = yaml.load(
readFileSync(join(__dirname, 'docs', 'swagger.yaml'), 'utf8')
);
const app = express();
/**
* CORS Configuration
* Configure CORS via environment variable `CORS_ORIGIN` (comma-separated)
* In production, CORS_ORIGIN must be explicitly set for security
*/
if (process.env.NODE_ENV === 'production' && !process.env.CORS_ORIGIN) {
console.error('\n❌ FATAL: CORS_ORIGIN must be set in production environment\n');
process.exit(1);
}
const corsOptions = {
origin: (origin, callback) => {
const allowedOrigins = process.env.CORS_ORIGIN
? process.env.CORS_ORIGIN.split(',')
: ['*'];
if (allowedOrigins.includes('*')) {
return callback(null, true);
}
if (!origin || allowedOrigins.includes(origin)) {
return callback(null, true);
}
callback(new Error('Not allowed by CORS'));
},
credentials: true
};
// Middleware
// Security headers with custom CSP for Swagger UI compatibility
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"], // Required for Swagger UI
styleSrc: ["'self'", "'unsafe-inline'"], // Required for Swagger UI
imgSrc: ["'self'", "data:", "https:"],
fontSrc: ["'self'", "data:"],
objectSrc: ["'none'"],
upgradeInsecureRequests: [],
},
},
})
);
app.use(cors(corsOptions));
app.use(requestId); // Request ID for tracing
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(requestLogger);
/**
* Swagger API Documentation
* Serves interactive API documentation at /api-docs
*/
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: 'myWorld Travel API Documentation',
customfavIcon: '/favicon.ico'
}));
/**
* Root endpoint with minimal HATEOAS links
* Provides a machine-readable entrypoint describing important routes
*/
app.get('/', (_, res) => {
res.json({
message: '🌍 Welcome to myWorld Travel API',
version: API_VERSION,
description: 'RESTful API with HATEOAS support for personalized travel experiences',
documentation: '/api-docs',
links: {
'api-info': {
href: '/',
method: 'GET'
},
users: {
href: '/users/{userId}/profile',
method: 'GET',
templated: true
},
places: {
href: '/places/{placeId}',
method: 'GET',
templated: true
},
search: {
href: '/places/search?keywords={keywords}',
method: 'GET',
templated: true
},
navigation: {
href: '/navigation',
method: 'GET'
}
}
});
});
// Health check endpoint
app.get('/health', (_, res) => {
// Determine database status
let dbStatus = 'in-memory';
if (process.env.USE_MONGODB === 'true') {
const readyState = mongoose.connection.readyState;
dbStatus = readyState === 1 ? 'connected' : readyState === 2 ? 'connecting' : 'disconnected';
}
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
database: dbStatus,
version: API_VERSION
});
});
// Mount all API routes
app.use('/', routes);
// 404 handler
app.use((req, res) => {
res.status(404).json({
error: 'ENDPOINT_NOT_FOUND',
message: `Endpoint ${req.method} ${req.path} not found`,
availableEndpoints: {
users: '/users/{userId}/profile',
places: '/places/{placeId}',
search: '/places/search',
navigation: '/navigation'
}
});
});
// Error handling middleware
app.use(errorHandler);
export default app;