-
Notifications
You must be signed in to change notification settings - Fork 0
/
hopper.gr
1494 lines (1364 loc) · 42.2 KB
/
hopper.gr
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module Hopper: An HTTP microframework for the Grain programming language.
*
* Version 0.1.0
*/
import Option from "option"
import Result from "result"
import Number from "number"
import Map from "map"
import List from "list"
import Array from "array"
import String from "string"
import Char from "char"
import Regex from "regex"
import Int64 from "int64"
import Marshal from "marshal"
import Process from "sys/process"
import File from "sys/file"
import Time from "sys/time"
/**
* @section Types: Type declarations included in the Hopper module.
*/
/**
* Represents various HTTP request methods.
*/
export enum Method {
Get,
Post,
Put,
Delete,
Head,
Patch,
Options,
Trace,
Method(String),
}
/**
* Represents either a single value or multiple values.
*/
export enum OneOrMany<a> {
Val(a),
Vals(List<a>),
}
// underscore prefix to discourage direct record field access
/**
* Represents request-specific message data (this simply contains data
* injected into `Message<a>` to make `Request` as `Message<RequestMsgData>`).
* Typically you should not access the fields of this record directly.
*/
export record RequestMsgData {
_wagiEnv: Map.Map<String, String>,
_params: Map.Map<String, String>,
_query: Map.Map<String, OneOrMany<String>>,
}
/**
* Represents HTTP response statuses.
*/
export enum Status {
// 1XX
Continue,
SwitchingProtocols,
// 2XX
HttpOk,
Created,
Accepted,
NonAuthoritativeInformation,
NoContent,
ResetContent,
ParialContent,
// 3XX
MultipleChoices,
MovedPermanently,
Found,
SeeOther,
NotModified,
TemporaryRedirect,
PermanentRedirect,
// 4XX
BadRequest,
Unauthorized,
PaymentRequired,
Forbidden,
NotFound,
MethodNotAllowed,
NotAcceptable,
ProxyAuthenticationRequired,
RequestTimeout,
Conflict,
Gone,
LengthRequired,
PreconditionFailed,
PayloadTooLarge,
UriTooLong,
UnsupportedMediaType,
RangeNotSatisfiable,
ExpectationFailed,
ImATeapot,
MisdirectedRequest,
TooEarly,
UpgradeRequired,
PrecoditionRequired,
TooManyRequests,
RequestHeaderFieldsTooLarge,
UnavailableForLegalReasons,
// 5XX
InternalServerError,
NotImplemented,
BadGateway,
ServiceUnavailable,
GatewayTimeout,
HttpVersionNotSupported,
VariantAlsoNegotiates,
NotExtended,
NetworkAuthenticationRequired,
// arbitrary status
Status(Number),
}
/**
* Represents response-specific message data (this simply contains data
* injected into `Message<a>` to make `Response` as `Message<ResponseMsgData>`).
* Typically you should not access the fields of this record directly.
*/
export record ResponseMsgData {
_status: Status,
}
/**
* Opaque polymorphic representation of an HTTP message (concretely instanced
* by `Request` and `Response` types). Typically you should not access the
* fields of this record directly.
*/
export record Message<a> {
_message: a,
_headers: Map.Map<String, String>,
_body: String,
_variables: Map.Map<String, Bytes>,
}
/**
* Represents an HTTP request.
*/
export type Request = Message<RequestMsgData>
/**
* Represents an HTTP response.
*/
export type Response = Message<ResponseMsgData>
/**
* Represents an HTTP request handler which processes a request and returns a response.
*/
export type RequestHandler = Request -> Response
/**
* Represents an HTTP middleware, which sits between the client and base request handler.
*/
export type Middleware = RequestHandler -> RequestHandler
// test-export
export enum RequestMethods {
Methods(List<Method>),
All,
}
/**
* Represents a route on the server with a request handler attached to it.
*/
export record Route {
path: String,
routeHandler: RouteHandler,
},
enum RouteHandler {
Endpoint(RequestMethods, RequestHandler),
Scope(Middleware, List<Route>),
}
/**
* Represents possible `Err` reasons for why a variable's value was not read.
*
* `NotSet` indicates that a variable with the given name does not exist
*
* `DeserializationError` indicates that the variable was unable to be
* deserialized properly. The attached `String` gives the error reason
*/
export enum GetVariableError {
NotSet,
DeserializationError(String),
}
/**
* Represents the result of fetching a message variable. A `Result` with an
* `Ok` variant containing the value or `GetVariableError` `Err` variant.
*/
export type Variable<a> = Result<a, GetVariableError>
/**
* Represents an option to apply globally to the server.
*
* `NotFoundHandler` can be used to define a custom 404 Not Found handler
* when a route is not matched.
*
* `MethodNotAllowedHandler` can be used to defined a custom 405 method
* Not Allowed handler for cases of method mismatches.
*/
export enum ServerOption {
NotFoundHandler(RequestHandler),
MethodNotAllowedHandler((List<Method>, Request) -> Response),
}
/**
* @section Utilities: Miscellaneous utility functions.
*/
let genericErrMsg = "make sure you are running in a properly configured WAGI environment"
let failWithMsg = msg => fail "ERROR " ++ msg ++ "; " ++ genericErrMsg
let failWithMsgWithErr = (msg, err) =>
fail "ERROR " ++
msg ++
"; " ++
genericErrMsg ++
"; err " ++
toString(err)
/**
* Writes a message to the WAGI log file.
*
* @param val: The value to write out to the log
*/
export let log = val => {
ignore(File.fdWrite(File.stderr, toString(val) ++ "\n"))
}
/**
* Utility function to combine multiple middlewares into one function.
*
* @param mws: The middlewares to combine
* @returns A single middleware function, chaining the first middleware in the list down to the last
*/
export let middlewares: List<Middleware> -> Middleware = mws => handler => {
List.reduceRight((mw, handler) => mw(handler), handler, mws)
}
// credit to https://github.com/deislabs/wagi-fileserver for the media types
let mediaTypes = Map.fromList(
[
("txt", "text/plain"),
("md", "text/plain"),
("mdown", "text/plain"),
("htm", "text/html"),
("html", "text/html"),
("xhtml", "application/xhtml+xml"),
("xml", "application/xml"),
("css", "text/css"),
("ics", "text/calendar"),
("json", "application/json"),
("jsonld", "application/ld+json"),
("toml", "application/toml"),
("yaml", "application/yaml"),
("js", "text/javascript"),
("mjs", "text/javascript"),
("wasm", "application/wasm"),
("csv", "text/csv"),
("sh", "application/x-sh"),
("apng", "image/apng"),
("avif", "image/avif"),
("png", "image/png"),
("png", "image/png"),
("jpg", "image/jpeg"),
("jpeg", "image/jpeg"),
("pjpeg", "image/jpeg"),
("pjp", "image/jpeg"),
("jfif", "image/jpeg"),
("gif", "image/gif"),
("tif", "image/tiff"),
("tiff", "image/tiff"),
("webp", "image/webp"),
("svg", "image/svg+xml"),
("bmp", "image/bmp"),
("ico", "image/vnd.microsoft.icon"),
("aac", "audio/aac"),
("avi", "video/x-msvideo"),
("wav", "audio/wave"),
("webm", "video/webm"),
("mp3", "audio/mpeg"),
("mp4", "video/mp4"),
("mpeg", "video/mpeg"),
("oga", "audio/ogg"),
("ogv", "video/ogg"),
("ogx", "application/ogg"),
("ts", "video/mp2t"),
("bz2", "application/x-bzip2"),
("tbz", "application/x-bzip2"),
("tbz2", "application/x-bzip2"),
("gz", "application/gzip"),
("rar", "application/vnd.rar"),
("tar", "text/x-tar"),
("tgz", "application/gzip"),
("jar", "application/java-archive"),
("mpkg", "application/vnd.apple.installer+xml"),
("zip", "application/zip"),
("7z", "application/x-7z-compressed"),
("azw", "application/vnd.amazon.ebook"),
("bin", "application/octet-stream"),
("doc", "application/msword"),
(
"docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
),
("epub", "application/epub+zip"),
("odp", "application/vnd.oasis.opendocument.presentation"),
("ods", "application/vnd.oasis.opendocument.spreadsheet"),
("odt", "application/vnd.oasis.opendocument.text"),
("pdf", "application/pdf"),
("ppt", "application/vnd.ms-powerpoint"),
(
"pptx",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
),
("rtf", "application/rtf"),
("vsd", "application/vnd.visio"),
("xls", "application/vnd.ms-excel"),
(
"xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
),
("eot", "application/vnd.ms-fontobject"),
("otf", "font/otf"),
("ttf", "font/ttf"),
("woff", "font/woff"),
("woff2", "font/woff2"),
]
)
/**
* Guesses the MIME type of a media file by its filename extension.
*
* @param fileName: The filename to guess the MIME type of
* @returns A MIME type string for the filename
*/
export let guessMimeType = fileName => {
let default = "application/octet-stream"
match (String.lastIndexOf(".", fileName)) {
Some(i) => {
let extension = String.slice(i + 1, String.length(fileName), fileName)
Option.unwrapWithDefault(default, Map.get(extension, mediaTypes))
},
None => default,
}
}
/**
* Splits a map containing `OneOrMany` values into a list of key-value pairs;
* an element is added for each value of `Vals` for a key.
*
* @param map: The map with `OneOrMany` values to inspect
* @returns A list of key-value pairs representing the map
*/
export let splitOneOrManyMap = map => {
let vals = List.flatMap(((key, val)) => {
match (val) {
Val(val) => [(key, val)],
Vals(vals) => List.map(val => (key, val), vals),
}
}, Map.toList(map))
List.sort(compare, vals)
}
/**
* Joins a list of key-value pairs into a map of `OneOrMany` values, where
* multiple values corresponding to the same key are collated into the same
* `Vals` variant.
*
* @param map: The key-value pairs list to inspect
* @returns A map representing the list of pairs
*/
export let joinOneOrManyMap = list => {
let valMap = Map.make()
List.forEach(((key, val)) => {
let val = match (Map.get(key, valMap)) {
None => Val(val),
Some(Val(currVal)) => Vals([currVal, val]),
Some(Vals(currVals)) => Vals(List.append(currVals, [val])),
}
Map.set(key, val, valMap)
}, list)
valMap
}
let replacePatternsWith = (str, re, replace) => {
let strLen = String.length(str)
let matchPositions = List.map((reMatch: Regex.MatchResult) =>
Option.unwrap(reMatch.groupPosition(0)), Regex.findAll(re, str))
let parts = List.zipWith(
((_, prevEnd), (currBegin, currEnd)) => {
let before = String.slice(prevEnd, currBegin, str)
let matched = String.slice(currBegin, currEnd, str)
before ++ (if (matched != "") replace(matched) else "")
},
[(0, 0), ...matchPositions],
List.append(matchPositions, [(strLen, strLen)])
)
List.join("", parts)
}
let toHexString = num => {
match (num) {
10 => "A",
11 => "B",
12 => "C",
13 => "D",
14 => "E",
15 => "F",
_ => toString(num),
}
}
let toEncodeRegex = Result.unwrap(Regex.make("[:/?#\\[\\]@!$&'()*+,;=% ]"))
let pctEncodedRegex = Result.unwrap(Regex.make("%[0-9A-Fa-f]{2}"))
/**
* Percent-encodes RFC 3986 reserved url characters (and space) in a string.
*
* @param str: The string to encode
* @returns A percent-encoding of the given string
*/
export let percentEncode = str => {
let replaceFn = c => {
let code = String.charCodeAt(0, c)
let firstHex = code >> 4
let secondHex = code % 16
"%" ++ toString(firstHex) ++ toHexString(secondHex)
}
replacePatternsWith(str, toEncodeRegex, replaceFn)
}
/**
* Decodes any percent-encoded characters in a string.
*
* @param str: The string to decode
* @returns A decoding of the given percent-encoded string
*/
export let percentDecode = str => {
let replaceFn = pctEncoding => {
// truncate percent
let hex = String.slice(1, 3, pctEncoding)
let code = Result.unwrap(Number.parseInt(hex, 16))
Char.toString(Char.fromCode(code))
}
replacePatternsWith(str, pctEncodedRegex, replaceFn)
}
/**
* Url-encodes a map of OneOrMany values into a single string.
*
* @param urlVals: A map of OneOrMany values to url-encode
* @returns A url-encoded string of the values
*/
export let urlEncode = urlVals => {
let list = splitOneOrManyMap(urlVals)
let parts = List.map(((key, val)) => {
percentEncode(key) ++ "=" ++ percentEncode(val)
}, list)
List.join("&", parts)
}
let urlDecodeParts = parts => {
let partKeyVals = List.map(part => {
match (String.indexOf("=", part)) {
// some parts may only have a key, set value to empty string in this case
None => (part, ""),
Some(i) => {
let name = String.slice(0, i, part)
let val = String.slice(i + 1, String.length(part), part)
(percentDecode(name), percentDecode(val))
},
}
}, parts)
joinOneOrManyMap(partKeyVals)
}
/**
* Decodes a url-encoded string into a map of OneOrMany values.
*
* @param str: A url-encoded string
* @returns A map of OneOrMany values containing the values of the encoded string
*/
export let urlDecode = str => {
let parts = Array.toList(String.split("&", str))
urlDecodeParts(parts)
}
let methodPairs = [
(Get, "GET"),
(Post, "POST"),
(Put, "PUT"),
(Delete, "DELETE"),
(Head, "HEAD"),
(Patch, "PATCH"),
(Options, "OPTIONS"),
(Trace, "TRACE"),
]
let methodToStringMap = Map.fromList(methodPairs)
let stringToMethodMap = Map.fromList(List.map(((a, b)) => (b, a), methodPairs))
/**
* Converts a string to an HTTP `Method`.
*
* @param str: The string to convert to a `Method`
* @returns A `Method` representing the string
*
* @example Hopper.stringToMethod("GET") // Method.Get
*/
export let stringToMethod = str => {
match (Map.get(str, stringToMethodMap)) {
Some(method) => method,
None => Method(str),
}
}
/**
* Converts a `Method` to a string describing the method.
*
* @param method: `Method` to stringify
* @returns A string representing the `Method`
*/
export let methodToString = method => {
match (method) {
Method(str) => str,
_ => Option.unwrap(Map.get(method, methodToStringMap)),
}
}
let statusPairs = [
(Continue, 100),
(SwitchingProtocols, 101),
(HttpOk, 200),
(Created, 201),
(Accepted, 202),
(NonAuthoritativeInformation, 203),
(NoContent, 204),
(ResetContent, 205),
(ParialContent, 206),
(MultipleChoices, 300),
(MovedPermanently, 301),
(Found, 302),
(SeeOther, 303),
(NotModified, 304),
(TemporaryRedirect, 307),
(PermanentRedirect, 308),
(BadRequest, 400),
(Unauthorized, 401),
(PaymentRequired, 402),
(Forbidden, 403),
(NotFound, 404),
(MethodNotAllowed, 405),
(NotAcceptable, 406),
(ProxyAuthenticationRequired, 407),
(RequestTimeout, 408),
(Conflict, 409),
(Gone, 410),
(LengthRequired, 411),
(PreconditionFailed, 412),
(PayloadTooLarge, 413),
(UriTooLong, 414),
(UnsupportedMediaType, 415),
(RangeNotSatisfiable, 416),
(ExpectationFailed, 417),
(ImATeapot, 418),
(MisdirectedRequest, 421),
(TooEarly, 425),
(UpgradeRequired, 426),
(PrecoditionRequired, 428),
(TooManyRequests, 429),
(RequestHeaderFieldsTooLarge, 431),
(UnavailableForLegalReasons, 451),
(InternalServerError, 500),
(NotImplemented, 501),
(BadGateway, 502),
(ServiceUnavailable, 503),
(GatewayTimeout, 504),
(HttpVersionNotSupported, 505),
(VariantAlsoNegotiates, 506),
(NotExtended, 510),
(NetworkAuthenticationRequired, 511),
]
let statusToCodeMap = Map.fromList(statusPairs)
let codeToStatusMap = Map.fromList(List.map(((a, b)) => (b, a), statusPairs))
/**
* Converts a status code to its corresponding status.
*
* @param status: A status code to convert to a `Status`
* @returns A status representing the given code
*/
export let codeToStatus = code => {
match (Map.get(code, codeToStatusMap)) {
Some(status) => status,
_ => Status(code),
}
}
/**
* Converts a response status to its corresponding status code.
*
* @param status: A `Status` to get the status code of
* @returns A status code for the response status
*/
export let statusToCode = status => {
match (status) {
Status(status) => status,
_ => Option.unwrap(Map.get(status, statusToCodeMap)),
}
}
let isStatusType = beginRange => status => {
let code = statusToCode(status)
let endRange = beginRange + 100
code >= beginRange && code < endRange
}
/**
* Determines if an HTTP status is informational i.e. has a 1XX code.
*
* @param status: The status to examine
* @returns `true` if the status has a 1XX status code or `false` otherwise
*/
export let isInformationalStatus = isStatusType(100)
/**
* Determines if an HTTP status is successful i.e. has a 2XX code.
*
* @param status: The status to examine
* @returns `true` if the status has a 2XX status code or `false` otherwise
*/
export let isSuccessfulStatus = isStatusType(200)
/**
* Determines if an HTTP status is a redirection i.e. has a 3XX code.
*
* @param status: The status to examine
* @returns `true` if the status has a 3XX status code or `false` otherwise
*/
export let isRedirectionStatus = isStatusType(300)
/**
* Determines if an HTTP status is a client error i.e. has a 4XX code.
*
* @param status: The status to examine
* @returns `true` if the status has a 4XX status code or `false` otherwise
*/
export let isClientErrorStatus = isStatusType(400)
/**
* Determines if an HTTP status is a server error i.e. has a 5XX code.
*
* @param status: The status to examine
* @returns `true` if the status has a 5XX status code or `false` otherwise
*/
export let isServerErrorStatus = isStatusType(500)
/**
* @section Messages: Functions that can be used on both requests and responses
*/
let toLower = str => {
String.implode(
Array.map(c => {
let code = Char.code(c)
if (code >= 65 && code <= 90) Char.fromCode(code + 32) else c
}, String.explode(str))
)
}
let headerNormed = str => {
let chars = String.explode(toLower(str))
String.implode(Array.map(c => if (c == '_') '-' else c, chars))
}
/**
* Fetches a header from the message.
*
* @param key: The header to request
* @param msg: The request or response to examine
* @returns The header value requested
*/
export let header = (key, msg) => {
let key = headerNormed(key)
let headersList = Map.toList(msg._headers)
let header = List.find(((k, val)) => headerNormed(k) == key, headersList)
match (header) {
Some((_, val)) => Some(val),
None => None,
}
}
/**
* Fetches headers on a message.
*
* @param msg: The request or response to examine
* @returns The headers on the request or response, with header names all in lowercase
*/
export let headers = msg => {
let headersList = Map.toList(msg._headers)
Map.fromList(List.map(((key, val)) => (headerNormed(key), val), headersList))
}
/**
* Fetches the message body as a string.
*
* @param msg: The request or response to examine
* @returns The body as a string
*/
export let body = msg => {
msg._body
}
/**
* Sets a variable on a message to a new arbitrary value.
*
* @param key: The variable to set
* @param value: The new value to give the variable
* @param msg: The message to attach the variable to
*/
export let setVariable = (key, value, msg) => {
Map.set(key, Marshal.marshal(value), msg._variables)
}
/**
* Fetches the value of a variable set on a message. The result of this
* function should be explicitly typed.
*
* @param key: The variable to fetch
* @param msg: The message to inspect
* @returns The value of the variable requested
*/
export let variable = (key, msg) => {
match (Map.get(key, msg._variables)) {
Some(val) => {
match (Marshal.unmarshal(val)) {
Ok(val) => Ok(val),
Err(err) => Err(DeserializationError(err)),
}
},
None => Err(NotSet),
}: Variable<a>
}
/**
* @section Requests: Functions related to handling incoming requests.
*/
/**
* Fetches a URL query parameter with the given name from a request.
*
* @param key: The name of the parameter to fetch the value of
* @param req: The request to fetch the query parameter from
* @returns The value of the query parameter with the given name
*/
export let query = (key, req: Request) => {
Option.map(val => match (val) {
Val(val) => val,
Vals([val, ..._]) => val,
_ => fail "",
}, Map.get(key, req._message._query))
}
/**
* Fetches a list of values associated with the URL query parameter with the
* given name.
*
* @param key: The name of the parameter to fetch the value of
* @param req: The request to fetch the query parameters from
* @returns The list of values of the query parameter with the given name
*/
export let queryList = (key, req: Request) => {
match (Map.get(key, req._message._query)) {
None => [],
Some(Val(val)) => [val],
Some(Vals(vals)) => vals,
}
}
/**
* Fetches all URL query parameters.
*
* @param req: The request to fetch the query parameters from
* @returns All query parameters given
*/
export let queries = (req: Request) => {
req._message._query
}
let getPath = wagiEnv => {
match (Map.get("PATH_INFO", wagiEnv)) {
Some(val) => val,
None => failWithMsg("Did not find \"PATH_INFO\" in environment"),
}
}
/**
* Fetches the full path from the requested URL.
*
* @param req: The request to examine
* @returns The full path requested
*/
export let path = (req: Request) => {
getPath(req._message._wagiEnv)
}
/**
* Fetches a path parameter from the request.
*
* @param key: The path parameter to fetch
* @param req: The request to examine
* @returns The path parameter requested
*/
export let param = (key, req: Request) => {
let failMsg = "URL path param " ++ key ++ " does not exist on route"
Option.expect(failMsg, Map.get(key, req._message._params))
}
let getReqMethod = wagiEnv => {
match (Map.get("REQUEST_METHOD", wagiEnv)) {
Some(reqMethod) => stringToMethod(reqMethod),
_ => failWithMsg("Did not find \"REQUEST_METHOD\" in request"),
}
}
/**
* Fetches the HTTP method of the request.
*
* @param req: The request to examine
* @returns The HTTP method of the request.
*/
export let method = (req: Request) => {
getReqMethod(req._message._wagiEnv)
}
/**
* @section Responses: Functions related to handling outgoing responses.
*/
/**
* Creates a new `Response` with a status, headers, and body.
*
* @param status: The desired HTTP status
* @param headers: The desired HTTP headers
* @param body: The body string to create the `Response` with
* @returns A new `Response` with the given values
*/
export let response = (status, headers, body) => {
{
_message: { _status: status, },
_variables: Map.make(),
_headers: headers,
_body: body,
}: Response
}
let ctHeader = contentType => Map.fromList([("Content-Type", contentType)])
/**
* Creates a new OK `Response` with a text body and `"text/plain"` Content-Type.
*
* @param body: The text body to create the `Response` with
* @returns A new text `Response`
*/
export let text = body => response(HttpOk, ctHeader("text/plain"), body)
/**
* Creates a new OK `Response` with a JSON string body and `"application/json"` Content-Type.
*
* Note: the argument type will likely be changed to a more friendly JSON
* representation once https://github.com/grain-lang/grain/pull/1133 gets
* merged.
*
* @param body: The JSON body to create the `Response` with
* @returns A new JSON `Response`
*/
export let json = body => response(HttpOk, ctHeader("application/json"), body)
/**
* Creates a new OK `Response` with the specified content type.
*
* @param contentType: The Content-Type to set for the `Response`
* @param body: The body of the response
* @returns A new `Response` with the given content type
*/
export let contentType = (contentType, body) =>
response(HttpOk, ctHeader(contentType), body)
/**
* Creates a new `Response` from an existing response, but with the response status code changed.
*
* @param status: The desired HTTP status
* @param res: The base response
* @returns A new `Response` with the desired HTTP status
*/
export let newStatus = (status, res: Response) => {
let { _headers, _body, _ } = res
response(status, _headers, _body)
}
/**
* Creates a new `Response` from an existing response, but with the response headers changed.
*
* @param headers: The desired HTTP headers
* @param res: The base response
* @returns A new `Response` with the desired HTTP headers
*/
export let newHeaders = (headers, res: Response) => {
let { _message: { _status }, _body, _ } = res
response(_status, headers, _body)
}
/**
* Creates a new `Response` from an existing response, but with the response body changed.
*
* @param body: The desired HTTP body
* @param res: The base response
* @returns A new `Response` with the desired HTTP body
*/
export let newBody = (body, res: Response) => {
let { _message: { _status }, _headers, _ } = res
response(_status, _headers, body)
}
/**
* Creates a new `Response` from a static file on the server at the given path.
*
* @param filePath: The path of the file to search for on the server
* @returns A new "OK" `Response` if the file is found, or a "Not Found" reponse otherwise
*/
export let file = filePath => {
let result = File.pathOpen(
File.pwdfd,
[],
filePath,
[],
[File.FdFilestats, File.FdRead],
[],
[]
)
match (result) {
Err(_) => response(NotFound, ctHeader("text/plain"), "File Not Found"),
Ok(fd) => {
let stats = Result.unwrap(File.fdFilestats(fd))
let fileSize = Int64.toNumber(stats.size)
let (contents, _) = Result.unwrap(File.fdRead(fd, fileSize))
File.fdClose(fd)
response(HttpOk, ctHeader(guessMimeType(filePath)), contents)
},
}
}
/**
* Creates a new redirection `Response` to another route on the server.
*
* @param path: The local path to redirect to
* @param req: The incoming `Request`
* @returns A new redirection `Response` with status code "302 Found"
*/
export let redirectLocal = (path, req: Request) => {
let item = key => Option.unwrap(Map.get(key, req._message._wagiEnv))
let isHttps = String.startsWith("https://", item("X_FULL_URL"))
let protocol = if (isHttps) "https://" else "http://"
let baseUrl = protocol ++ item("SERVER_NAME") ++ ":" ++ item("SERVER_PORT")
response(Found, Map.fromList([("Location", baseUrl ++ path)]), "")
}
/**
* Creates a new redirection `Response` to an arbitrary URL.
*
* @param url: The URL to redirect to
* @returns A new redirection `Response` with status code "302 Found"
*/
export let redirectExternal = url =>
response(Found, Map.fromList([("Location", url)]), "")
/**
* Fetches the HTTP response status of a response.
*
* @param res: The response to examine
* @returns The status of the response
*/
export let status = (res: Response) => {
res._message._status
}