patx/relay-lang

from "../lib/common.ry" import users, posts, follows, counters, count_items, text_or_empty, number_or_zero, api_error, request_input, username_key, follow_key, counter_key, post_key, find_user, current_user_doc, active_viewer_username, next_sequence, is_username_char, is_valid_username, is_valid_password, is_valid_bio, is_valid_post_body, user_brief_from_doc, public_user_from_doc, serialize_post_doc, insert_post_desc, sort_posts_desc, collect_posts, discover_posts, user_posts, home_feed_posts

fn register(app)
    @app.get("/api/feed/home")
    fn home_feed()
        user = current_user_doc()
        if (user == None)
            return api_error(401, "Log in to view your home feed")

        username = text_or_empty(user["username"])
        return app.json({
            "feed": "home",
            "items": home_feed_posts(username)
        })

    @app.get("/api/feed/discover")
    fn discover_feed()
        return app.json({
            "feed": "discover",
            "items": discover_posts()
        })

    @app.post("/api/posts")
    fn create_post()
        user = current_user_doc()
        if (user == None)
            return api_error(401, "Log in to post")

        body = text_or_empty(request_input("body"))
        if (is_valid_post_body(body) == False)
            return api_error(400, "Post body must be between 1 and 280 characters")

        username = text_or_empty(user["username"])
        seq = next_sequence("posts")
        post_id = post_key(seq)

        created = posts.insert_one({
            "_id": post_id,
            "seq": seq,
            "author_username": username,
            "body": body
        })
        str(created["inserted_id"])

        return app.json({
            "ok": True,
            "post": {
                "id": post_id,
                "seq": seq,
                "body": body,
                "author": user_brief_from_doc(user)
            }
        })