58 lines
1.8 KiB
TypeScript
58 lines
1.8 KiB
TypeScript
import type { HttpContext } from '@adonisjs/core/http'
|
|
import ComputerPicture from '#models/computer_picture'
|
|
import Computer from '#models/computer'
|
|
import { v4 as uuid } from 'uuid'
|
|
import type { Image } from '#types/UItypes'
|
|
import { existsSync, unlinkSync } from 'node:fs'
|
|
|
|
async function handlePictures(
|
|
pictures: Image[],
|
|
request: HttpContext['request'],
|
|
computer: Computer
|
|
) {
|
|
const currentPictures = await computer.related('pictures').query()
|
|
const currentPictureIds = currentPictures.map((picture) => picture.id)
|
|
const imagesToRemove = currentPictureIds.filter(
|
|
(id: number) => !pictures.some((picture) => 'id' in picture && picture.id === id)
|
|
)
|
|
|
|
await Promise.all(
|
|
pictures.map(async (picture: Image, index: number) => {
|
|
if ('id' in picture) {
|
|
const existingPicture = await ComputerPicture.findOrFail(picture.id)
|
|
existingPicture.order = picture.order
|
|
await existingPicture.save()
|
|
} else {
|
|
const image = request.file(`pictures[${index}][file]`, {
|
|
size: '2mb',
|
|
extnames: ['jpg', 'png', 'jpeg', 'svg'],
|
|
})
|
|
if (image) {
|
|
const imageName = `img_${uuid()}.${image.extname}`
|
|
await image.move(`uploads/computer_${computer.id}`, {
|
|
name: imageName,
|
|
})
|
|
await ComputerPicture.create({
|
|
computerId: computer.id,
|
|
link: `/uploads/computer_${computer.id}/${imageName}`,
|
|
order: picture.order,
|
|
})
|
|
}
|
|
}
|
|
})
|
|
)
|
|
|
|
await Promise.all(
|
|
imagesToRemove.map(async (id: number) => {
|
|
const picture = await ComputerPicture.findOrFail(id)
|
|
const filePath = `uploads/computer_${computer.id}/${picture.link.split('/').pop()}`
|
|
if (existsSync(filePath)) {
|
|
unlinkSync(filePath)
|
|
}
|
|
await picture.delete()
|
|
})
|
|
)
|
|
}
|
|
|
|
export { handlePictures }
|