-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
204 lines (173 loc) · 4.7 KB
/
index.ts
File metadata and controls
204 lines (173 loc) · 4.7 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import 'dotenv/config'
import { Prisma, PrismaClient } from '@prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
import express from 'express'
const pool = new PrismaPg({ connectionString: process.env.DATABASE_URL! })
const prisma = new PrismaClient({ adapter: pool })
const app = express()
app.use(express.json())
app.get('/', (req, res) => {
res.json({ message: 'Node.js API', version: '1.0.0' })
})
app.get('/instance-info', async (req, res) => {
const os = await import('os')
res.json({
hostname: os.hostname(),
platform: os.platform(),
arch: os.arch(),
cpus: os.cpus().length,
totalMemory: `${Math.round(os.totalmem() / 1024 / 1024)}MB`,
freeMemory: `${Math.round(os.freemem() / 1024 / 1024)}MB`,
uptime: `${Math.round(os.uptime())}s`,
networkInterfaces: Object.entries(os.networkInterfaces())
.flatMap(([name, interfaces]) =>
interfaces?.filter(i => i.family === 'IPv4').map(i => ({ name, address: i.address })) || []
),
podName: process.env.HOSTNAME || 'unknown',
})
})
app.get('/cpu-stress', async (req, res) => {
const duration = Number(req.query.duration) || 5 // seconds
const startTime = Date.now()
// CPU-intensive calculation
while (Date.now() - startTime < duration * 1000) {
// Fibonacci calculation to burn CPU
let a = 0, b = 1
for (let i = 0; i < 10000000; i++) {
const temp = a + b
a = b
b = temp
}
}
res.json({
message: `CPU stress completed`,
duration: `${duration}s`,
podName: process.env.HOSTNAME || 'unknown',
})
})
app.get('/health', async (req, res) => {
try {
await prisma.$queryRaw`SELECT 1`
res.status(200).json({ status: 'healthy', timestamp: new Date().toISOString() })
} catch (error) {
res.status(503).json({ status: 'unhealthy', error: 'Database connection failed' })
}
})
app.post(`/signup`, async (req, res) => {
const { name, email, posts } = req.body
const postData = posts?.map((post: Prisma.PostCreateInput) => {
return { title: post?.title, content: post?.content }
})
const result = await prisma.user.create({
data: {
name,
email,
posts: {
create: postData,
},
},
})
res.json(result)
})
app.post(`/post`, async (req, res) => {
const { title, content, authorEmail } = req.body
const result = await prisma.post.create({
data: {
title,
content,
author: { connect: { email: authorEmail } },
},
})
res.json(result)
})
app.put('/post/:id/views', async (req, res) => {
const { id } = req.params
try {
const post = await prisma.post.update({
where: { id: Number(id) },
data: {
viewCount: {
increment: 1,
},
},
})
res.json(post)
} catch (error) {
res.json({ error: `Post with ID ${id} does not exist in the database` })
}
})
app.put('/publish/:id', async (req, res) => {
const { id } = req.params
try {
const postData = await prisma.post.findUnique({
where: { id: Number(id) },
select: {
published: true,
},
})
const updatedPost = await prisma.post.update({
where: { id: Number(id) || undefined },
data: { published: !postData?.published },
})
res.json(updatedPost)
} catch (error) {
res.json({ error: `Post with ID ${id} does not exist in the database` })
}
})
app.delete(`/post/:id`, async (req, res) => {
const { id } = req.params
const post = await prisma.post.delete({
where: {
id: Number(id),
},
})
res.json(post)
})
app.get('/users', async (req, res) => {
const users = await prisma.user.findMany()
res.json(users)
})
app.get('/user/:id/drafts', async (req, res) => {
const { id } = req.params
const drafts = await prisma.post.findMany({
where: {
authorId: Number(id),
published: false,
},
})
res.json(drafts)
})
app.get(`/post/:id`, async (req, res) => {
const { id }: { id?: string } = req.params
const post = await prisma.post.findUnique({
where: { id: Number(id) },
})
res.json(post)
})
app.get('/feed', async (req, res) => {
const { searchString, skip, take, orderBy } = req.query
const or: Prisma.PostWhereInput = searchString
? {
OR: [
{ title: { contains: searchString as string } },
{ content: { contains: searchString as string } },
],
}
: {}
const posts = await prisma.post.findMany({
where: {
published: true,
...or,
},
include: { author: true },
take: Number(take) || undefined,
skip: Number(skip) || undefined,
orderBy: {
updatedAt: orderBy as Prisma.SortOrder,
},
})
res.json(posts)
})
const server = app.listen(3000, () =>
console.log(`Server ready at: http://localhost:3000`)
)