about summary refs log tree commit diff
path: root/usth/ICT3.2/prac/5/3.patch
blob: 98081e22f18cd26f21edd33aa70b1204ad592059 (plain) (blame)
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
From ede9ffb8df2b225fb2deaea958f9cc126f3352b6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Nguy=E1=BB=85n=20Gia=20Phong?= <mcsinyx@disroot.org>
Date: Sun, 11 Oct 2020 21:37:18 +0700
Subject: [PATCH] Implement a simple RESTful API

---
 app/Config/Routes.php    |  2 +-
 app/Controllers/Home.php | 21 ++++++++++++++++-----
 2 files changed, 17 insertions(+), 6 deletions(-)

diff --git a/app/Config/Routes.php b/app/Config/Routes.php
index 56839ca..312d31e 100644
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -30,7 +30,7 @@ $routes->setAutoRoute(true);
 
 // We get a performance increase by specifying the default
 // route since we don't have to scan directories.
-$routes->get('/', 'Home::index');
+$routes->get('/(:any)', 'Home::index/$1');
 
 /**
  * --------------------------------------------------------------------
diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php
index 8798cdd..3c80328 100644
--- a/app/Controllers/Home.php
+++ b/app/Controllers/Home.php
@@ -1,12 +1,23 @@
 <?php namespace App\Controllers;
 
+function data($uri)
+{
+	return dirname(dirname(dirname(__DIR__))) . '/data/' . $uri . '.json';
+}
+
 class Home extends BaseController
 {
-	public function index()
+	private $supported = ['<p>/user</p>', '<p>/user/{userId}/post</p>',
+	                      '<p>/post</p>', '<p>/post/{postId}/comment</p>'];
+
+	public function index($uri)
 	{
-		return view('welcome_message');
+		if (!file_exists($file = data($uri))) {
+			echo "<p>Supported URIs:</p>\n";
+			return join("\n", $this->supported);
+		}
+		$this->response->setHeader('Access-Control-Allow-Origin', '*');
+		$this->response->setContentType('application/json');
+		readfile($file);
 	}
-
-	//--------------------------------------------------------------------
-
 }
-- 
2.28.0