Tutorial: A Complete Blog
This tutorial walks through examples/blog, a small but complete application in the Runcobo repository. It has posts and comments, a token-protected admin API, a paginated JSON API, an HTML home page and specs for all of it. Every file is shown below, in the order you'd write them.
You'll see:
- migrations and named SQL queries turned into typed Crystal methods,
- contracts that validate path, query and body input,
- a filter that protects the write endpoints,
- JSON templates and partials, and an HTML page with a layout,
- how to avoid N+1 queries and escape HTML,
- specs that run against a real database.
Run it first
You need Crystal, sqlc 1.31.1 and PostgreSQL on 127.0.0.1:5432 with a postgres user.
git clone https://github.com/runcobo/runcobo.git
cd runcobo/examples/blog
shards install
bin/cobo test --prepare # 15 examples, 0 failures
BLOG_ADMIN_TOKEN=secret bin/cobo devcobo dev creates blog_development, applies the migrations, runs the seed script and starts the server. Open http://localhost:3000:
curl localhost:3000/posts
curl -X POST localhost:3000/posts \
-H 'Authorization: Bearer secret' -H 'Content-Type: application/json' \
-d '{"title":"Hello","body":"My first post"}'
curl -X POST localhost:3000/posts/1/comments \
-H 'Content-Type: application/json' -d '{"author":"Ada","body":"Nice post"}'1. The project
The blog started like every Runcobo project — see Installation:
crystal init app blog
cd blog
# add runcobo to shard.yml
shards install
bin/cobo init # PostgreSQLThe finished application:
src/app.cr loads everything in dependency order. The two abstract base classes come first, because every action inherits from one of them:
require "runcobo"
require "pg"
require "./persistence/generated/queries"
require "./actions/base_action"
require "./actions/admin_action"
require "./web/handlers"
require "./actions/**"2. The tables
Each migration is plain SQL, applied by bin/cobo db migrate (and automatically by cobo dev and cobo test --prepare):
-- migrate:up
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- migrate:down
DROP TABLE posts;-- migrate:up
CREATE TABLE comments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
post_id bigint NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
author text NOT NULL,
body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX comments_post_id_index ON comments (post_id);
-- migrate:down
DROP TABLE comments;ON DELETE CASCADE deletes a post's comments with it, and the index keeps "comments of this post" fast.
3. The queries
Every database call is a named SQL query. bin/cobo generate reads them together with the migrations and writes a typed method for each one into src/persistence/generated/queries.cr — see Database Access.
-- name: ListPosts :many
SELECT id, title, body, created_at FROM posts
ORDER BY id DESC
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);
-- name: CountPosts :one
SELECT count(*) AS total FROM posts;
-- name: ListRecentPostsWithCommentCounts :many
SELECT posts.id, posts.title, posts.created_at, count(comments.id) AS comments_count
FROM posts
LEFT JOIN comments ON comments.post_id = posts.id
GROUP BY posts.id
ORDER BY posts.id DESC
LIMIT sqlc.arg(row_limit);
-- name: GetPost :one
SELECT id, title, body, created_at, updated_at FROM posts WHERE id = sqlc.arg(id);
-- name: CreatePost :one
INSERT INTO posts (title, body) VALUES (sqlc.arg(title), sqlc.arg(body))
RETURNING id, title, body, created_at, updated_at;
-- name: UpdatePost :one
UPDATE posts SET
title = CASE WHEN sqlc.arg(title_present)::boolean THEN sqlc.narg(title)::text ELSE title END,
body = CASE WHEN sqlc.arg(body_present)::boolean THEN sqlc.narg(body)::text ELSE body END,
updated_at = now()
WHERE id = sqlc.arg(id)
RETURNING id, title, body, created_at, updated_at;
-- name: DeletePost :execrows
DELETE FROM posts WHERE id = sqlc.arg(id);-- name: ListCommentsForPost :many
SELECT id, post_id, author, body, created_at FROM comments
WHERE post_id = sqlc.arg(post_id)
ORDER BY id;
-- name: ListCommentsForPosts :many
SELECT id, post_id, author, body, created_at FROM comments
WHERE post_id = ANY(sqlc.arg(post_ids)::bigint[])
ORDER BY id;
-- name: CreateComment :one
INSERT INTO comments (post_id, author, body)
SELECT posts.id, sqlc.arg(author), sqlc.arg(body) FROM posts WHERE posts.id = sqlc.arg(post_id)
RETURNING comments.id, comments.post_id, comments.author, comments.body, comments.created_at;A few of these are worth a closer look:
UpdatePostchanges only the fields the client sent — see Partial updates.DeletePost :execrowsreturns the number of deleted rows, so the action can answer404when it's0.CreateCommentinserts only if the post exists. A missing post gives no row —nilfromcreate_comment?— instead of a foreign-key error.
The generated methods are typed from the schema: store.get_post?(id: Int64) returns a GetPostRow? whose title is a String and whose created_at is a Time.
4. Listing posts
The base action gives every action the store and a shared 404 helper:
abstract class Blog::BaseAction < ::BaseAction
protected def store : Blog::Store::Queries
context.blog_store
end
private def not_found(resource : String)
render_json({error: "#{resource}_not_found"}, status_code: 404)
end
endGET /posts returns one page of posts, each with its comments:
class Posts::ListPostsContract < RequestValidation::Contract
schema do
optional :page, Int32, gteq: 1
optional :per_page, Int32, gteq: 1, lteq: 100
end
endclass Posts::ListPosts < Blog::BaseAction
get "/posts"
call do
input = validate(ListPostsContract)
pagination = Runcobo::Pagination.new(input.page, input.per_page)
posts = store.list_posts(row_limit: pagination.per_page, row_offset: pagination.offset.to_i32)
total = store.count_posts.total
# One query for the comments of every post on the page, not one per post.
comments = store.list_comments_for_posts(post_ids: posts.map(&.id.as(Int64?))).group_by(&.post_id)
render
end
endjson.array!("posts", posts) do |json, post|
json.partial! "posts/partials/post", post: post
json.array!("comments", comments[post.id]? || [] of Blog::Store::ListCommentsForPostsRow) do |json, comment|
json.partial! "comments/partials/comment", comment: comment
end
end
json.meta do |json|
json.page pagination.page
json.per_page pagination.per_page
json.total total
end# locals: post
json.id post.id
json.title post.title
json.body post.body
json.created_at post.created_at.to_rfc3339Loading each post's comments inside the loop would run one query per post — the N+1 problem. Instead, list_comments_for_posts loads the comments of the whole page in one query, and group_by hands each post its own. However many posts the page shows, the action runs three queries. A spec checks exactly that.
?per_page=500 is rejected with a 422, because the contract allows at most 100.
5. Reading a post
class Posts::ShowPostContract < RequestValidation::Contract
schema do
required :id, Int64
end
endclass Posts::ShowPost < Blog::BaseAction
get "/posts/:id"
call do
input = validate(ShowPostContract)
if post = store.get_post?(id: input.id)
comments = store.list_comments_for_post(post_id: post.id)
render
else
not_found "post"
end
end
endjson.partial! "posts/partials/post", post: post
json.updated_at post.updated_at.to_rfc3339
json.array!("comments", comments) do |json, comment|
json.partial! "comments/partials/comment", comment: comment
end/posts/abc never reaches the query: the contract rejects abc as an Int64 with a 422.
6. Protecting writes
Creating, changing and deleting posts needs an admin token. Those actions inherit from Blog::AdminAction, which adds a before filter:
require "crypto/subtle"
# Actions that change posts. They require `Authorization: Bearer <token>`,
# where the token is the BLOG_ADMIN_TOKEN environment variable.
abstract class Blog::AdminAction < Blog::BaseAction
before authenticate
private def authenticate
expected = ENV["BLOG_ADMIN_TOKEN"]?
given = request.headers["Authorization"]?.try(&.lchop?("Bearer "))
# Fail closed when no token is configured, and compare in constant time.
unless expected && !expected.empty? && given && Crypto::Subtle.constant_time_compare(given, expected)
render_json({error: "unauthorized"}, status_code: 401)
return byebye
end
end
end- The filter runs before the body is read, so an unauthenticated request is rejected without parsing anything.
- Returning
byebyestops the request:callnever runs. - Without
BLOG_ADMIN_TOKEN, every write is refused rather than allowed. Crypto::Subtle.constant_time_comparedoesn't leak how much of the token was right through timing.
See Security for more.
7. Creating, updating and deleting
class Posts::CreatePostContract < RequestValidation::Contract
schema do
required :title, String, filled: true, strip: true, max_size: 200
required :body, String, filled: true, max_size: 20_000
end
endclass Posts::CreatePost < Blog::AdminAction
post "/posts"
call do
input = validate(CreatePostContract)
post = store.create_post(title: input.title.strip, body: input.body)
render status_code: 201
end
endstrip: true makes " " fail the filled check, but it doesn't change the value, so the action strips the title before saving it.
PATCH keeps the fields the client didn't send. The contract's <field>_present? methods tell the query which ones to change:
class Posts::UpdatePostContract < RequestValidation::Contract
schema do
required :id, Int64 # from the path
optional :title, String, filled: true, strip: true, max_size: 200 # from the body
optional :body, String, filled: true, max_size: 20_000
end
endclass Posts::UpdatePost < Blog::AdminAction
patch "/posts/:id"
call do
input = validate(UpdatePostContract)
post = store.update_post?(id: input.id,
title: input.title.try(&.strip), title_present: input.title_present?,
body: input.body, body_present: input.body_present?)
if post
render
else
not_found "post"
end
end
endclass Posts::DeletePost < Blog::AdminAction
delete "/posts/:id"
call do
input = validate(DeletePostContract)
if store.delete_post(id: input.id) > 0
render_empty status_code: 204
else
not_found "post"
end
end
endComments are open to everyone, so Comments::CreateComment inherits from Blog::BaseAction. Its contract reads post_id from the path and the rest from the body:
# Anyone can comment; only the admin token can change posts.
class Comments::CreateComment < Blog::BaseAction
post "/posts/:post_id/comments"
call do
input = validate(CreateCommentContract)
if comment = store.create_comment?(post_id: input.post_id, author: input.author.strip, body: input.body)
render status_code: 201
else
not_found "post"
end
end
end8. The HTML home page
GET / renders HTML with Water inside a layout:
class Home::ShowHome < Blog::BaseAction
get "/"
call do
posts = store.list_recent_posts_with_comment_counts(row_limit: 20)
render engine: :water, layout: "application"
end
endh1 "Blog"
if posts.empty?
para "No posts yet. Create one with POST /posts."
else
ul {
posts.each do |post|
li {
# Only the numeric id goes into the attribute; text content is escaped.
a %|href="/posts/#{post.id}"|, post.title
br
small "#{post.created_at.to_s("%Y-%m-%d")} · #{post.comments_count} #{post.comments_count == 1 ? "comment" : "comments"}"
}
end
}
endWater.new do
doctype
html %|lang="en"| {
head {
meta %|charset="utf-8"|
meta %|name="viewport" content="width=device-width, initial-scale=1"|
title "Blog"
style %q{ /* ... */ }
}
body {
yield_content
}
}
end- The comment counts come from one
LEFT JOIN ... GROUP BYquery, so the page costs one query however many posts it lists. - A post titled
<script>alert(1)</script>is shown as text: Water escapes tag content. Attributes are written as you give them, so only the numericidgoes intohref— see Escaping HTML.
9. Specs
spec/spec_helper.cr opens the test database, empties the tables before each example and adds a few helpers:
require "spec"
require "../src/app"
ENV["BLOG_ADMIN_TOKEN"] = "test-token"
TEST_DB = DB.open(ENV["DATABASE_URL"])
TEST_STORE = Blog::Store::Queries.new(TEST_DB)
# Start every example from empty tables.
Spec.before_each do
TEST_DB.exec "TRUNCATE posts, comments RESTART IDENTITY CASCADE"
end
def dispatch(method : String, path : String, body : String? = nil, headers = HTTP::Headers.new,
handler : HTTP::Handler = Blog::RouteHandler.new(TEST_STORE)) : HTTP::Client::Response
# ... runs the request through the app in memory
end
def admin_headers
HTTP::Headers{"Content-Type" => "application/json", "Authorization" => "Bearer test-token"}
endSpecs exercise the app over HTTP, the way clients use it:
describe "POST /posts" do
it "requires the admin token" do
dispatch("POST", "/posts", %({"title":"Hello","body":"World"}), json_headers).status_code.should eq(401)
TEST_STORE.count_posts.total.should eq(0)
end
it "reports every invalid field" do
response = dispatch("POST", "/posts", %({"title":""}), admin_headers)
response.status_code.should eq(422)
json(response)["errors"].as_a.map(&.["path"][0].as_s).sort.should eq(["body", "title"])
end
endThe generated store can report every query it runs, which turns "no N+1" into a test:
it "loads the comments of a page with a fixed number of queries" do
3.times { |i| TEST_STORE.create_comment?(post_id: TEST_STORE.create_post(title: "P#{i}", body: "b").id, author: "A", body: "c") }
queries = [] of String
store = TEST_STORE.with_observer(->(event : Blog::Store::QueryEvent) { queries << event.query_name; nil })
dispatch("GET", "/posts", handler: Blog::RouteHandler.new(store)).status_code.should eq(200)
queries.should eq(["ListPosts", "CountPosts", "ListCommentsForPosts"])
endRun them with:
bin/cobo test --prepare # first time: create and migrate blog_test
bin/cobo test10. Seed data
runcobo.yml points seed_command at a script, which cobo dev runs after migrating:
name: blog
database_prefix: blog # databases: blog_development, blog_test
seed_command: [crystal, run, src/seed.cr]require "./app"
# Sample data for development, run by `bin/cobo db seed` and `bin/cobo dev`.
Blog::Store.open(ENV["DATABASE_URL"]) do |store|
if store.count_posts.total.zero?
welcome = store.create_post(title: "Welcome to the blog", body: "This post was created by src/seed.cr.")
store.create_comment?(post_id: welcome.id, author: "Ada", body: "First!")
store.create_post(title: "Second post", body: "Runcobo checks routes, input and templates at compile time.")
end
endWhere to go next
- Ship it: Deployment
- Every option for input: Request Contracts
- More query patterns: Query Recipes
- Harden it: Security