77 lines
2.3 KiB
JavaScript
77 lines
2.3 KiB
JavaScript
// app/composables/apiArticles.js
|
||
// 统一封装“文章相关”接口,基于你已有的 useApi()
|
||
|
||
import { useApi } from './useApi'
|
||
|
||
/**
|
||
* RealWorld 风格的后端:
|
||
* - 创建:POST /articles body: { article: {...} }
|
||
* - 获取明细:GET /articles/:slug
|
||
* - 更新:PUT /articles/:slug body: { article: {...} }
|
||
* - 删除:DELETE /articles/:slug
|
||
* - 列表:GET /articles params: { tag, author, favorited, limit, offset }
|
||
* - 订阅流:GET /articles/feed params: 同上(需要登录)
|
||
* - 点赞:POST /articles/:slug/favorite
|
||
* - 取消赞:DELETE /articles/:slug/favorite
|
||
* - 标签:GET /tags
|
||
*/
|
||
export function useArticlesApi() {
|
||
const api = useApi()
|
||
|
||
// 表单 -> 后端 article payload
|
||
const toPayload = (form) => ({
|
||
title: form.title?.trim() || '',
|
||
description: form.description?.trim() || '',
|
||
body: form.body ?? '',
|
||
tagList: Array.isArray(form.tagList) ? form.tagList : []
|
||
})
|
||
|
||
// 创建
|
||
const create = (formOrArticle) => {
|
||
const article =
|
||
formOrArticle && formOrArticle.title !== undefined
|
||
? toPayload(formOrArticle)
|
||
: (formOrArticle || {})
|
||
return api.post('/articles', { article })
|
||
}
|
||
|
||
// 更新
|
||
const update = (slug, formOrArticle) => {
|
||
const article =
|
||
formOrArticle && formOrArticle.title !== undefined
|
||
? toPayload(formOrArticle)
|
||
: (formOrArticle || {})
|
||
return api.put(`/articles/${encodeURIComponent(slug)}`, { article })
|
||
}
|
||
|
||
// 删除
|
||
const remove = (slug) => api.del(`/articles/${encodeURIComponent(slug)}`)
|
||
|
||
// 明细
|
||
const get = (slug) => api.get(`/articles/${encodeURIComponent(slug)}`)
|
||
|
||
// 列表(公共)
|
||
const list = (params = {}) => api.get('/articles', params)
|
||
|
||
// 订阅流(需要登录)
|
||
const feed = (params = {}) => api.get('/articles/feed', params)
|
||
|
||
// 喜欢/取消喜欢
|
||
const addFavorite = (slug) => api.post(`/articles/${encodeURIComponent(slug)}/favorite`)
|
||
const removeFavorite = (slug) => api.del(`/articles/${encodeURIComponent(slug)}/favorite`)
|
||
|
||
// 标签列表
|
||
const listTags = () => api.get('/tags')
|
||
|
||
return {
|
||
// 主要增删改查
|
||
create, update, remove, get, list, feed,
|
||
// 互动
|
||
addFavorite, removeFavorite,
|
||
// 其他
|
||
listTags,
|
||
// 工具(可选导出,发文页也能复用)
|
||
toPayload
|
||
}
|
||
}
|