JsonApi.vala 18 KB

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