60 lines
1.6 KiB
JavaScript
60 lines
1.6 KiB
JavaScript
|
|
// 薄薄一层 fetch 封装。错误统一抛 Error(message)。
|
||
|
|
|
||
|
|
async function jsonOrThrow(res) {
|
||
|
|
if (!res.ok) {
|
||
|
|
const text = await res.text().catch(() => '')
|
||
|
|
throw new Error(text || `${res.status} ${res.statusText}`)
|
||
|
|
}
|
||
|
|
return res.json()
|
||
|
|
}
|
||
|
|
|
||
|
|
export function listPieces() {
|
||
|
|
return fetch('/api/pieces').then(jsonOrThrow)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function getPiece(id) {
|
||
|
|
return fetch(`/api/pieces/${id}`).then(jsonOrThrow)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function createPiece(body) {
|
||
|
|
return fetch('/api/pieces', {
|
||
|
|
method: 'POST',
|
||
|
|
headers: { 'Content-Type': 'application/json' },
|
||
|
|
body: JSON.stringify(body),
|
||
|
|
}).then(jsonOrThrow)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function patchPiece(id, body) {
|
||
|
|
return fetch(`/api/pieces/${id}`, {
|
||
|
|
method: 'PATCH',
|
||
|
|
headers: { 'Content-Type': 'application/json' },
|
||
|
|
body: JSON.stringify(body),
|
||
|
|
}).then(jsonOrThrow)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function deletePiece(id) {
|
||
|
|
return fetch(`/api/pieces/${id}`, { method: 'DELETE' }).then(jsonOrThrow)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function recordPlay(id) {
|
||
|
|
return fetch(`/api/pieces/${id}/play`, { method: 'POST' }).then(jsonOrThrow)
|
||
|
|
}
|
||
|
|
|
||
|
|
// `role`: null | 'chord' | 'numbered' | 'staff'
|
||
|
|
export function uploadAttachments(pieceId, files, role) {
|
||
|
|
const fd = new FormData()
|
||
|
|
for (const f of files) fd.append('files', f, f.name)
|
||
|
|
const url = role
|
||
|
|
? `/api/pieces/${pieceId}/attachments?role=${encodeURIComponent(role)}`
|
||
|
|
: `/api/pieces/${pieceId}/attachments`
|
||
|
|
return fetch(url, { method: 'POST', body: fd }).then(jsonOrThrow)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function deleteAttachment(id) {
|
||
|
|
return fetch(`/api/attachments/${id}`, { method: 'DELETE' }).then(jsonOrThrow)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function attachmentUrl(id) {
|
||
|
|
return `/api/attachments/${id}`
|
||
|
|
}
|