notea/pages/api/trash.ts

65 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-03-07 12:04:53 +03:00
import { api, ApiRequest } from 'services/api'
2021-03-07 15:27:30 +03:00
import { jsonToMeta, metaToJson } 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)
.get(async (req, res) => {
res.json(await req.treeStore.trash.get())
})
.post(async (req, res) => {
2021-03-07 12:04:53 +03:00
const { action, data } = req.body as {
action: 'delete' | 'restore'
data: any
}
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':
await restoreNote(req, data.id)
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)
await req.treeStore.trash.removeItem(id)
}
async function restoreNote(req: ApiRequest, id: string) {
const notePath = getPathNoteById(id)
const oldMeta = await req.store.getObjectMeta(notePath)
2021-03-07 15:27:30 +03:00
const oldMetaJson = metaToJson(oldMeta)
2021-03-07 12:04:53 +03:00
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',
})
await req.treeStore.trash.removeItem(id)
2021-03-07 15:27:30 +03:00
await req.treeStore.addItem(
id,
oldMetaJson.deleted === NOTE_DELETED.DELETED ? oldMetaJson.pid : 'root'
)
2021-03-07 12:04:53 +03:00
}