處理 RESTful API 的 GET 回傳 Array Object 在實務上一定會碰到,傳統會使用 Promise 處理,事實上 Future 更適合 Point-free。
Version
Vue 3.0.11
Fluture 14.0.0
Future
按下 Get Books
會從 API 獲得 Array Object。
api/getBook_.js
import axios from 'axios'
import { encaseP } from 'fluture'
export default _ => encaseP (axios) ('books')
encaseP
:將axios
轉成回傳 Future 的 function 後,再傳入 url
App.vue
<template lang='pug'>
div
button(@click='onClick') Get Books
ul
li(v-for='x in books') {{ x.title }} / {{ x.price }}
</template>
<script setup>
import { ref } from 'vue'
import { write } from 'vue3-fp'
import { pipe, map, prop, path } from 'ramda'
import { error } from 'wink-fp'
import { fork, mapRej } from 'fluture'
import getBooks from '/src/api/getBooks_'
let books = ref ([])
let onClick = pipe (
getBooks,
map (prop ('data')),
mapRej (path (['response', 'data', 'error'])),
fork (error) (write (books))
)
</script>
18 行
let onClick = pipe (
getBooks,
map (prop ('data')),
mapRej (path (['response', 'data', 'error'])),
fork (error) (write (books))
)
使用 pipe
組合 onClick
:
getBooks
:呼叫 API 回傳 Futuremap (prop ('data'))
:在 Resolved Future 內取得data
mapRej (path (['response', 'data', 'error']))
:在 Rejected Future 內取得response.date.error
fork (error) (write (books))
:從 Future 內處理 Rejected Future,並從 Resolved Future 內取出資料寫入books
state
Conclusion
- 透過
mapRef
可在pipe
內處理 Rejected Future,不必再如otherwise
需另外組合 function 處理