【山竹记账后端】13.超快速实现后端接口


大纲链接 §

[toc]


基本步骤

  1. 创建 model,运行 db:migrate
  2. 创建 controller
  3. 写测试
  4. 写代码
  5. 写文档(测试代码)

1. 快速实现读取API ⇧

实现 /api/v1/tags

创建 tag 的 model

1
2
3
4
5
6
7
8
9
Table Tag {
  id bigint [pk, increment]
  user_id bigint [not null]
  name varchar(50) [not null]
  sign varchar(10) [not null]
  deleted_at datetime
  created_at datetime
  updated_at datetime
}

mangosteen-1

  • 运行命令 bin/rails g model tag 前,需要看下概要设计文档数据库设计中 tag 表中的字段:
    • user:references 识别为引用到 user 表,自动在表中生成字段 user_id 并匹配类型 bigint
    • name:string
    • sign:string
    • deleted_at:datetime
    • created_at:datetime
    • updated_at:datetime
  • 确认然后再运行 bin/rails g model tag user:references name:string sign:string deleted_at:datetime
  • 生成以下文件:

    1
    2
    3
    4
    5
    6
    
    bin/rails g model tag user:references name:string sign:string deleted_at:datetime
      invoke  active_record
      create    db/migrate/20261128130348_create_tags.rb
      create    app/models/tag.rb
      invoke    rspec
      create      spec/models/tag_spec.rb

打开 db/migrate/xxxxxxxxxxx_create_tags.rb 需要在迁移前补充更多详细配置,修改如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class CreateTags < ActiveRecord::Migration[7.2]
  def change
    create_table :tags do |t|
      t.references :user, null: false, foreign_key: false
      t.string :name
      t.string :sign
      t.datetime :deleted_at

      t.timestamps
    end
  end
end
  • t.references :user, null: false, foreign_key: false 表示引用到 user 表,不能为空,不使用外键(不方便测试)
  • t.string :name, null: false 不能为空,如果此处不写 null: false,那么需要在 ruby 验证器中添加不能为空的验证
  • 目前 db/schema.rb 中还没有这个表需要创建,运行 bin/rails db:migrate

    1
    2
    3
    4
    
    == 20261128130348 CreateTags: migrating =======================================
    -- create_table(:tags)
    -> 0.0295s
    == 20261128130348 CreateTags: migrated (0.0296s) ==============================
  • 可以看到 db/schema.rb 中已经生成了 tag 表

  • 之前写的引用 t.references :user, null: false, foreign_key: false

    • 自动变为 t.bigint "user_id", null: false 的引用 "user_id" 类型 t.bigint 比较智能

db/schema.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
ActiveRecord::Schema[7.2].define(version: 2026_11_28_130348) do
  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "items", force: :cascade do |t|
    t.bigint "user_id"
    t.integer "amount"
    t.text "note"
    t.bigint "tags_id", array: true
    t.datetime "happened_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "tags", force: :cascade do |t|
    t.bigint "user_id", null: false
    t.string "name", null: false
    t.string "sign", null: false
    t.datetime "deleted_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_tags_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email"
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "validation_codes", force: :cascade do |t|
    t.string "email"
    t.integer "kind", default: 1, null: false
    t.string "code", limit: 100
    t.datetime "used_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
end

app/models/tag.rb

1
2
3
class Tag < ApplicationRecord
  belongs_to :user
end
  • belongs_to :user 于数据表关联,暂时忽略
  • spec/models/tag_spec.rb 中不写测试,暂时不测 model,可以删掉

创建 tag 的 controller ⇧

  • 运行命令 bin/rails g controller api/v1/tags_controller

    1
    2
    3
    
      create  app/controllers/api/v1/tags_controller.rb
      invoke  rspec
      create    spec/requests/api/v1/tags_spec.rb

spec/requests/api/v1/tags_spec.rb

1
2
3
4
5
6
7
require 'rails_helper'

RSpec.describe "Api::V1::Tags", type: :request do
  describe "GET /index" do
    pending "add some examples (or delete) #{__FILE__}"
  end
end

app/controllers/api/v1/tags_controller.rb

1
2
class Api::V1::TagsController < ApplicationController
end

写 tag 的测试用例 ⇧

添加未登录获取标签测试用例 spec/requests/api/v1/tags_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
require 'rails_helper'

RSpec.describe "Api::V1::Tags", type: :request do
  describe "获取标签" do
    it "未登录获取标签" do
      get '/api/v1/tags'
      expect(response).to have_http_status :unauthorized
    end
    it "已登录获取标签" do
    end

  end
end
  • 运行 rspec spec/requests/api/v1/tags_spec.rb 成功
    • 是因为之前中间件 auto_jwt.rb 中只要不在白名单中的请求路径,请求头 jwt 为空,即返回 401

完成测试用例 spec/requests/api/v1/tags_spec.rb 测试分页

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
require 'rails_helper'

RSpec.describe "Api::V1::Tags", type: :request do
  describe "获取标签" do
    it "未登录获取标签" do
      get '/api/v1/tags'
      expect(response).to have_http_status :unauthorized
    end
    it "已登录获取标签" do
      user = User.create email: '1@163.com'
      11.times do |i| Tag.create name: "tag#{i}", user_id: user.id, sign: '😄' end

      get '/api/v1/tags', headers: user.generate_auth_header
      expect(response).to have_http_status :ok
      json = JSON.parse response.body
      expect(json['resources'].size).to eq 10

      get '/api/v1/tags', headers: user.generate_auth_header,
        params: { page: 2 }
      expect(response).to have_http_status :ok
      json = JSON.parse response.body
      expect(json['resources'].size).to eq 1
    end

  end
end
  • 运行测试用例 rspec spec/requests/api/v1/tags_spec.rb:9
  • 发现报错 null value in column "sign" of relation "tags" violates not-null constraint
  • 补充sign属性 Tag.create name: "tag#{i}", user_id: user.id, sign: '😄'

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    rspec spec/requests/api/v1/tags_spec.rb:9
    Run options: include {:locations=>{"./spec/requests/api/v1/tags_spec.rb"=>[9]}}
    F
    
    Failures:
    
    1) Api::V1::Tags 获取标签 已登录获取标签(分页)
     Failure/Error: expect(response).to have_http_status :ok
    expected the response to have status code :ok (200) but it was :not_found (404)
     # ./spec/requests/api/v1/tags_spec.rb:16:in `block (3 levels) in <top (required)>'
    
    Finished in 0.15225 seconds (files took 0.68188 seconds to load)
    1 example, 1 failure
    
    Failed examples:
    
    rspec ./spec/requests/api/v1/tags_spec.rb:9 # Api::V1::Tags 获取标签 已登录获取标签(分页)
  • 现在去实现 controller


实现 tag 的 controller ⇧

添加一个 index 方法 app/controllers/api/v1/tags_controller.rb

1
2
3
4
class Api::V1::TagsController < ApplicationController
  def index
  end
end
  • 运行测试用例 rspec spec/requests/api/v1/tags_spec.rb:9 会返回

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    Failures:
    
    1) Api::V1::Tags 获取标签 已登录获取标签(分页)
     Failure/Error: expect(response).to have_http_status :ok
    expected the response to have status code :ok (200) but it was :no_content (204)
     # ./spec/requests/api/v1/tags_spec.rb:16:in `block (3 levels) in <top (required)>'
    
    Finished in 0.06641 seconds (files took 1.08 seconds to load)
    1 example, 1 failure
    
    Failed examples:
    
    rspec ./spec/requests/api/v1/tags_spec.rb:9 # Api::V1::Tags 获取标签 已登录获取标签(分页)
  • 空方法默认返回 204 No Content

app/controllers/api/v1/tags_controller.rb

1
2
3
4
5
class Api::V1::TagsController < ApplicationController
  def index
    head 444
  end
end
  • 运行测试用例 rspec spec/requests/api/v1/tags_spec.rb:9 会返回

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    Failures:
    
    1) Api::V1::Tags 获取标签 已登录获取标签(分页)
     Failure/Error: expect(response).to have_http_status :ok
       expected the response to have status code :ok (200) but it was 444
     # ./spec/requests/api/v1/tags_spec.rb:16:in `block (3 levels) in <top (required)>'
    
    Finished in 0.08136 seconds (files took 1.1 seconds to load)
    1 example, 1 failure
    
    Failed examples:
    
    rspec ./spec/requests/api/v1/tags_spec.rb:9 # Api::V1::Tags 获取标签 已登录获取标签(分页)

app/controllers/api/v1/tags_controller.rb

1
2
3
4
5
6
7
8
class Api::V1::TagsController < ApplicationController
  # 获取标签.
  # @return [Object]
  def index
    tags = Tag.page(params[:page]) # .per(10)
    render json: { resources: tags }
  end
end
  • 运行测试用例 rspec spec/requests/api/v1/tags_spec.rb:9 会返回

    1
    2
    3
    4
    5
    
    Run options: include {:locations=>{"./spec/requests/api/v1/tags_spec.rb"=>[9]}}
    .
    
    Finished in 0.06543 seconds (files took 0.66441 seconds to load)
    1 example, 0 failures
  • 虽然测试用例成功了,但没有区分是否当前用户创建的标签

  • 继续修改测试用例

spec/requests/api/v1/tags_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
require 'rails_helper'

RSpec.describe "Api::V1::Tags", type: :request do
  describe "获取标签" do
    it "未登录获取标签" do
      get '/api/v1/tags'
      expect(response).to have_http_status :unauthorized
    end
    it "已登录获取标签(分页)" do
      user = User.create email: '1@163.com'
      user2 = User.create email: '2@163.com'
      11.times do |i|
        Tag.create name: "tag#{i}", user_id: user.id, sign: '😄'
        Tag.create name: "tag#{i}", user_id: user2.id, sign: '😃'
      end

      get '/api/v1/tags', headers: user.generate_auth_header
      expect(response).to have_http_status :ok
      json = JSON.parse response.body
      expect(json['resources'].size).to eq 10

      get '/api/v1/tags', headers: user.generate_auth_header,
        params: { page: 2 }
      expect(response).to have_http_status :ok
      json = JSON.parse response.body
      expect(json['resources'].size).to eq 1
    end

  end
end
  • 数据库一般都包含不同用户创建的所有标签,请求只能筛选出当前用户的所有标签
  • 再次运行 rspec spec/requests/api/v1/tags_spec.rb:9 报错

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    rspec spec/requests/api/v1/tags_spec.rb:9
    Run options: include {:locations=>{"./spec/requests/api/v1/tags_spec.rb"=>[9]}}
    F
    
    Failures:
    
    1) Api::V1::Tags 获取标签 已登录获取标签(分页)
     Failure/Error: expect(json['resources'].size).to eq 1
    
       expected: 1
            got: 10
    
       (compared using ==)
     # ./spec/requests/api/v1/tags_spec.rb:25:in `block (3 levels) in <top (required)>'
    
    Finished in 0.09378 seconds (files took 0.69141 seconds to load)
    1 example, 1 failure
    
    Failed examples:
    
    rspec ./spec/requests/api/v1/tags_spec.rb:9 # Api::V1::Tags 获取标签 已登录获取标签(分页)
  • 期待第二页的数据为1,但实际为10

  • 修改 controller 实现,筛选当前用户的标签

app/controllers/api/v1/tags_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Api::V1::TagsController < ApplicationController
  # 获取标签.
  # @return [Object]
  def index
    current_user = User.find request.env["current_user_id"]
    return render status :not_found if current_user.nil?
    tags = Tag
      .where(user_id: current_user.id)
      .page(params[:page])
    render json: { resources: tags }
  end
end
  • 再次运行 rspec spec/requests/api/v1/tags_spec.rb:9 就成功了

写tags文档(测试代码) ⇧

新建文件 touch spec/acceptance/tags_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
require 'rails_helper'
require 'rspec_api_documentation/dsl'

resource "标签" do
  get "/api/v1/tags" do
    # 基础验证
    authentication :basic, :auth
    parameter :page, "页码"
    with_options scope: :resources do
      response_field :id, "ID"
      response_field :name, "标签名称"
      response_field :sign, "标签符号"
      response_field :user_id, "用户 ID"
      response_field :deleted_at, "删除时间"
    end

    let(:current_user) { User.create email: '1@163.com' }
    let(:auth) { "Bearer #{current_user.generate_jwt}" }

    example "获取标签" do
      11.times do |i|
        Tag.create name: "tag#{i}", sign: '😄',
          user_id: current_user.id
      end
      do_request
      expect(status).to eq Rack::Utils.status_code(:ok)
      json = JSON.parse response_body
      expect(json["resources"].size).to eq 10
    end
  end
end
  • 运行 bin/rake docs:generate 测试通过生成文档
  • 运行 pnpx http-server doc/api/. 查看文档,发现缺少分页信息 pager 字段

修改 app/controllers/api/v1/tags_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Api::V1::TagsController < ApplicationController
  # 获取标签.
  # @return [Object]
  def index
    current_user = User.find request.env["current_user_id"]
    return render status :not_found if current_user.nil?
    tags = Tag
      .where(user_id: current_user.id)
      .page(params[:page])

    render json: {
      resources: tags,
      pager: {
        page: params[:page] || 1,
        per_page: Tag.default_per_page,
        count: Tag.count
      }
    }
  end
end
  • 运行 bin/rake docs:generate 测试通过生成文档
  • 运行 pnpx http-server doc/api/. 查看文档

‘post /api/v1/tags’

  1. 创建 model,运行 db:migrate 已创建
  2. 创建 controller 已创建
  3. 写测试
  4. 写代码
  5. 写文档(测试代码)

2. 快速实现创建API ⇧

创建标签接口功能测试 ⇧

``


实现创建标签接口功能 ⇧

``


完成创建标签接口文档 ⇧

``


3. 快速实现更新API ⇧

更新标签接口功能测试 ⇧

``


实现更新标签接口功能 ⇧

``


完成更新标签接口文档 ⇧

``


4. 快速实现删除API ⇧

删除标签接口功能测试 ⇧

``


实现删除标签接口功能 ⇧

``


完成删除标签接口文档 ⇧

``


5. 快速实现单个读取API ⇧

``


6. $3 ⇧

``


7. 可能的报错信息 ⇧

密钥相关报错

  • 拿到代码后,可能需要重新创建密钥:https://docs.qq.com/doc/DU3ByQXZWbFpQRHND 。
  • 这一步是可选的,但如果遇到 ActiveSupport::MessageEncryptor::InvalidMessage 报错,那么你就必须重新创建密钥了。

·未完待续·

参考文章

相关文章

  • 无

  • 作者: Joel
  • 文章链接:
  • 版权声明
  • 非自由转载-非商用-非衍生-保持署名