2025-12-04 10:04:21 +08:00

77 lines
2.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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
}
}