JsonApi.vala 18 KB

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