-
Notifications
You must be signed in to change notification settings - Fork 59
/
Index.res
596 lines (524 loc) · 13.4 KB
/
Index.res
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
open Express
/* The tests below relies upon the ability to store in the Request
objects abritrary JSON properties.
Each middleware will both check that previous middleware
have been called by making properties exists in the Request object and
upon success will themselves adds another property to the Request.
*/
/* [checkProperty req next property k] makes sure [property] is
present in [req]. If success then [k()] is invoked, otherwise
[Next.route] is called with next */
let checkProperty = (req, next, property, k, res) => {
let reqData = Request.asJsonObject(req)
switch Js.Dict.get(reqData, property) {
| None => next(Next.route, res)
| Some(x) =>
switch Js.Json.decodeBoolean(x) {
| Some(b) when b => k(res)
| _ => next(Next.route, res)
}
}
}
/* same as [checkProperty] but with a list of properties */
let checkProperties = (req, next, properties, k, res) => {
let rec aux = properties =>
switch properties {
| list{} => k(res)
| list{p, ...tl} => checkProperty(req, next, p, _ => aux(tl), res)
}
aux(properties)
}
/* [setProperty req property] sets the [property] in the [req] Request
value */
let setProperty = (req, property, res) => {
let reqData = Request.asJsonObject(req)
Js.Dict.set(reqData, property, Js.Json.boolean(true))
res
}
/* return the string value for [key], None if the key is not in [dict]
TODO once BOption.map is released */
let getDictString = (dict, key) =>
switch Js.Dict.get(dict, key) {
| Some(json) => Js.Json.decodeString(json)
| _ => None
}
/* make a common JSON object representing success */
let makeSuccessJson = () => {
let json = Js.Dict.empty()
Js.Dict.set(json, "success", Js.Json.boolean(true))
Js.Json.object_(json)
}
let app = express()
/*
If you would like to set view engine
App.set(app, "view engine", "pug");
*/
App.disable(app, ~name="x-powered-by")
App.useOnPath(
app,
~path="/",
Middleware.from((next, req, res) =>
res |> setProperty(req, "middleware0") |> next(Next.middleware)
),
) /* call the next middleware in the processing pipeline */
App.useWithMany(
app,
[
Middleware.from((next, req) =>
checkProperty(req, next, "middleware0", res =>
res |> setProperty(req, "middleware1") |> next(Next.middleware)
)
),
Middleware.from((next, req) =>
checkProperties(req, next, list{"middleware0", "middleware1"}, res =>
next(Next.middleware, setProperty(req, "middleware2", res))
)
),
],
)
App.get(
app,
~path="/",
Middleware.from((next, req) => {
let previousMiddlewares = list{"middleware0", "middleware1", "middleware2"}
checkProperties(req, next, previousMiddlewares, Response.sendJson(_, makeSuccessJson()))
}),
)
App.useOnPath(
app,
~path="/static",
{
let options = Static.defaultOptions()
Static.make("static", options) |> Static.asMiddleware
},
)
App.postWithMany(
app,
~path="/:id/id",
[
Middleware.from((next, req) => {
let previousMiddlewares = list{"middleware0", "middleware1", "middleware2"}
checkProperties(req, next, previousMiddlewares, res =>
switch getDictString(Request.params(req), "id") {
| Some("123") => Response.sendJson(res, makeSuccessJson())
| _ => next(Next.route, res)
}
)
}),
],
)
App.patchWithMany(
app,
~path="/:id/id",
[
Middleware.from((next, req) => {
let previousMiddlewares = list{"middleware0", "middleware1", "middleware2"}
checkProperties(req, next, previousMiddlewares, res =>
switch getDictString(Request.params(req), "id") {
| Some("123") => Response.sendJson(res, makeSuccessJson())
| _ => next(Next.route, res)
}
)
}),
],
)
App.putWithMany(
app,
~path="/:id/id",
[
Middleware.from((next, req) => {
let previousMiddlewares = list{"middleware0", "middleware1", "middleware2"}
checkProperties(req, next, previousMiddlewares, res =>
switch getDictString(Request.params(req), "id") {
| Some("123") => Response.sendJson(res, makeSuccessJson())
| _ => next(Next.route, res)
}
)
}),
],
)
App.deleteWithMany(
app,
~path="/:id/id",
[
Middleware.from((next, req) => {
let previousMiddlewares = list{"middleware0", "middleware1", "middleware2"}
checkProperties(req, next, previousMiddlewares, res =>
switch getDictString(Request.params(req), "id") {
| Some("123") => Response.sendJson(res, makeSuccessJson())
| _ => next(Next.route, res)
}
)
}),
],
)
/* If you have set up view engine, you can uncomment this "get"
Middleware.from((_, _) =>{
let dict: Js.Dict.t(string) = Js.Dict.empty();
Response.render("index", dict, ());
});
*/
App.get(
app,
~path="/baseUrl",
Middleware.from((next, req) =>
switch Request.baseUrl(req) {
| "" => Response.sendJson(_, makeSuccessJson())
| _ => next(Next.route)
}
),
)
App.get(
app,
~path="/hostname",
Middleware.from((next, req) =>
switch Request.hostname(req) {
| "localhost" => Response.sendJson(_, makeSuccessJson())
| _ => next(Next.route)
}
),
)
App.get(
app,
~path="/ip",
Middleware.from((next, req) =>
switch Request.ip(req) {
| "127.0.0.1" => Response.sendJson(_, makeSuccessJson())
| s =>
Js.log(s)
next(Next.route)
/* TODO why is it printing ::1 */
}
),
)
App.get(
app,
~path="/method",
Middleware.from((next, req) =>
switch Request.httpMethod(req) {
| Request.Get => Response.sendJson(_, makeSuccessJson())
| s =>
Js.log(s)
next(Next.route)
}
),
)
App.get(
app,
~path="/originalUrl",
Middleware.from((next, req) =>
switch Request.originalUrl(req) {
| "/originalUrl" => Response.sendJson(_, makeSuccessJson())
| s =>
Js.log(s)
next(Next.route)
}
),
)
App.get(
app,
~path="/path",
Middleware.from((next, req) =>
switch Request.path(req) {
| "/path" => Response.sendJson(_, makeSuccessJson())
| s =>
Js.log(s)
next(Next.route)
}
),
)
App.get(
app,
~path="/protocol",
Middleware.from((next, req) =>
switch Request.protocol(req) {
| Request.Http => Response.sendJson(_, makeSuccessJson())
| s =>
Js.log(s)
next(Next.route)
}
),
)
App.get(
app,
~path="/query",
Middleware.from((next, req) =>
switch getDictString(Request.query(req), "key") {
| Some("value") => Response.sendJson(_, makeSuccessJson())
| _ => next(Next.route)
}
),
)
App.get(
app,
~path="/not-found",
Middleware.from((_, _) => Response.sendStatus(_, Response.StatusCode.NotFound)),
)
App.get(
app,
~path="/error",
Middleware.from((_, _, res) =>
res
->Response.status(Response.StatusCode.InternalServerError)
->Response.sendJson(makeSuccessJson())
),
)
App.getWithMany(
app,
~path="/accepts",
[
Middleware.from((next, req) =>
switch Request.accepts(req, ["audio/whatever", "audio/basic"]) {
| Some("audio/basic") => next(Next.middleware)
| _ => next(Next.route)
}
),
Middleware.from((next, req) =>
switch Request.accepts(req, ["text/css"]) {
| None => Response.sendJson(_, makeSuccessJson())
| _ => next(Next.route)
}
),
],
)
let \">>" = (f, g, x) => x |> f |> g
App.getWithMany(
app,
~path="/accepts-charsets",
[
Middleware.from((next, req) =>
switch Request.acceptsCharsets(req, ["UTF-8", "UTF-16"]) {
| Some("UTF-8") => next(Next.middleware)
| _ => next(Next.route)
}
),
Middleware.from((next, req) =>
switch Request.acceptsCharsets(req, ["UTF-16"]) {
| None => Response.sendJson(_, makeSuccessJson())
| _ => next(Next.route)
}
),
],
)
App.get(
app,
~path="/get",
Middleware.from((next, req) =>
switch Request.get(req, "key") {
| Some("value") => Response.sendJson(_, makeSuccessJson())
| _ => next(Next.route)
}
),
)
App.get(
app,
~path="/fresh",
Middleware.from((next, req) =>
if !Request.fresh(req) {
Response.sendJson(_, makeSuccessJson())
} else {
next(Next.route)
}
),
)
App.get(
app,
~path="/stale",
Middleware.from((next, req) =>
if Request.stale(req) {
Response.sendJson(_, makeSuccessJson())
} else {
next(Next.route)
}
),
)
App.get(
app,
~path="/secure",
Middleware.from((next, req) =>
if !Request.secure(req) {
Response.sendJson(_, makeSuccessJson())
} else {
next(Next.route)
}
),
)
App.get(
app,
~path="/xhr",
Middleware.from((next, req) =>
if !Request.xhr(req) {
Response.sendJson(_, makeSuccessJson())
} else {
next(Next.route)
}
),
)
App.get(app, ~path="/redir", Middleware.from((_, _) => Response.redirect(_, "/redir/target")))
App.get(
app,
~path="/redircode",
Middleware.from((_, _) => Response.redirectCode(_, 301, "/redir/target")),
)
App.getWithMany(
app,
~path="/ocaml-exception",
[
Middleware.from((_, _, _next) => raise(Failure("Elvis has left the building!"))),
Middleware.fromError((_, err, _, res) =>
switch err {
| Failure(f) =>
res->Response.status(Response.StatusCode.PaymentRequired)->Response.sendString(f)
| _ => res->Response.sendStatus(Response.StatusCode.NotFound)
}
),
],
)
App.get(
app,
~path="/promise",
PromiseMiddleware.from((_req, _next, res) =>
res->Response.sendStatus(Response.StatusCode.NoContent)->Js.Promise.resolve
),
)
App.getWithMany(
app,
~path="/failing-promise",
[
PromiseMiddleware.from((_, _, _next) => Js.Promise.reject(Not_found)),
PromiseMiddleware.fromError((_, _req, _next, res) =>
res
->Response.status(Response.StatusCode.InternalServerError)
->Response.sendString("Caught Failing Promise")
->Js.Promise.resolve
),
],
)
let router1 = router()
Router.get(router1, ~path="/123", Middleware.from((_, _) => Response.sendStatus(_, Created)))
App.useRouterOnPath(app, ~path="/testing/testing", router1)
let router2 = router(~caseSensitive=true, ~strict=true, ())
Router.get(router2, ~path="/Case-sensitive", Middleware.from((_, _) => Response.sendStatus(_, Ok)))
Router.get(router2, ~path="/strict/", Middleware.from((_, _) => Response.sendStatus(_, Ok)))
App.useRouterOnPath(app, ~path="/router-options", router2)
App.param(
app,
~name="identifier",
Middleware.from((_next, _req) => Response.sendStatus(_, Created)),
)
App.get(
app,
~path="/param-test/:identifier",
Middleware.from((_next, _req) => Response.sendStatus(_, BadRequest)),
)
App.get(
app,
~path="/cookie-set-test",
Middleware.from((_next, _req, res) =>
res
->Response.cookie(~name="test-cookie", Js.Json.string("cool-cookie"))
->Response.sendStatus(Ok)
),
)
App.get(
app,
~path="/cookie-clear-test",
Middleware.from((_next, _req, res) =>
res->Response.clearCookie(~name="test-cookie2", ())->Response.sendStatus(Ok)
),
)
App.get(
app,
~path="/response-set-header",
Middleware.from((_, _, res) =>
res->Response.setHeader("X-Test-Header", "Set")->Response.sendStatus(Response.StatusCode.Ok)
),
)
let router3 = router(~caseSensitive=true, ~strict=true, ())
open ByteLimit
Router.use(router3, Middleware.json(~limit=5.0 |> mb, ()))
Router.use(router3, Middleware.urlencoded(~extended=true, ()))
module Body = {
type payload = {"number": int}
let jsonDecoder = json => {
open Json.Decode
{"number": json |> field("number", int)}
}
let urlEncodedDecoder = dict =>
{
"number": Js.Dict.unsafeGet(dict, "number") |> int_of_string,
}
let encoder = body => {
open Json.Encode
object_(list{("number", body["number"] |> int)})
}
}
let raiseIfNone = x =>
switch x {
| Some(value) => value
| None => Js.Exn.raiseError("Body is none")
}
Router.post(
router3,
~path="/json-doubler",
Middleware.from((_next, req, res) => {
let json = req->Request.bodyJSON->raiseIfNone->Body.jsonDecoder
Response.sendJson(res, {"number": json["number"] * 2}->Body.encoder)
}),
)
Router.post(
router3,
~path="/urlencoded-doubler",
Middleware.from((_next, req, res) => {
let decoded = req->Request.bodyURLEncoded->raiseIfNone->Body.urlEncodedDecoder
Response.sendJson(res, {"number": decoded["number"] * 2}->Body.encoder)
}),
)
App.useRouterOnPath(app, ~path="/builtin-middleware", router3)
let router4 = router(~caseSensitive=true, ~strict=true, ())
Router.use(router4, Middleware.text())
Router.post(
router4,
~path="/text-body",
Middleware.from((_next, req, res) =>
Response.sendString(res, Request.bodyText(req)->raiseIfNone)
),
)
App.useRouterOnPath(app, ~path="/router4", router4)
let onListen = e =>
switch e {
| exception Js.Exn.Error(e) => {
Js.log(e)
Node.Process.exit(1)
}
| _ => Js.log("Listening at http://127.0.0.1:3000")
}
let server = App.listen(app, ~port=3000, ~onListen, ())
let countRequests = server => {
let count = ref(0)
HttpServer.on(server, #request((_, _) => count := count.contents + 1))
() => {
let result = count.contents
count := -1
result
}
}
let getRequestsCount = countRequests(server)
App.post(
app,
~path="/get-request-count",
Middleware.from((_, _, res) =>
Response.sendString(
res,
"The server has been called " ++ (string_of_int(getRequestsCount()) ++ " times."),
)
),
)
/* Other examples are
App.listen app ();
App.listen app port::1000 ();
App.listen app port::1000 onListen::(fun e => Js.log e) ();
*/
/* -- Test the server --
npm run start && cd tests && ./test.sh
*/