import fetchJson from 'helpers/fetchJson' import saveFile from 'helpers/saveFile' import filename from '../helpers/fileName' export const getNote = async (note, setFetchedNote, t, setPopup, callback) => { try { const { content } = await fetchJson(`/api/notes/${note.noteId}`) setFetchedNote({ ...note, content }) callback() } catch (err) { setFetchedNote() setPopup({ content: t('notes_open_error'), time: 2000, error: true }) } } export const addNote = async (e, mutateNotes, setAction, t, setPopup) => { const content = e.currentTarget.content.value const title = e.currentTarget.title.value try { mutateNotes( await fetchJson('/api/notes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title, content }) }) ) setPopup({ content: t('notes_added'), time: 2000 }) setAction('') } catch (e) { setPopup({ content: t('notes_added_error'), time: 2000, error: true }) } } export const updateNote = async (e, note, mutateNotes, setAction, t, setPopup) => { const content = e.currentTarget.content.value const title = e.currentTarget.title.value const { _id, noteId } = note try { mutateNotes( await fetchJson(`/api/notes/${_id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title, noteId, content }) }) ) setPopup({ content: t('notes_updated'), time: 2000 }) setAction('') } catch (e) { setPopup({ content: t('notes_updated_error'), time: 2000, error: true }) } } export const removeNote = (e, _id, mutateNotes, t, setPopup, setAction) => { e.stopPropagation() const remove = async () => { try { await mutateNotes( await fetchJson(`/api/notes/${_id}`, { method: 'DELETE' }) ) setPopup({ content: t('notes_removed'), time: 2000 }) setAction('') } catch (err) { setPopup({ content: t('notes_removed_error'), time: 2000, error: true }) } } setPopup({ content: t('notes_remove_confirm'), yes: { label: t('remove'), action: remove }, no: { label: t('cancel'), action: async () => {} }, error: true }) } export const exportNote = async note => { const { title } = note const { content } = note.content ? note : await fetchJson(`/api/notes/${note.noteId}`) saveFile(content, filename(title), 'text/plain') }