如何在葡萄 api 应用程序中拆分东西? [英] How to split things up in a grape api app?
问题描述
在我看到的每个例子中,人们只实现了一个巨大的 api.rb 文件.例如:
In every examples I see, people only implement one giant api.rb file. Ex:
虽然这种方法按原样运行良好,但它很快就会变得拥挤且难以维护,因此我想在我的应用程序上进行拆分.
While this approach works fine as is, it can quickly become crowded and difficult to maintain so I would like to split things up on my app.
例如,我想从我的资源中拆分我的实体,然后在不同的文件之间拆分我的资源.例如:
For instance, I would like to split my entities from my resources, and then split up my resources between different files. For examples:
app
- api
api.rb
- entities
- weblog.rb
- post.rb
- comment.rb
- resources
- weblog.rb
- post.rb
- comment.rb
现在,api.rb 将类似于:
require 'grape'
module Blog
class API < Grape::API
prefix "api"
end
end
app/api/entities/post.rb 类似于:
module Blog
module Entities
class Post < Grape::Entity
root 'posts', 'posts'
expose :id
expose :content
end
end
end
app/api/resources/post.rb 类似于:
module Blog
class API < Grape::API
resource :posts do
get do
present Post.all, with: Blog::Entities::Post
end
desc "returns the payment method corresponding to a certain id"
params do
requires :id, :type => Integer, :desc => "Post id."
end
get ':id' do
present Post.find(params[:id]), with: Blog::Entities::Post
end
end
end
end
执行此操作时,我们会遇到以下消息:
When we do this, we encounter the following message:
预期/blog-app/api/resources/post.rb 来定义 Post
Expected /blog-app/api/resources/post.rb to define Post
<小时>
解决方案(感谢 dB. 和我的同事)
您必须将结构更改为:
app
- api
api.rb
- resources
- post_api.rb
然后,在post_api.rb
module Blog
class Resources::PostAPI < Grape::API
resource :posts do
get do
present Post.all
end
end
end
end
最后,api.rb 变成:
require 'grape'
module Blog
class API < Grape::API
prefix 'api'
version 'v1', :using => :path
format :json
mount Blog::Resources::PostAPI => '/'
end
end
现在 /api/v1/posts
应该可以工作了 :)
Now /api/v1/posts
should work :)
推荐答案
post.rb 中的类应该是 Post,而不是 API.然后就可以在类 API 中挂载 Post API.
The class in post.rb should be Post, not API. Then you can mount the Post API inside class API.
class API < Grape::API
mount Blog::Post => '/'
end
为了避免混淆,我也将 Post 放在 Resources 命名空间中,或者将其重命名为 PostAPI.
To avoid confusion I would put Post in a Resources namespace, too or rename it to PostAPI.
这篇关于如何在葡萄 api 应用程序中拆分东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!