Blog App Tutorial Part 3

Part 3 covers post and comment workflows.

Create posts linked to an author

ballerina
type PostRow record {
    int id;
    string title;
    string? excerpt;
    string content;
    string status;
    int authorId;
    string? publishedAt = ();
};

record {}? thambaruRow = check db.'from(User)
    .'where({email: {'equals: "hi@thambaru.com"}})
    .findUnique();

if thambaruRow is record {} {
    UserRow thambaru = check thambaruRow.cloneWithType();

    PostRow post1 = check (check db.'from(Post).create({
        title: "Getting Started with Ballerina ORM",
        excerpt: "Learn how to build type-safe database applications",
        content: "Ballerina ORM provides a Prisma-like experience for Ballerina developers...",
        status: PUBLISHED,
        authorId: thambaru.id,
        publishedAt: time:utcNow()
    })).cloneWithType();

    PostRow post2 = check (check db.'from(Post).create({
        title: "Advanced Query Patterns",
        excerpt: "Master complex queries and relations",
        content: "In this post, we'll explore advanced patterns for querying databases...",
        status: DRAFT,
        authorId: thambaru.id
    })).cloneWithType();

    _ = [post1, post2];
}

Filter by status and publication state

ballerina
PostRow[] publishedPosts = check (check db.'from(Post)
    .'where({
        status: {'equals: PUBLISHED},
        publishedAt: {isNull: false}
    })
    .orderBy({publishedAt: orm:DESC})
    .findMany()).cloneWithType();

Pagination with skip and take

ballerina
int pageSize = 2;

PostRow[] page1 = check (check db.'from(Post)
    .orderBy({id: orm:ASC})
    .skip(0)
    .take(pageSize)
    .findMany()).cloneWithType();

PostRow[] page2 = check (check db.'from(Post)
    .orderBy({id: orm:ASC})
    .skip(pageSize)
    .take(pageSize)
    .findMany()).cloneWithType();

Add comments to posts

ballerina
type CommentRow record {
    int id;
    string content;
    int postId;
    int authorId;
};

record {}? firstPostRow = check db.'from(Post).findFirst();
record {}? firstUserRow = check db.'from(User).findFirst();

if firstPostRow is record {} && firstUserRow is record {} {
    PostRow post = check firstPostRow.cloneWithType();
    UserRow user = check firstUserRow.cloneWithType();

    CommentRow _ = check (check db.'from(Comment).create({
        content: "Great write-up. Looking forward to part 2.",
        postId: post.id,
        authorId: user.id
    })).cloneWithType();
}

Next step

Proceed to Part 4: Categories & Advanced Queries.