refactor: update api /api/attachment

This commit is contained in:
purocean
2024-07-11 22:26:04 +08:00
parent 1097ac2c92
commit 60b66f73fb
2 changed files with 27 additions and 7 deletions
+24 -3
View File
@@ -206,13 +206,34 @@ const attachment = async (ctx: any, next: any) => {
await file.upload(repo, buffer, path)
ctx.body = result('ok', 'success', path)
} else if (ctx.method === 'GET') {
const { repo, path } = ctx.query
let { repo, path } = ctx.query
if (!repo || !path) {
const filePath = ctx.path.replace('/api/attachment', '')
const arr = filePath.split('/')
repo = arr[1]
path = decodeURI(arr.slice(2).join('/'))
}
if (!repo || !path) {
throw new Error('Invalid path.')
}
checkPrivateRepo(ctx, repo)
noCache(ctx)
ctx.type = mime.getType(path)
ctx.body = await file.read(repo, path)
try {
ctx.body = await file.read(repo, path)
ctx.type = mime.getType(path)
} catch (error: any) {
if (error.code === 'ENOENT') {
ctx.status = 404
ctx.body = result('error', 'Not found')
} else {
throw error
}
}
}
} else {
await next()
+3 -4
View File
@@ -3,7 +3,7 @@ import filenamify from 'filenamify/browser'
import type { Doc, FindInRepositoryQuery } from '@fe/types'
import * as api from '@fe/support/api'
import { FLAG_DEMO, HELP_REPO_NAME } from '@fe/support/args'
import { binMd5, quote, fileToBase64URL, getLogger, removeQuery } from '@fe/utils'
import { binMd5, quote, fileToBase64URL, getLogger } from '@fe/utils'
import { basename, resolve, extname, dirname, relative, isBelongTo } from '@fe/utils/path'
import { dayjs } from '@fe/context/lib'
import { useModal } from '@fe/support/ui/modal'
@@ -27,13 +27,12 @@ export function getAttachmentURL (doc: Doc, opts: { origin: boolean } = { origin
throw new Error('Document type must be file')
}
const fileName = removeQuery(doc.name)
const repo = doc.repo
const filePath = doc.path
const filePath = resolve(doc.path)
const uri = repo === HELP_REPO_NAME
? `/api/help/file?path=${encodeURIComponent(filePath)}`
: `/api/attachment/${encodeURIComponent(fileName)}?repo=${repo}&path=${encodeURIComponent(filePath)}`
: `/api/attachment/${encodeURIComponent(repo)}${encodeURI(filePath)}`
if (opts.origin) {
return `${window.location.origin}${uri}`