-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
236 lines (218 loc) · 6.28 KB
/
server.ts
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import { faker } from '@faker-js/faker'
import cors from 'cors'
import express, { Request, Response } from 'express'
import { validate } from 'jsonschema'
import morgan from 'morgan'
import pkg from './package.json'
const app = express()
const dev = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 8080
const secret = process.env.SECRET_KEY || ''
const allowOrigin = process.env.ALLOWED_ORIGIN || '*'
const allowMethods =
process.env.ALLOWED_METHODS && process.env.ALLOWED_METHODS !== '*'
? process.env.ALLOWED_METHODS.replaceAll(' ', '')
.split(',')
.join(', ')
.toUpperCase()
: '*'
const allowHeaders =
process.env.ALLOWED_HEADERS && process.env.ALLOWED_HEADERS !== '*'
? `${process.env.ALLOWED_HEADERS?.replaceAll(' ', '').split(',').join(', ')}, X-Smockr-Secret`
: '*'
const corsOptions = cors({
origin: allowOrigin,
methods: allowMethods,
allowedHeaders: allowHeaders,
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
})
app.use(corsOptions)
app.use(express.json())
app.use(
morgan('combined', {
skip: function (req, _res) {
return req.url === '/favicon.ico'
},
}),
)
app.get('/health-check', (_req: Request, res: Response) => {
res.send({ health_check: 'up' })
})
app.get('/favicon.ico', (_req: Request, res: Response) => {
res.status(204)
})
app.all('*', (req: Request, res: Response) => {
const clientSecret = req.headers['x-smockr-secret']
const { mock }: any = req.query
let body = mock?.response?.body
let headers = mock?.response?.headers
let status = mock?.response?.status
let delay = mock?.response?.delay
let bodySchema = mock?.request?.body?.schema
if (secret) {
if (clientSecret !== secret) {
res.status(401)
res.send({
code: 401,
message:
'Your secret is unauthorized, please check X-Smockr-Secret header on your request.',
type: 'AuthException',
})
return
}
}
if (!body && !headers && !status && !delay && !bodySchema) {
res.status(422)
res.send({
code: 422,
message:
'Invalid mock, read our docs for using mock https://github.com/kitabisa/smockr?tab=readme-ov-file#usage.',
type: 'MockSearchParamsException',
})
return
}
if (body) {
try {
body = faker.helpers.fake(body)
} catch (error: any) {
res.status(422)
res.send({
code: 422,
message: error.message,
type: 'FakerHelperException',
})
return
}
}
if (headers) {
try {
headers = {
'Content-Type': 'application/json',
...JSON.parse(headers),
'Access-Control-Allow-Origin': allowOrigin,
'Access-Control-Allow-Methods': allowMethods,
'Access-Control-Allow-Headers': allowHeaders,
'X-Powered-By': 'Smockr',
}
} catch (_error: any) {
res.status(422)
res.send({
code: 422,
message:
'Mock response headers is not valid JSON string, read our docs for using mock https://github.com/kitabisa/smockr?tab=readme-ov-file#usage.',
type: 'MockSearchParamsException',
})
return
}
} else {
headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': allowOrigin,
'Access-Control-Allow-Methods': allowMethods,
'Access-Control-Allow-Headers': allowHeaders,
'X-Powered-By': 'Smockr',
}
}
if (status) {
if (
!isNaN(Number(status)) &&
Number(status) >= 200 &&
Number(status) <= 599
) {
status = Number(status)
} else {
res.status(422)
res.send({
code: 422,
message:
'Mock response status is not valid HTTP status code, read our docs for using mock https://github.com/kitabisa/smockr?tab=readme-ov-file#usage.',
type: 'MockSearchParamsException',
})
return
}
} else {
status = 200
}
if (delay) {
if (!isNaN(Number(delay))) {
delay = Number(delay)
} else {
res.status(422)
res.send({
code: 422,
message:
'Mock response delay is not valid number, read our docs for using mock https://github.com/kitabisa/smockr?tab=readme-ov-file#usage.',
type: 'MockSearchParamsException',
})
return
}
} else {
delay = 0
}
if (bodySchema) {
try {
bodySchema = JSON.parse(bodySchema)
} catch (_error: any) {
res.status(422)
res.send({
code: 422,
message:
'Mock request body schema is not valid JSON schema validation string, read our docs for using mock https://github.com/kitabisa/smockr?tab=readme-ov-file#usage.',
type: 'MockSearchParamsException',
})
return
}
try {
const validation = validate(req.body, bodySchema, {
required: true,
allowUnknownAttributes: false,
})
if (!validation.valid) {
const msg = validation.errors[0]
.toString()
.replaceAll('instance ', '')
.replaceAll('instance.', '')
.replaceAll('"', '')
res.status(400)
res.send({
// nosemgrep
code: 400,
message: msg && msg[0].toUpperCase() + msg.slice(1),
type: 'SchemaValidationException',
})
return
}
} catch (error: any) {
res.status(422)
res.send({
code: 422,
message: error.message,
type: 'JSONSchemaHelperException',
})
return
}
}
if (delay) {
setTimeout(() => {
res.status(status)
res.set(headers)
res.send(body) // nosemgrep
}, delay)
return
}
res.status(status)
res.set(headers)
res.send(body) // nosemgrep
})
app.listen(port, () => {
console.log(` \x1b[33m▲ ${pkg.name} ${pkg.version}\x1b[0m`)
console.log(` - Runtime: ${process.versions.bun ? 'bun' : 'node'}`)
console.log(` - Network: http://localhost:${port}`)
console.log(` - Local: http://0.0.0.0:${port}`)
console.log(` - Params: --port ${port}`)
if (secret)
console.log(` --secret ${dev ? secret : '******'}`)
console.log(` --allowOrigin ${allowOrigin}`)
console.log(` --allowMethods ${allowMethods}`)
console.log(` --allowHeaders ${allowHeaders}\n`)
})