Files
sori.studio/server/utils/member-avatar.js

63 lines
1.7 KiB
JavaScript

import { join, relative } from 'node:path'
import { createError } from 'h3'
import { getPostgresClient } from '../repositories/postgres-client'
const managedAvatarPrefix = '/uploads/members/avatars/'
/**
* 회원 전용 썸네일 URL인지 확인한다.
* @param {string} url - 대상 URL
* @returns {boolean} 회원 썸네일 여부
*/
export const isManagedAvatarUrl = (url) => String(url || '').startsWith(managedAvatarPrefix)
/**
* 회원 썸네일 URL을 실제 파일 경로로 변환한다.
* @param {string} url - 썸네일 URL
* @returns {string} 파일 시스템 경로
*/
export const resolveMemberAvatarPath = (url) => {
if (!isManagedAvatarUrl(url)) {
throw createError({
statusCode: 400,
message: '회원 썸네일 경로가 아닙니다.'
})
}
const decodedUrl = decodeURIComponent(url)
const filePath = join(process.cwd(), 'public', decodedUrl)
const uploadRoot = join(process.cwd(), 'public', 'uploads')
const relativePath = relative(uploadRoot, filePath)
if (relativePath.startsWith('..') || relativePath === '') {
throw createError({
statusCode: 400,
message: '회원 썸네일 경로가 올바르지 않습니다.'
})
}
return filePath
}
/**
* 프로필에서 썸네일 URL을 끊을 때 `media_metadata` 행만 제거한다. 디스크 파일은 유지해 관리자 미디어(썸네일 탭)에서 미사용 자산으로 확인·삭제할 수 있게 한다.
* @param {string} url - 정리 대상 URL
* @returns {Promise<void>}
*/
export const removeManagedAvatarAsset = async (url) => {
if (!isManagedAvatarUrl(url)) {
return
}
const sql = getPostgresClient()
if (!sql) {
return
}
await sql`
DELETE FROM media_metadata
WHERE url = ${url}
`
}