-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
96 lines (84 loc) · 2.38 KB
/
server.js
File metadata and controls
96 lines (84 loc) · 2.38 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
const express = require("express");
const cors = require("cors");
const winston = require("winston");
const app = express();
const port = process.env.PORT || 1337;
// Configure logger
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Middleware
app.use(cors());
app.use(express.json());
// Health check endpoint
app.get("/health", (req, res) => {
res.json({ status: "healthy" });
});
app.post("/send", (req, res) => {
const { type, recipient, message } = req.body;
const random = Math.random() * 100;
logger.info('Received notification request', {
type,
recipient,
random,
timestamp: new Date().toISOString()
});
if (random <= 30) {
// 30% chance of rate limit
logger.warn('Rate limit exceeded', { random });
return res.status(429).json({
error: "Too Many Requests",
message: "Rate limit exceeded",
retryAfter: 30
});
}
if (random > 30 && random <= 35) {
// 5% chance of server error
logger.error('Internal server error occurred', { random });
return res.status(500).json({
error: "Internal Server Error",
message: "Something went wrong",
errorId: Date.now().toString(36)
});
}
if (random > 35 && random <= 55) {
// 20% chance of timeout (5 seconds)
logger.info('Delayed response initiated', { random });
setTimeout(() => {
logger.info('Sending delayed response', { random });
res.json({
success: true,
message: "Delayed response",
processedAt: new Date().toISOString()
});
}, 5000);
return;
}
// Normal response
logger.info('Sending successful response', { random });
res.json({
success: true,
message: "Notification processed successfully",
processedAt: new Date().toISOString()
});
});
// Error handling middleware
app.use((err, req, res, next) => {
logger.error('Unhandled error', { error: err.message, stack: err.stack });
res.status(500).json({
error: "Internal Server Error",
message: "An unexpected error occurred"
});
});
app.listen(port, "0.0.0.0", () => {
logger.info(`Mock API running on port ${port}`);
});