42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
import { defineStore } from 'pinia'
|
|
import { shallowRef } from 'vue'
|
|
import type { Note, CreateNotePayload, UpdateNotePayload } from '@/types/note'
|
|
import { api } from '@/utils/api'
|
|
|
|
export const useNotesStore = defineStore('notes', () => {
|
|
const notes = shallowRef<Note[]>([])
|
|
const loading = shallowRef(false)
|
|
|
|
async function fetchNotes() {
|
|
loading.value = true
|
|
try {
|
|
notes.value = await api.get<Note[]>('/notes')
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
async function createNote(payload: CreateNotePayload = {}) {
|
|
const note = await api.post<Note>('/notes', payload)
|
|
notes.value = [note, ...notes.value]
|
|
return note
|
|
}
|
|
|
|
async function updateNote(id: number, payload: UpdateNotePayload) {
|
|
const updated = await api.put<Note>(`/notes/${id}`, payload)
|
|
notes.value = notes.value.map((n) => (n.id === id ? updated : n))
|
|
return updated
|
|
}
|
|
|
|
async function deleteNote(id: number) {
|
|
await api.delete(`/notes/${id}`)
|
|
notes.value = notes.value.filter((n) => n.id !== id)
|
|
}
|
|
|
|
function getNote(id: number): Note | undefined {
|
|
return notes.value.find((n) => n.id === id)
|
|
}
|
|
|
|
return { notes, loading, fetchNotes, createNote, updateNote, deleteNote, getNote }
|
|
})
|