notea/pages/api/trash.ts

60 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-03-07 12:04:53 +03:00
import { api, ApiRequest } from 'services/api'
2021-03-08 15:07:50 +03:00
import { jsonToMeta } from 'services/meta'
2021-03-07 09:53:29 +03:00
import { useAuth } from 'services/middlewares/auth'
import { useStore } from 'services/middlewares/store'
2021-03-07 12:04:53 +03:00
import { getPathNoteById } from 'services/note-path'
import { NOTE_DELETED } from 'shared/meta'
2021-03-07 09:53:29 +03:00
export default api()
.use(useAuth)
.use(useStore)
.post(async (req, res) => {
2021-03-07 12:04:53 +03:00
const { action, data } = req.body as {
action: 'delete' | 'restore'
2021-03-08 15:07:50 +03:00
data: {
id: string
parentId?: string
}
2021-03-07 12:04:53 +03:00
}
2021-03-07 09:53:29 +03:00
switch (action) {
case 'delete':
2021-03-07 12:04:53 +03:00
await deleteNote(req, data.id)
break
case 'restore':
2021-03-08 15:07:50 +03:00
await restoreNote(req, data.id, data.parentId)
2021-03-07 09:53:29 +03:00
break
default:
return res.APIError.NOT_SUPPORTED.throw('action not found')
}
res.end()
})
2021-03-07 12:04:53 +03:00
async function deleteNote(req: ApiRequest, id: string) {
const notePath = getPathNoteById(id)
await req.store.deleteObject(notePath)
2021-03-08 18:00:45 +03:00
await req.treeStore.deleteItem(id)
2021-03-07 12:04:53 +03:00
}
2021-03-08 15:07:50 +03:00
async function restoreNote(req: ApiRequest, id: string, parentId = 'root') {
2021-03-07 12:04:53 +03:00
const notePath = getPathNoteById(id)
const oldMeta = await req.store.getObjectMeta(notePath)
let meta = jsonToMeta({
date: new Date().toISOString(),
deleted: NOTE_DELETED.NORMAL.toString(),
})
if (oldMeta) {
meta = new Map([...oldMeta, ...meta])
}
await req.store.copyObject(notePath, notePath, {
meta,
contentType: 'text/markdown',
})
2021-03-08 15:07:50 +03:00
await req.treeStore.restoreItem(id, parentId)
2021-03-07 12:04:53 +03:00
}