-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.hack
More file actions
70 lines (62 loc) · 1.91 KB
/
index.hack
File metadata and controls
70 lines (62 loc) · 1.91 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
// Dependancies
require_once(__DIR__.'/../vendor/hh_autoload.hh');
use type Facebook\HackRouter\{BaseRouter, HttpMethod};
/*
* Parsing Methods
*/
// tuple to store method and route
newtype MethodAndPath = (HttpMethod, string);
// converts string to HttpMethod. Ex: "GET" => HttpMethod::GET
function get_http_method_from_string(string $str) : HttpMethod {
switch ($str) {
case "GET":
return HttpMethod::GET;
case "POST":
return HttpMethod::POST;
default:
// get is generally treated as the default
return HttpMethod::GET;
}
}
// parse the server request to get the path and method
function convert_request_to_path_and_method(array $server) : MethodAndPath {
$method = get_http_method_from_string($server['REQUEST_METHOD']);
$path = $server['REQUEST_URI'];
return tuple($method, $path);
}
/*
* Router and Routes
*/
type TResponder = (function(dict<string, string>):string);
// this class can have any name
final class RESTAPIRouter extends BaseRouter<TResponder> {
<<__Override>>
protected function getRoutes(
): dict<HttpMethod, dict<string, TResponder>> {
return dict [
HttpMethod::GET => dict [
'/' =>
($_params) ==> 'Getting the home page...',
'/example/{example_param}' =>
($params) ==> 'Example Page: accessing, ' . $params['example_param'],
],
HttpMethod::POST => dict [
'/' => ($_params) ==> 'Posting to the home page...',
],
];
}
}
// runs the code
<<__EntryPoint>>
function main(): noreturn {
$router = new RESTAPIRouter();
$method_and_path = convert_request_to_path_and_method($_SERVER);
try {
list($responder, $params) = $router->routeMethodAndPath($method_and_path[0], $method_and_path[1]);
echo $responder(dict($params));
}
catch (Facebook\HackRouter\NotFoundException $ex) {
echo "Route does not exist";
}
exit(0);
}