การเขียน web service server (ต่อ)
เมื่อคุณใช้ dispatching mode :delegated หรือ layered คุณต้องมีการกำหนด method ทีมีในแต่ละ model ที่ไฟล์ API ซึ่งมันจะยากกว่าแบบ :direct mode เล็กน้อย แต่เป็นทางเลือกที่ีดีที่สุด สำหรับการพัฒนาที่ใหญ่และมีความซับซ้อน เนื่องจากมันมีความยืดหยุ่นกว่า สำหรับ :direct mode จะเหมาะกับ service ที่ง่ายและมีคุณลักษณะ (feature) น้อย
ใน Rails การเขียนโปรแกรมแบบ :delegated และ layered จะเหมือนกัน แต่จะต่างกันตรง
end point URL ที่ client จะใช้ access wen service แบบ :delegated mode client จะใช้
distinct URL สำหรับแต่ละเมธอดใน API เช่น yourdomain.com/product/getdata , yourdomain.com/product/getprice ส่วนแบบ :layered client จะใช้ URL เหมือนกันในการเรียกแต่ละเมธอด และ AWS จะเป็นตัวบอกเส้นทางการร้องขอข้อมูลจาก header ในฝั่ง client เช่น yourdomain.com/product/api ถ้า SOAP client ใช้ไฟล์
WSDL เพื่อกำหนดการเรียกเมธอด จึงไม่มีความแตกต่างในการเขียน web service server ทั้ง 2 แบบ
ตัวอย่างการเขียน dispatching mode แบบ :delegated
class StatsApi < ActionWebService::API::Base
api_method :listgames, #A line auto generate
:expects => [{:year => :int}],
:returns => [[:string]]
api_method :getgamestats, #A line auto generate
:expects => [{:username => :string} , {:game => :string}],
:returns => [[Footballstats]]
end
class StatsController < ApplicationController
wsdl_service_name 'Stats' #A line auto generate
wsdl_namespace 'urn:sportsxml'
web_service_dispatching_mode :delegated
web_service :footballstats, Getstats.new
web_service_scaffold :test
def about
#info about our service
#accessed through reg. web browser
#http://localhost:3000/stats/about
end
end
class Getstats < ActionWebService::Base
web_service_api StatsApi
before_invocation :checkusername, :except => [:listgames]
def getgamestats(username, gamename)
# get the stats for a specific game
stats = []
statdetails = Footballgames.find_by_sql(
["select statfor, as stattype, statvalue, statlogged from gametimestats
where gamename = ?",gamename])
statdetails.each do |rec|
stats << Footballstats.new(:statfor => rec.statfor, :stattype => rec.stattype,
:statvalue => rec.statvalue, :statlogged => rec.statlogged)
end
return stats
end
def listgames(year)
# get a list of football games stats are available for
Footballgames.find_by_sql(["select distinct gamename from gametimestats
where gametimestats_year = ?", year]).map {|rec| rec.gamename}
end
protected
def checkusername(name, args)
if (args[0] != "kevin")
raise "Access denied!"
end
end
end
- ภาพแสดงการทดสอบ
- ลิงค์ไปยังเมธอดตามที่เรียก
- เลือก SOAP
- ผลลัพธ์จากการเลือก SOAP
- ผลลัพธ์จากการเลือก XML-RPC