Fitted
0.1.7
使用 ECMAScript 裝飾器(目前為第 2 階段提案)執行 HTTP 請求並管理回應處理,這是管理資料如何流經應用程式網路層的簡單易讀的方式。
兩個主要部分,實際執行請求的方法裝飾器,以及允許您處理來自伺服器的回應的轉換和處理方式的類別裝飾器。
最簡單的範例只是從 JSON 端點取得資料:
import { get } from 'fitted' ;
class HackerNews {
@ get ( 'https://hacker-news.firebaseio.com/v0/topstories.json' )
topstories ( request , response ) {
return request ( { } , response ) ;
}
}並獲取:
const hackerNews = new HackerNews ( ) ;
const topstories = await hackerNews . topstories ( ) ;
console . log ( topstories ) ; 基本要求
使用get裝飾器你可以觸發GET請求:
import { get } from 'fitted' ;
class HackerNews {
@ get ( 'https://hacker-news.firebaseio.com/v0/topstories.json' )
topstories ( request , response ) {
return request ( { } , response ) ;
}
}合併參數
為了將 params 與 url 合併,我們使用 url-template,它使用大括號封裝要合併的變數。
import { get } from 'fitted' ;
class HackerNews {
@ get ( 'https://hacker-news.firebaseio.com/v0/item/{id}.json' )
item ( id , request , response ) {
return request ( {
template : {
id : 123
}
} , response ) ;
}
}基本網址
大多數時候,您的端點將共享相同的基本 url,因此 Fitted 允許您設定一個基本 url,該基本 url 將作為方法裝飾器中設定的所有路徑的前綴。
import { base , get } from 'fitted' ;
@ base ( 'https://hacker-news.firebaseio.com/v0/' )
class HackerNews {
@ get ( 'item/{id}.json' )
item ( id , request , response ) {
return request ( {
template : {
id : 123
}
} , response ) ;
}
}傳送數據
若要將資料新增至post 、 put和destroy請求並為get請求指定查詢字串,您需要將data物件新增至請求定義。
import { put } from 'fitted' ;
class HackerNews {
@ put ( 'https://hacker-news.firebaseio.com/v0/item/{id}.json' )
item ( id , name , request , response ) {
return request ( {
template : {
id : 123
} ,
data : {
name : name
}
} , response ) ;
}
}要求裝飾
通常,所有端點都有相同的請求要求,例如,要求所有端點都設定一些標頭。為此,可以使用@request裝飾器。它將獲取傳遞的每個請求的配置,然後將其交給驅動程式。
import { get , request } from 'fitted' ;
const myRequestHandler = config => {
config . headers = {
'accept' : 'application/json'
}
return config ;
}
@ request ( myRequestHandler )
class HackerNews {
@ get ( 'item/{id}.json' )
item ( id , request , response ) {
return request ( {
template : {
id : id
}
} , response ) ;
}
}回應處理
當伺服器回應包含application/json Content-Type標頭時,Fitting 會自動提供給JSON.parse函數,以便產生的 Promise 將輸出對應的物件。
任何其他Content-Type將導致拋出錯誤並要求您實作自己的處理程序。
自訂回應處理器
當您的端點傳回需要一些預處理的內容時,您可以在 api 定義中為所有端點定義一個處理器。它由一個函數組成,該函數接收來自伺服器的回應並將解析後的資料傳遞給回應物件。
import { get , processor } from 'fitted' ;
const myProcessor = response => {
const data = JSON . parse ( response . getBody ( ) ) ;
response . setBody ( data ) ;
return data ;
}
@ processor ( myProcessor )
class HackerNews {
@ get ( 'item/{id}.json' )
item ( id , request , response ) {
return request ( {
template : {
id : id
}
} , response ) ;
}
}