Thai Grails

กิจกรรมล่าสุดของไซต์

13.1 REST

13.1 REST

- ตัว REST นั้นไม่ใช่เทคโนโลยี แต่เป็นสถาปัตยกรรมที่เรียบง่าย
- ติดต่อสื่อสารด้วย XML, JSON
- ทำงานผ่าน HTTP methods ต่างๆ  เช่น GET, PUT, POST, DELETE โดยในแต่ละ method จะจับคู่กับการกระทำดังนี้

GET สำหรับดึงข้อมูล
PUT สำหรับสร้างข้อมูล
POST สำหรับแก้ไขข้อมูล
DELETE สำหรับลบข้อมูล

- จะสังเกตได้ว่า REST จะคล้ายๆ CRUD ( Create Read Update Delete )


URL patterns
ขั้นตอนแรกในการสร้าง REST ด้วย Grails นั้นด้วยการปรับค่าใน url mappings ดังนี้
ทำการปรับแต่ใน file  /grails-app/config/UrlMappings.groovy

static mappings = {
   "/product/$id?"(resource:"product")
}


คำอธิบาย
ทำการ mapping  URI /product ไปยัง ProductController และใน HTTP method จะทำงานใน action ต่างๆ ใน controller ดังนี้

 Method   Action
 GET show
 PUT update
 POST save
 DELETE delete


แต่สามารถยกเลิกหรือเปลี่ยนแปลงการทำงานของ HTTP method แต่ละตัวผ่านทาง URL Mappings ดังนี้

"/product/$id"(controller:"product"){
    action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]
}

อย่างไรก็ตาม Grails นั้นไม่ได้เตรียมการ marshaling ข้อมูล XML หรือ JSON แบบอัตโนมัติมาให้ แต่สามารถปรับแต่งเพิ่มเติม
ได้ด้วยการเพิ่ม parseRequest ใน URL Mapping ดังนี้

"/product/$id"(controller:"product", parseRequest:true){
    action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]
}



XML Marshaling - Reading
ในทุกๆ controller นั้นสามารถทำ xml marshaling ผ่าน GET method ได้ดังนี้

import grails.converters.*
class ProductController {
    def show = {
        if(params.id && Product.exists(params.id)) {
            def p = Product.findByName(params.id)
            render p as XML
        }
        else {
            def all = Product.list()
            render all as XML
        }
    }
    ..
}



XML Marshalling - Updating
ทำการแก้ไขข้อมูลผ่าน PUT และ POST method โดยสามารถอ่านข้อมูล XML ที่ส่งเข้ามาผ่าน param object
และสร้างผลลัพธ์เป็น XML  กลับไป ดังนี้

ข้อมูล XML ที่ส่งเข้ามา
<?xml version="1.0" encoding="ISO-8859-1"?>
<product>
    <name>MacBook</name>
    <vendor id="12">
        <name>Apple</name>
     </vender>
</product>


สามารถทำการอ่านหรือ parse ข้อมูล XML นี้ด้วยวิธีการของ Data Biding ผ่าน param object ดังนี้

def save = {
    def p = new Product(params['product'])

    if(p.save()) {
        render p as XML
    } else {
        render p.errors
    }
}


คำอธิบาย
- อ่านข้อมูล XML ที่ส่งผ่านมาทาง request ด้วย param object
- อ่านข้อมูลผ่านตัวแปรชื่อ product
- ทำการสร้างและ bind ข้อมูล XML ผ่าน constructor ของ Domain class ชื่อ Product
- ถ้าเปลี่ยนข้อมูลจาก XML เป็น JSON ก็สามารถทำได้โดยไม่ต้องเปลี่ยนแปลงส่วนการสร้างและ bind ทำให้สะดวกมากยิงขึ้น

แต่ถ้ากระบวนการสร้างและ bind เกิดข้อผิดพลาดแล้ว Grails validation จะแสดงข้อความในลักษณะดังนี้

<error>
   <message>The property 'title' of class 'Person' must be specified</message>
</error>