| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540 |
- using Astralis;
- using Invercargill;
- using Invercargill.DataStructures;
- /**
- * JsonApi Example
- *
- * Demonstrates building a JSON API with proper headers.
- * Uses Invercargill data structures for data management and
- * Enumerable for JSON serialization.
- */
- // API root handler
- class ApiRootHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var json = @"{
- \"name\": \"Astralis JSON API\",
- \"version\": \"1.0.0\",
- \"endpoints\": {
- \"users\": \"/api/users\",
- \"posts\": \"/api/posts\",
- \"comments\": \"/api/comments\",
- \"stats\": \"/api/stats\"
- }
- }";
-
- return new BufferedHttpResult.from_string(
- json,
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // List all users
- class UsersListHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var users = get_users();
-
- var json_parts = new Series<string>();
- json_parts.add_start(@"{ \"users\": [");
-
- bool first = true;
- users.to_immutable_buffer().iterate((user) => {
- if (!first) json_parts.add_start(", ");
- json_parts.add_start(user.to_json());
- first = false;
- });
-
- var user_count = users.to_immutable_buffer().count();
- json_parts.add("], ");
- json_parts.add("\"count\": " + user_count.to_string() + " }");
-
- var json_string = json_parts.to_immutable_buffer()
- .aggregate<string>("", (acc, s) => acc + s);
-
- return new BufferedHttpResult.from_string(
- json_string,
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // Get user by ID
- class UserByIdHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var id_str = route_context.get_segment("id");
- var id = int.parse(id_str);
- var user = find_user(id);
-
- if (user == null) {
- return error_response(@"User with ID $id not found", StatusCode.NOT_FOUND);
- }
-
- return new BufferedHttpResult.from_string(
- user.to_json(),
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // List all posts
- class PostsListHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var posts = get_posts();
-
- // Filter by user_id if provided
- var user_id_param = http_context.request.get_query("user_id");
- if (user_id_param != null) {
- var user_id = int.parse(user_id_param);
- posts = posts.to_immutable_buffer()
- .where(p => p.user_id == user_id)
- .to_series();
- }
-
- var json_parts = new Series<string>();
- json_parts.add_start(@"{ \"posts\": [");
-
- bool first = true;
- posts.to_immutable_buffer().iterate((post) => {
- if (!first) json_parts.add_start(", ");
- json_parts.add_start(post.to_json());
- first = false;
- });
-
- var post_count = posts.to_immutable_buffer().count();
- json_parts.add("], ");
- json_parts.add("\"count\": " + post_count.to_string() + " }");
-
- var json_string = json_parts.to_immutable_buffer()
- .aggregate<string>("", (acc, s) => acc + s);
-
- return new BufferedHttpResult.from_string(
- json_string,
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // Get post by ID
- class PostByIdHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var id_str = route_context.get_segment("id");
- var id = int.parse(id_str);
- var post = find_post(id);
-
- if (post == null) {
- return error_response(@"Post with ID $id not found", StatusCode.NOT_FOUND);
- }
-
- // Include user and comments in response
- var user = find_user(post.user_id);
- var comments = get_comments_for_post(id);
-
- var json_parts = new Series<string>();
- json_parts.add_start(@"{ \"post\": $(post.to_json()), ");
-
- if (user != null) {
- json_parts.add_start("\"user\": " + user.to_json() + ", ");
- } else {
- json_parts.add_start("\"user\": null, ");
- }
-
- json_parts.add_start("\"comments\": [");
-
- bool first = true;
- comments.to_immutable_buffer().iterate((comment) => {
- if (!first) json_parts.add_start(", ");
- json_parts.add_start(comment.to_json());
- first = false;
- });
-
- json_parts.add("] }");
-
- var json_string = json_parts.to_immutable_buffer()
- .aggregate<string>("", (acc, s) => acc + s);
-
- return new BufferedHttpResult.from_string(
- json_string,
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // List all comments
- class CommentsListHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var comments = get_comments();
-
- // Filter by post_id if provided
- var post_id_param = http_context.request.get_query("post_id");
- if (post_id_param != null) {
- var post_id = int.parse(post_id_param);
- comments = comments.to_immutable_buffer()
- .where(c => c.post_id == post_id)
- .to_series();
- }
-
- var json_parts = new Series<string>();
- json_parts.add_start(@"{ \"comments\": [");
-
- bool first = true;
- comments.to_immutable_buffer().iterate((comment) => {
- if (!first) json_parts.add_start(", ");
- json_parts.add_start(comment.to_json());
- first = false;
- });
-
- var comment_count = comments.to_immutable_buffer().count();
- json_parts.add("], ");
- json_parts.add("\"count\": " + comment_count.to_string() + " }");
-
- var json_string = json_parts.to_immutable_buffer()
- .aggregate<string>("", (acc, s) => acc + s);
-
- return new BufferedHttpResult.from_string(
- json_string,
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // Get comment by ID
- class CommentByIdHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var id_str = route_context.get_segment("id");
- var id = int.parse(id_str);
- var comment = find_comment(id);
-
- if (comment == null) {
- return error_response(@"Comment with ID $id not found", StatusCode.NOT_FOUND);
- }
-
- return new BufferedHttpResult.from_string(
- comment.to_json(),
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // API statistics
- class StatsHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var users = get_users();
- var posts = get_posts();
- var comments = get_comments();
-
- var user_count = users.to_immutable_buffer().count();
- var post_count = posts.to_immutable_buffer().count();
- var comment_count = comments.to_immutable_buffer().count();
- var posts_per_user = post_count / (double)user_count;
- var comments_per_post = comment_count / (double)post_count;
-
- var json = @"{
- \"users\": $user_count,
- \"posts\": $post_count,
- \"comments\": $comment_count,
- \"posts_per_user\": $posts_per_user,
- \"comments_per_post\": $comments_per_post
- }";
-
- return new BufferedHttpResult.from_string(
- json,
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // Search endpoint
- class SearchHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var query = http_context.request.get_query("q");
-
- if (query == null || query == "") {
- return error_response("Query parameter 'q' is required");
- }
-
- var results = new Series<SearchResult>();
-
- // Search users
- get_users().to_immutable_buffer()
- .where(u => u.name.down().contains(query.down()))
- .iterate((user) => {
- results.add_start(new SearchResult("user", user.id.to_string(), user.name));
- });
-
- // Search posts
- get_posts().to_immutable_buffer()
- .where(p => p.title.down().contains(query.down()) || p.content.down().contains(query.down()))
- .iterate((post) => {
- results.add_start(new SearchResult("post", post.id.to_string(), post.title));
- });
-
- var json_parts = new Series<string>();
- json_parts.add_start(@"{ \"query\": \"$query\", \"results\": [");
-
- bool first = true;
- results.to_immutable_buffer().iterate((result) => {
- if (!first) json_parts.add_start(", ");
- json_parts.add_start(result.to_json());
- first = false;
- });
-
- var result_count = results.to_immutable_buffer().count();
- json_parts.add("], ");
- json_parts.add("\"count\": " + result_count.to_string() + " }");
-
- var json_string = json_parts.to_immutable_buffer()
- .aggregate<string>("", (acc, s) => acc + s);
-
- return new BufferedHttpResult.from_string(
- json_string,
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // Pagination example
- class PaginatedPostsHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var page = int.parse(http_context.request.get_query_or_default("page", "1"));
- var per_page = int.parse(http_context.request.get_query_or_default("per_page", "10"));
-
- var posts = get_posts();
- var total = posts.to_immutable_buffer().count();
- var total_pages = (total + per_page - 1) / per_page;
-
- // Calculate pagination
- var offset = (page - 1) * per_page;
- var paginated_posts = posts.to_immutable_buffer()
- .skip(offset)
- .take(per_page);
-
- var json_parts = new Series<string>();
- json_parts.add_start(@"{ \"page\": $page, \"per_page\": $per_page, \"total\": $total, \"total_pages\": $total_pages, \"posts\": [");
-
- bool first = true;
- paginated_posts.iterate((post) => {
- if (!first) json_parts.add_start(", ");
- json_parts.add_start(post.to_json());
- first = false;
- });
-
- json_parts.add("] }");
-
- var json_string = json_parts.to_immutable_buffer()
- .aggregate<string>("", (acc, s) => acc + s);
-
- return new BufferedHttpResult.from_string(
- json_string,
- StatusCode.OK,
- get_json_headers()
- );
- }
- }
- // Error handling endpoint
- class ApiErrorHandler : Object, RouteHandler {
- public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
- var error_type = http_context.request.get_query_or_default("type", "generic");
-
- switch (error_type) {
- case "not_found":
- return error_response("Resource not found", StatusCode.NOT_FOUND);
- case "bad_request":
- return error_response("Invalid request parameters", StatusCode.BAD_REQUEST);
- case "server_error":
- return error_response("Internal server error occurred", StatusCode.INTERNAL_SERVER_ERROR);
- default:
- return error_response("An error occurred");
- }
- }
- }
- void main() {
- var router = new Router();
- var server = new Server(8085, router);
-
- // Register routes
- router.get("/api", new ApiRootHandler());
- router.get("/api/users", new UsersListHandler());
- router.get("/api/users/{id}", new UserByIdHandler());
- router.get("/api/posts", new PostsListHandler());
- router.get("/api/posts/{id}", new PostByIdHandler());
- router.get("/api/comments", new CommentsListHandler());
- router.get("/api/comments/{id}", new CommentByIdHandler());
- router.get("/api/stats", new StatsHandler());
- router.get("/api/search", new SearchHandler());
- router.get("/api/posts/paginated", new PaginatedPostsHandler());
- router.get("/api/error", new ApiErrorHandler());
-
- print("JSON API Example Server running on port 8085\n");
- print("Try these endpoints:\n");
- print(" - http://localhost:8085/api\n");
- print(" - http://localhost:8085/api/users\n");
- print(" - http://localhost:8085/api/users/1\n");
- print(" - http://localhost:8085/api/posts\n");
- print(" - http://localhost:8085/api/posts?user_id=1\n");
- print(" - http://localhost:8085/api/posts/1\n");
- print(" - http://localhost:8085/api/comments\n");
- print(" - http://localhost:8085/api/comments?post_id=1\n");
- print(" - http://localhost:8085/api/stats\n");
- print(" - http://localhost:8085/api/search?q=test\n");
- print(" - http://localhost:8085/api/posts/paginated?page=1&per_page=5\n");
-
- server.run();
- }
- // Helper functions
- Catalogue<string, string> get_json_headers() {
- var headers = new Catalogue<string, string>();
- headers.add("Content-Type", "application/json");
- headers.add("Access-Control-Allow-Origin", "*");
- return headers;
- }
- BufferedHttpResult error_response(string message, StatusCode status = StatusCode.BAD_REQUEST) {
- var json = @"{ \"error\": \"$message\" }";
- return new BufferedHttpResult.from_string(
- json,
- status,
- get_json_headers()
- );
- }
- // Data models and storage
- class User {
- public int id { get; private set; }
- public string name { get; private set; }
- public string email { get; private set; }
-
- public User(int id, string name, string email) {
- this.id = id;
- this.name = name;
- this.email = email;
- }
-
- public string to_json() {
- return @"{ \"id\": $id, \"name\": \"$name\", \"email\": \"$email\" }";
- }
- }
- class Post {
- public int id { get; private set; }
- public int user_id { get; private set; }
- public string title { get; private set; }
- public string content { get; private set; }
-
- public Post(int id, int user_id, string title, string content) {
- this.id = id;
- this.user_id = user_id;
- this.title = title;
- this.content = content;
- }
-
- public string to_json() {
- var escaped_content = content.replace("\"", "\\\"").replace("\n", "\\n");
- return @"{ \"id\": $id, \"user_id\": $user_id, \"title\": \"$title\", \"content\": \"$escaped_content\" }";
- }
- }
- class Comment {
- public int id { get; private set; }
- public int post_id { get; private set; }
- public string author { get; private set; }
- public string text { get; private set; }
-
- public Comment(int id, int post_id, string author, string text) {
- this.id = id;
- this.post_id = post_id;
- this.author = author;
- this.text = text;
- }
-
- public string to_json() {
- var escaped_text = text.replace("\"", "\\\"").replace("\n", "\\n");
- return @"{ \"id\": $id, \"post_id\": $post_id, \"author\": \"$author\", \"text\": \"$escaped_text\" }";
- }
- }
- class SearchResult {
- public string result_type { get; private set; }
- public string id { get; private set; }
- public string title { get; private set; }
-
- public SearchResult(string result_type, string id, string title) {
- this.result_type = result_type;
- this.id = id;
- this.title = title;
- }
-
- public string to_json() {
- return @"{ \"type\": \"$result_type\", \"id\": \"$id\", \"title\": \"$title\" }";
- }
- }
- // Data storage functions
- Series<User> get_users() {
- var users = new Series<User>();
- users.add_start(new User(1, "Alice Johnson", "alice@example.com"));
- users.add_start(new User(2, "Bob Smith", "bob@example.com"));
- users.add_start(new User(3, "Charlie Brown", "charlie@example.com"));
- users.add_start(new User(4, "Diana Prince", "diana@example.com"));
- users.add_start(new User(5, "Eve Davis", "eve@example.com"));
- return users;
- }
- Series<Post> get_posts() {
- var posts = new Series<Post>();
- posts.add_start(new Post(1, 1, "First Post", "This is my first post!"));
- posts.add_start(new Post(2, 1, "Second Post", "Another day, another post."));
- posts.add_start(new Post(3, 2, "Hello World", "Just saying hello to everyone."));
- posts.add_start(new Post(4, 3, "Vala Programming", "Vala is a great programming language."));
- posts.add_start(new Post(5, 4, "Web Development", "Building web applications is fun."));
- posts.add_start(new Post(6, 5, "API Design", "RESTful APIs are the way to go."));
- return posts;
- }
- Series<Comment> get_comments() {
- var comments = new Series<Comment>();
- comments.add_start(new Comment(1, 1, "Bob", "Great first post!"));
- comments.add_start(new Comment(2, 1, "Charlie", "Welcome to the platform!"));
- comments.add_start(new Comment(3, 2, "Alice", "Keep posting!"));
- comments.add_start(new Comment(4, 3, "Alice", "Hello to you too!"));
- comments.add_start(new Comment(5, 4, "Bob", "I agree!"));
- comments.add_start(new Comment(6, 5, "Charlie", "Good point!"));
- return comments;
- }
- Series<Comment> get_comments_for_post(int post_id) {
- return get_comments().to_immutable_buffer()
- .where(c => c.post_id == post_id)
- .to_series();
- }
- User? find_user(int id) {
- return get_users().to_immutable_buffer()
- .first_or_default(u => u.id == id);
- }
- Post? find_post(int id) {
- return get_posts().to_immutable_buffer()
- .first_or_default(p => p.id == id);
- }
- Comment? find_comment(int id) {
- return get_comments().to_immutable_buffer()
- .first_or_default(c => c.id == id);
- }
|