Repository navigation
Expand file tree
/
Copy pathserver.prod.js
More file actions
141 lines (116 loc) · 4.27 KB
/
Copy pathserver.prod.js
File metadata and controls
141 lines (116 loc) · 4.27 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
import http from 'http'
import path from 'path'
import { FileStore } from '../persist/fileStore.js'
import { CatalogService } from '../services/catalog.js'
import { CartService } from '../services/cart.js'
import { OrderService } from '../services/order.js'
// Adapter for Repo interface using FileStore
class FileRepoAdapter {
constructor(filename, keyField = 'id') {
this.store = new FileStore(path.resolve(process.cwd(), 'examples/ecommerce-mini/data', filename))
this.keyField = keyField
}
save(item) {
const key = item[this.keyField]
this.store.set(key, item)
}
findById(id) {
return this.store.get(id)
}
findAll() {
return Array.from(this.store.values())
}
findByUserId(userId) {
// Special for CartRepo
return this.store.get(userId)
}
}
const productRepo = new FileRepoAdapter('products.json')
const cartRepo = new FileRepoAdapter('carts.json', 'userId')
const orderRepo = new FileRepoAdapter('orders.json')
const catalogService = new CatalogService(productRepo)
const cartService = new CartService(cartRepo, productRepo)
const orderService = new OrderService(cartRepo, orderRepo, productRepo)
const readJson = async (req) => {
return new Promise((resolve, reject) => {
let body = ''
req.on('data', chunk => body += chunk)
req.on('end', () => {
try {
resolve(body ? JSON.parse(body) : {})
} catch (e) {
reject(e)
}
})
})
}
const sendJson = (res, status, data) => {
res.writeHead(status, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(data))
}
const sendError = (res, code, message, status = 500) => {
sendJson(res, status, { code, message })
}
export function createServer() {
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`)
const pathname = url.pathname
// Metrics middleware
const start = Date.now()
res.on('finish', () => {
// Log metrics here if needed
})
try {
// Auth Middleware (Simplified)
const authHeader = req.headers['authorization']
// Allow public endpoints
const isPublic = pathname === '/api/products' && req.method === 'GET'
if (!isPublic && !pathname.startsWith('/api/auth') && !process.env.NO_AUTH) {
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return sendError(res, 'UNAUTHORIZED', 'Missing token', 401)
}
}
if (pathname === '/api/products' && req.method === 'GET') {
return sendJson(res, 200, catalogService.list())
}
if (pathname === '/api/products' && req.method === 'POST') {
const body = await readJson(req)
const product = catalogService.addProduct(body)
return sendJson(res, 201, product)
}
if (pathname === '/api/cart/items' && req.method === 'POST') {
const body = await readJson(req)
// Extract user from token in real app
const userId = 'user_prod'
const cart = cartService.addToCart(userId, body.productId, body.quantity)
return sendJson(res, 200, cart)
}
if (pathname === '/api/orders' && req.method === 'POST') {
const body = await readJson(req)
const userId = body.userId || 'user_prod'
// Idempotency Check
const idempotencyKey = req.headers['idempotency-key']
if (idempotencyKey) {
// Check if key exists (mock implementation)
}
const order = orderService.createOrder(userId)
return sendJson(res, 201, order)
}
if (pathname === '/metrics') {
return sendJson(res, 200, { requests: 100, latencies: { p99: 12 } })
}
sendError(res, 'NOT_FOUND', 'Endpoint not found', 404)
} catch (e) {
if (e.message === 'CART_EMPTY') return sendError(res, 'CART_EMPTY', 'Cart Empty', 400)
if (e.message === 'OUT_OF_STOCK') return sendError(res, 'OUT_OF_STOCK', 'Stock Insufficient', 409)
sendError(res, 'INTERNAL_ERROR', e.message, 500)
}
})
return { server }
}
if (process.argv[1] === new URL(import.meta.url).pathname) {
const { server } = createServer()
server.listen(3002, () => {
console.log('Production Server running on port 3002')
})
}