File size: 2,124 Bytes
8a49743
de10f77
8a49743
de10f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a49743
de10f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a49743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de10f77
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { client, collections, db } from '$lib/server/db';
import type { Product } from '$lib/types/Product';
import { error, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { omit } from 'lodash';

export const load: PageServerLoad = async ({ params }) => {
	const product = await collections.products.findOne({ _id: params.id });

	if (!product) {
		throw error(404, 'Produit non trouvé');
	}

	const pictures = await collections.pictures
		.find({ productId: params.id })
		.sort({ createdAt: 1 })
		.toArray();
	product.photos = pictures;

	return {
		product
	};
};

export const actions: Actions = {
	update: async ({ request, params }) => {
		const formData = await request.formData();

		const update = {
			...(formData.get('name') && { name: formData.get('name') as string }),
			...(formData.get('state') && { state: formData.get('state') as Product['state'] }),
			...(formData.get('kind') && { kind: formData.get('kind') as Product['kind'] }),
			...(formData.get('description') && {
				description: (formData.get('description') as string).replaceAll('\r', '')
			}),
			...(formData.get('price') && { price: Number(formData.get('price')) }),
			updatedAt: new Date()
		};

		const product = await collections.products.findOneAndUpdate(
			{ _id: params.id },
			{ $set: update },
			{ returnDocument: 'after' }
		);

		if (!product.value) {
			throw error(404, 'Produit non trouvé');
		}

		return {};
	},

	delete: async ({ params }) => {
		await client.withSession(async (session) => {
			const product = await collections.products.findOneAndDelete({ _id: params.id });

			if (!product.value) {
				throw error(404);
			}

			const pictures = await collections.pictures
				.find({ productId: params.id }, { session })
				.toArray();

			await collections.pictures.deleteMany(
				{ _id: { $in: pictures.map((p) => p._id) } },
				{ session }
			);
			await collections.picturesFs.deleteMany(
				{
					_id: { $in: pictures.flatMap((p) => p.storage.map((s) => s._id)) }
				},
				{ session }
			);
		});

		throw redirect(303, '/admin/produits');
	}
};