JsonApi.vala 20 KB

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