JsonApi.vala 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. /**
  5. * JsonApi Example
  6. *
  7. * Demonstrates building a JSON API with proper headers.
  8. * Uses Invercargill data structures for data management and
  9. * Enumerable for JSON serialization.
  10. */
  11. void main() {
  12. var router = new Router();
  13. var server = new Server(8085, router);
  14. // API root
  15. router.map_func("/api", (context) => {
  16. var json = @"{
  17. \"name\": \"Astralis JSON API\",
  18. \"version\": \"1.0.0\",
  19. \"endpoints\": {
  20. \"users\": \"/api/users\",
  21. \"posts\": \"/api/posts\",
  22. \"comments\": \"/api/comments\",
  23. \"stats\": \"/api/stats\"
  24. }
  25. }";
  26. return new BufferedHttpResult.from_string(
  27. json,
  28. StatusCode.OK,
  29. get_json_headers()
  30. );
  31. });
  32. // List all users
  33. router.map_func("/api/users", (context) => {
  34. var users = get_users();
  35. var json_parts = new Series<string>();
  36. json_parts.add_start(@"{ \"users\": [");
  37. bool first = true;
  38. users.to_immutable_buffer().iterate((user) => {
  39. if (!first) json_parts.add_start(", ");
  40. json_parts.add_start(user.to_json());
  41. first = false;
  42. });
  43. var user_count = users.to_immutable_buffer().count();
  44. json_parts.add("], ");
  45. json_parts.add("\"count\": " + user_count.to_string() + " }");
  46. var json_string = json_parts.to_immutable_buffer()
  47. .aggregate<string>("", (acc, s) => acc + s);
  48. return new BufferedHttpResult.from_string(
  49. json_string,
  50. StatusCode.OK,
  51. get_json_headers()
  52. );
  53. });
  54. // Get user by ID
  55. router.map_func("/api/users/", (context) => {
  56. var components = context.request.path_components.to_vector();
  57. if (components.count() < 3) {
  58. return error_response("User ID required");
  59. }
  60. var id = int.parse(components[2]);
  61. var user = find_user(id);
  62. if (user == null) {
  63. return error_response(@"User with ID $id not found", StatusCode.NOT_FOUND);
  64. }
  65. return new BufferedHttpResult.from_string(
  66. user.to_json(),
  67. StatusCode.OK,
  68. get_json_headers()
  69. );
  70. });
  71. // List all posts
  72. router.map_func("/api/posts", (context) => {
  73. var posts = get_posts();
  74. // Filter by user_id if provided
  75. var user_id_param = context.request.get_query("user_id");
  76. if (user_id_param != null) {
  77. var user_id = int.parse(user_id_param);
  78. posts = posts.to_immutable_buffer()
  79. .where(p => p.user_id == user_id)
  80. .to_series();
  81. }
  82. var json_parts = new Series<string>();
  83. json_parts.add_start(@"{ \"posts\": [");
  84. bool first = true;
  85. posts.to_immutable_buffer().iterate((post) => {
  86. if (!first) json_parts.add_start(", ");
  87. json_parts.add_start(post.to_json());
  88. first = false;
  89. });
  90. var post_count = posts.to_immutable_buffer().count();
  91. json_parts.add("], ");
  92. json_parts.add("\"count\": " + post_count.to_string() + " }");
  93. var json_string = json_parts.to_immutable_buffer()
  94. .aggregate<string>("", (acc, s) => acc + s);
  95. return new BufferedHttpResult.from_string(
  96. json_string,
  97. StatusCode.OK,
  98. get_json_headers()
  99. );
  100. });
  101. // Get post by ID
  102. router.map_func("/api/posts/", (context) => {
  103. var components = context.request.path_components.to_vector();
  104. if (components.count() < 3) {
  105. return error_response("Post ID required");
  106. }
  107. var id = int.parse(components[2]);
  108. var post = find_post(id);
  109. if (post == null) {
  110. return error_response(@"Post with ID $id not found", StatusCode.NOT_FOUND);
  111. }
  112. // Include user and comments in response
  113. var user = find_user(post.user_id);
  114. var comments = get_comments_for_post(id);
  115. var json_parts = new Series<string>();
  116. json_parts.add_start(@"{ \"post\": $(post.to_json()), ");
  117. if (user != null) {
  118. json_parts.add_start("\"user\": " + user.to_json() + ", ");
  119. } else {
  120. json_parts.add_start("\"user\": null, ");
  121. }
  122. json_parts.add_start("\"comments\": [");
  123. bool first = true;
  124. comments.to_immutable_buffer().iterate((comment) => {
  125. if (!first) json_parts.add_start(", ");
  126. json_parts.add_start(comment.to_json());
  127. first = false;
  128. });
  129. json_parts.add("] }");
  130. var json_string = json_parts.to_immutable_buffer()
  131. .aggregate<string>("", (acc, s) => acc + s);
  132. return new BufferedHttpResult.from_string(
  133. json_string,
  134. StatusCode.OK,
  135. get_json_headers()
  136. );
  137. });
  138. // List all comments
  139. router.map_func("/api/comments", (context) => {
  140. var comments = get_comments();
  141. // Filter by post_id if provided
  142. var post_id_param = context.request.get_query("post_id");
  143. if (post_id_param != null) {
  144. var post_id = int.parse(post_id_param);
  145. comments = comments.to_immutable_buffer()
  146. .where(c => c.post_id == post_id)
  147. .to_series();
  148. }
  149. var json_parts = new Series<string>();
  150. json_parts.add_start(@"{ \"comments\": [");
  151. bool first = true;
  152. comments.to_immutable_buffer().iterate((comment) => {
  153. if (!first) json_parts.add_start(", ");
  154. json_parts.add_start(comment.to_json());
  155. first = false;
  156. });
  157. var comment_count = comments.to_immutable_buffer().count();
  158. json_parts.add("], ");
  159. json_parts.add("\"count\": " + comment_count.to_string() + " }");
  160. var json_string = json_parts.to_immutable_buffer()
  161. .aggregate<string>("", (acc, s) => acc + s);
  162. return new BufferedHttpResult.from_string(
  163. json_string,
  164. StatusCode.OK,
  165. get_json_headers()
  166. );
  167. });
  168. // Get comment by ID
  169. router.map_func("/api/comments/", (context) => {
  170. var components = context.request.path_components.to_vector();
  171. if (components.count() < 3) {
  172. return error_response("Comment ID required");
  173. }
  174. var id = int.parse(components[2]);
  175. var comment = find_comment(id);
  176. if (comment == null) {
  177. return error_response(@"Comment with ID $id not found", StatusCode.NOT_FOUND);
  178. }
  179. return new BufferedHttpResult.from_string(
  180. comment.to_json(),
  181. StatusCode.OK,
  182. get_json_headers()
  183. );
  184. });
  185. // API statistics
  186. router.map_func("/api/stats", (context) => {
  187. var users = get_users();
  188. var posts = get_posts();
  189. var comments = get_comments();
  190. var user_count = users.to_immutable_buffer().count();
  191. var post_count = posts.to_immutable_buffer().count();
  192. var comment_count = comments.to_immutable_buffer().count();
  193. var posts_per_user = post_count / (double)user_count;
  194. var comments_per_post = comment_count / (double)post_count;
  195. var json = @"{
  196. \"users\": $user_count,
  197. \"posts\": $post_count,
  198. \"comments\": $comment_count,
  199. \"posts_per_user\": $posts_per_user,
  200. \"comments_per_post\": $comments_per_post
  201. }";
  202. return new BufferedHttpResult.from_string(
  203. json,
  204. StatusCode.OK,
  205. get_json_headers()
  206. );
  207. });
  208. // Search endpoint
  209. router.map_func("/api/search", (context) => {
  210. var query = context.request.get_query("q");
  211. if (query == null || query == "") {
  212. return error_response("Query parameter 'q' is required");
  213. }
  214. var results = new Series<SearchResult>();
  215. // Search users
  216. get_users().to_immutable_buffer()
  217. .where(u => u.name.down().contains(query.down()))
  218. .iterate((user) => {
  219. results.add_start(new SearchResult("user", user.id.to_string(), user.name));
  220. });
  221. // Search posts
  222. get_posts().to_immutable_buffer()
  223. .where(p => p.title.down().contains(query.down()) || p.content.down().contains(query.down()))
  224. .iterate((post) => {
  225. results.add_start(new SearchResult("post", post.id.to_string(), post.title));
  226. });
  227. var json_parts = new Series<string>();
  228. json_parts.add_start(@"{ \"query\": \"$query\", \"results\": [");
  229. bool first = true;
  230. results.to_immutable_buffer().iterate((result) => {
  231. if (!first) json_parts.add_start(", ");
  232. json_parts.add_start(result.to_json());
  233. first = false;
  234. });
  235. var result_count = results.to_immutable_buffer().count();
  236. json_parts.add("], ");
  237. json_parts.add("\"count\": " + result_count.to_string() + " }");
  238. var json_string = json_parts.to_immutable_buffer()
  239. .aggregate<string>("", (acc, s) => acc + s);
  240. return new BufferedHttpResult.from_string(
  241. json_string,
  242. StatusCode.OK,
  243. get_json_headers()
  244. );
  245. });
  246. // Pagination example
  247. router.map_func("/api/posts/paginated", (context) => {
  248. var page = int.parse(context.request.get_query_or_default("page", "1"));
  249. var per_page = int.parse(context.request.get_query_or_default("per_page", "10"));
  250. var posts = get_posts();
  251. var total = posts.to_immutable_buffer().count();
  252. var total_pages = (total + per_page - 1) / per_page;
  253. // Calculate pagination
  254. var offset = (page - 1) * per_page;
  255. var paginated_posts = posts.to_immutable_buffer()
  256. .skip(offset)
  257. .take(per_page);
  258. var json_parts = new Series<string>();
  259. json_parts.add_start(@"{ \"page\": $page, \"per_page\": $per_page, \"total\": $total, \"total_pages\": $total_pages, \"posts\": [");
  260. bool first = true;
  261. paginated_posts.iterate((post) => {
  262. if (!first) json_parts.add_start(", ");
  263. json_parts.add_start(post.to_json());
  264. first = false;
  265. });
  266. json_parts.add("] }");
  267. var json_string = json_parts.to_immutable_buffer()
  268. .aggregate<string>("", (acc, s) => acc + s);
  269. return new BufferedHttpResult.from_string(
  270. json_string,
  271. StatusCode.OK,
  272. get_json_headers()
  273. );
  274. });
  275. // Error handling endpoint
  276. router.map_func("/api/error", (context) => {
  277. var error_type = context.request.get_query_or_default("type", "generic");
  278. switch (error_type) {
  279. case "not_found":
  280. return error_response("Resource not found", StatusCode.NOT_FOUND);
  281. case "bad_request":
  282. return error_response("Invalid request parameters", StatusCode.BAD_REQUEST);
  283. case "server_error":
  284. return error_response("Internal server error occurred", StatusCode.INTERNAL_SERVER_ERROR);
  285. default:
  286. return error_response("An error occurred");
  287. }
  288. });
  289. print("JSON API Example Server running on port 8085\n");
  290. print("Try these endpoints:\n");
  291. print(" - http://localhost:8085/api\n");
  292. print(" - http://localhost:8085/api/users\n");
  293. print(" - http://localhost:8085/api/users/1\n");
  294. print(" - http://localhost:8085/api/posts\n");
  295. print(" - http://localhost:8085/api/posts?user_id=1\n");
  296. print(" - http://localhost:8085/api/posts/1\n");
  297. print(" - http://localhost:8085/api/comments\n");
  298. print(" - http://localhost:8085/api/comments?post_id=1\n");
  299. print(" - http://localhost:8085/api/stats\n");
  300. print(" - http://localhost:8085/api/search?q=test\n");
  301. print(" - http://localhost:8085/api/posts/paginated?page=1&per_page=5\n");
  302. server.run();
  303. }
  304. // Helper functions
  305. Catalogue<string, string> get_json_headers() {
  306. var headers = new Catalogue<string, string>();
  307. headers.add("Content-Type", "application/json");
  308. headers.add("Access-Control-Allow-Origin", "*");
  309. return headers;
  310. }
  311. BufferedHttpResult error_response(string message, StatusCode status = StatusCode.BAD_REQUEST) {
  312. var json = @"{ \"error\": \"$message\" }";
  313. return new BufferedHttpResult.from_string(
  314. json,
  315. status,
  316. get_json_headers()
  317. );
  318. }
  319. // Data models and storage
  320. class User {
  321. public int id { get; private set; }
  322. public string name { get; private set; }
  323. public string email { get; private set; }
  324. public User(int id, string name, string email) {
  325. this.id = id;
  326. this.name = name;
  327. this.email = email;
  328. }
  329. public string to_json() {
  330. return @"{ \"id\": $id, \"name\": \"$name\", \"email\": \"$email\" }";
  331. }
  332. }
  333. class Post {
  334. public int id { get; private set; }
  335. public int user_id { get; private set; }
  336. public string title { get; private set; }
  337. public string content { get; private set; }
  338. public Post(int id, int user_id, string title, string content) {
  339. this.id = id;
  340. this.user_id = user_id;
  341. this.title = title;
  342. this.content = content;
  343. }
  344. public string to_json() {
  345. var escaped_content = content.replace("\"", "\\\"").replace("\n", "\\n");
  346. return @"{ \"id\": $id, \"user_id\": $user_id, \"title\": \"$title\", \"content\": \"$escaped_content\" }";
  347. }
  348. }
  349. class Comment {
  350. public int id { get; private set; }
  351. public int post_id { get; private set; }
  352. public string author { get; private set; }
  353. public string text { get; private set; }
  354. public Comment(int id, int post_id, string author, string text) {
  355. this.id = id;
  356. this.post_id = post_id;
  357. this.author = author;
  358. this.text = text;
  359. }
  360. public string to_json() {
  361. var escaped_text = text.replace("\"", "\\\"").replace("\n", "\\n");
  362. return @"{ \"id\": $id, \"post_id\": $post_id, \"author\": \"$author\", \"text\": \"$escaped_text\" }";
  363. }
  364. }
  365. class SearchResult {
  366. public string result_type { get; private set; }
  367. public string id { get; private set; }
  368. public string title { get; private set; }
  369. public SearchResult(string result_type, string id, string title) {
  370. this.result_type = result_type;
  371. this.id = id;
  372. this.title = title;
  373. }
  374. public string to_json() {
  375. return @"{ \"type\": \"$result_type\", \"id\": \"$id\", \"title\": \"$title\" }";
  376. }
  377. }
  378. // Data storage functions
  379. Series<User> get_users() {
  380. var users = new Series<User>();
  381. users.add_start(new User(1, "Alice Johnson", "alice@example.com"));
  382. users.add_start(new User(2, "Bob Smith", "bob@example.com"));
  383. users.add_start(new User(3, "Charlie Brown", "charlie@example.com"));
  384. users.add_start(new User(4, "Diana Prince", "diana@example.com"));
  385. users.add_start(new User(5, "Eve Davis", "eve@example.com"));
  386. return users;
  387. }
  388. Series<Post> get_posts() {
  389. var posts = new Series<Post>();
  390. posts.add_start(new Post(1, 1, "First Post", "This is my first post!"));
  391. posts.add_start(new Post(2, 1, "Second Post", "Another day, another post."));
  392. posts.add_start(new Post(3, 2, "Hello World", "Just saying hello to everyone."));
  393. posts.add_start(new Post(4, 3, "Vala Programming", "Vala is a great programming language."));
  394. posts.add_start(new Post(5, 4, "Web Development", "Building web applications is fun."));
  395. posts.add_start(new Post(6, 5, "API Design", "RESTful APIs are the way to go."));
  396. return posts;
  397. }
  398. Series<Comment> get_comments() {
  399. var comments = new Series<Comment>();
  400. comments.add_start(new Comment(1, 1, "Bob", "Great first post!"));
  401. comments.add_start(new Comment(2, 1, "Charlie", "Welcome to the platform!"));
  402. comments.add_start(new Comment(3, 2, "Alice", "Keep posting!"));
  403. comments.add_start(new Comment(4, 3, "Alice", "Hello to you too!"));
  404. comments.add_start(new Comment(5, 4, "Bob", "I agree!"));
  405. comments.add_start(new Comment(6, 5, "Charlie", "Good point!"));
  406. return comments;
  407. }
  408. Series<Comment> get_comments_for_post(int post_id) {
  409. return get_comments().to_immutable_buffer()
  410. .where(c => c.post_id == post_id)
  411. .to_series();
  412. }
  413. User? find_user(int id) {
  414. return get_users().to_immutable_buffer()
  415. .first_or_default(u => u.id == id);
  416. }
  417. Post? find_post(int id) {
  418. return get_posts().to_immutable_buffer()
  419. .first_or_default(p => p.id == id);
  420. }
  421. Comment? find_comment(int id) {
  422. return get_comments().to_immutable_buffer()
  423. .first_or_default(c => c.id == id);
  424. }