JsonApi.vala 19 KB

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