68 lines
1.6 KiB
TypeScript
68 lines
1.6 KiB
TypeScript
import {ResourceType} from '@prisma/client'
|
|
import im, {Features} from 'imagemagick'
|
|
import fs from 'node:fs'
|
|
import path from 'node:path'
|
|
|
|
import {db} from '@/lib/db/prisma/client'
|
|
|
|
export const PUBLIC_UPLOAD_PRODUCTS_DIR = '/uploads/products'
|
|
export const UPLOAD_PRODUCTS_DIR = path.resolve(
|
|
`./public${PUBLIC_UPLOAD_PRODUCTS_DIR}`
|
|
)
|
|
|
|
export function getFilesByProductId(id: number, fullPath: boolean = true) {
|
|
const files = fs
|
|
.readdirSync(UPLOAD_PRODUCTS_DIR)
|
|
.filter(file => file.startsWith(`${id}-`))
|
|
|
|
return !fullPath
|
|
? files
|
|
: files.map(file => path.join(UPLOAD_PRODUCTS_DIR, file))
|
|
}
|
|
|
|
interface ProductImage {
|
|
type: string
|
|
productId: number
|
|
filesize: number
|
|
height: number
|
|
width: number
|
|
'mime type'?: string
|
|
mimeType: string
|
|
quality: number
|
|
properties: {
|
|
signature: string
|
|
}
|
|
signature: string
|
|
}
|
|
|
|
export async function getMetaOfFile(id: number) {
|
|
getFilesByProductId(id).forEach(file => {
|
|
im.identify(file, async (err, features) => {
|
|
if (err) throw err
|
|
// { format: 'JPEG', width: 3904, height: 2622, depth: 8 }
|
|
const data = features as ProductImage
|
|
|
|
try {
|
|
const result = await db.productResource.create({
|
|
data: {
|
|
type: 'IMAGE' as ResourceType,
|
|
productId: id,
|
|
uri: PUBLIC_UPLOAD_PRODUCTS_DIR + '/' + path.basename(file),
|
|
filesize: parseInt(data.filesize as unknown as string),
|
|
height: data.height,
|
|
width: data.width,
|
|
quality: data.quality,
|
|
mimeType: data['mime type'] || 'image/*',
|
|
signature: data.properties.signature
|
|
//meta: features
|
|
}
|
|
})
|
|
|
|
//return result
|
|
} catch (e) {
|
|
//console.log(e)
|
|
}
|
|
})
|
|
})
|
|
}
|