diff --git a/controllers/events.ts b/controllers/events.ts index de803b4..42eca58 100644 --- a/controllers/events.ts +++ b/controllers/events.ts @@ -83,41 +83,35 @@ export const getEventAPI = async (req: NextApiRequest, res: NextApiResponse) => export const createEvent = (req: NextApiRequest, res: NextApiResponse) => { const form = formidable() form.parse(req, async (err, fields, files) => { + const filesUrl: { [key: string]: any } = {} try { if (err) { - return res.status(500).json({ error: err, fields, files }) + return res.status(500).json(err) } - if (files.image) { - const file = files.image as formidable.File - const { Location: imageUrl, error: saveError } = await addObject(file, 'events') - - if (saveError) { - return res.status(500).json({ error: saveError, fields, files }) - } + for (const key in files) { + if (Object.prototype.hasOwnProperty.call(files, key)) { + const file = files[key] as formidable.File + const { Location: url, error: awsError } = await addObject(file, 'events') - const { errors } = await client.mutate({ - mutation: CREATE_EVENT, - variables: { ...fields, imageUrl: imageUrl || '' }, - }) + if (awsError) { + return res.status(500).json({ error: awsError, fields, files }) + } - if (errors) { - return res.status(500).json({ errors }) + if (url) { + filesUrl[key] = url + } } - - return res.json({ - msg: 'Event created successfully', - data: { ...fields, imageUrl }, - }) } + const variables = { ...fields, ...filesUrl } await client.mutate({ mutation: CREATE_EVENT, - variables: { ...fields, imageUrl: '' }, + variables, }) return res.json({ msg: 'Event created successfully', - data: { ...fields }, + variables, }) } catch (error) { res.status(500).json({ error, fields, files }) @@ -128,12 +122,10 @@ export const createEvent = (req: NextApiRequest, res: NextApiResponse) => { export const updateEvent = async (req: NextApiRequest, res: NextApiResponse) => { const form = formidable() form.parse(req, async (err, fields, files) => { + const filesUrl: { [key: string]: any } = {} + const eventId = req.query?.id try { - const eventId = req.query?.id - const eventDataBase = await getEvent(eventId) - const { event: eventDefault, error: errEventDataBase } = eventDataBase ?? {} - - if (err || errEventDataBase) { + if (err) { return res.status(500).json(err) } @@ -141,27 +133,28 @@ export const updateEvent = async (req: NextApiRequest, res: NextApiResponse) => return res.status(400).json({ msg: 'EventId is required' }) } - if (files.image) { - const file = files.image as formidable.File - const { Location: imageUrl } = await addObject(file, 'events') - - await client.mutate({ - mutation: UPDATE_EVENT, - variables: { ...fields, imageUrl, id: eventId }, - }) - return res.status(204).json({ - msg: 'Event updated successfully', - data: { ...fields, imageUrl }, - }) + for (const key in files) { + if (Object.prototype.hasOwnProperty.call(files, key)) { + const file = files[key] as formidable.File + const { Location: url, error: awsError } = await addObject(file, 'events') + + if (awsError) { + return res.status(500).json({ error: awsError, fields, files }) + } + + if (url) { + filesUrl[key] = url + } + } } await client.mutate({ mutation: UPDATE_EVENT, - variables: { ...fields, imageUrl: eventDefault?.imageUrl ?? '', id: eventId }, + variables: { ...fields, ...filesUrl, id: eventId }, }) return res.status(204).json({ msg: 'Event updated successfully', - data: { ...fields }, + variables: { ...fields, ...filesUrl }, }) } catch (error) { res.status(500).json(error) diff --git a/pages/eventos/crear.tsx b/pages/eventos/crear.tsx index 8eae2a4..648d96a 100644 --- a/pages/eventos/crear.tsx +++ b/pages/eventos/crear.tsx @@ -17,13 +17,12 @@ const Create: NextPage = () => { const submitHandler = async (formValues: EventEditableWithFiles, e: FormEvent) => { e.preventDefault() + const form = new FormData(e.target as HTMLFormElement) + form.set('type', isEventOrWorkshop(form.get('type') as unknown as boolean)) + form.set('date', formValues.date.concat('T', formValues.time || '00:00', ':00')) setLoading(true) try { - const form = new FormData(e.target as HTMLFormElement) - form.set('type', isEventOrWorkshop(form.get('type') as unknown as boolean)) - form.set('date', formValues.date.concat('T', formValues.time || '00:00', ':00')) - await axios.post('/api/events', form, { headers: { 'Content-Type': 'multipart/form-data', diff --git a/pages/eventos/editar/[id].tsx b/pages/eventos/editar/[id].tsx index 162c6ed..2ca5d31 100644 --- a/pages/eventos/editar/[id].tsx +++ b/pages/eventos/editar/[id].tsx @@ -1,7 +1,7 @@ import axios from 'axios' import { NextPage } from 'next' import { useRouter } from 'next/router' -import { useState } from 'react' +import { FormEvent, useState } from 'react' import Swal from 'sweetalert2' import UpdateFormContainer from '@/components/UpdateForm' @@ -16,35 +16,27 @@ const EditEvent: NextPage = () => { const { push, query } = useRouter() const { error: logError } = useLogger() const [loading, setLoading] = useState(false) - const submitHandler = async (updatedEvent: EventEditable) => { + const submitHandler = async (updatedEvent: EventEditable, e: FormEvent) => { + setLoading(true) const formattedDate = updatedEvent.date.concat('T', updatedEvent?.time || '00:00', ':00') - const formData = new FormData() - - Object.entries(updatedEvent).forEach(([key, value]) => { - if (key === 'image' || key === 'pdf') { - formData.set(key, value[0]) - } else { - formData.set(key, value) - } - }) + const formData = new FormData(e.target as HTMLFormElement) formData.set('date', formattedDate) formData.set('type', isEventOrWorkshop(updatedEvent.type as boolean)) try { - setLoading(true) await axios.put(`/api/events/${query.id}`, formData) - setLoading(false) - push(`/eventos`) Swal.fire({ title: 'Evento actualizado', icon: 'success', showConfirmButton: false, - timer: 3000, + timer: 2000, timerProgressBar: true, }) - } catch (error: any) { + push(`/eventos`) setLoading(false) + } catch (error: any) { logError(error, 'pages/eventos/editar/[id].tsx', 'Error al actualizar el evento') + setLoading(false) } } diff --git a/services/AWS/s3.ts b/services/AWS/s3.ts index 9268517..c44c8b8 100644 --- a/services/AWS/s3.ts +++ b/services/AWS/s3.ts @@ -1,6 +1,5 @@ import S3 from 'aws-sdk/clients/s3' import crypto from 'crypto' -import type { File } from 'formidable' import fs from 'fs' import { v4 as uuid } from 'uuid' @@ -18,15 +17,14 @@ const s3 = new S3({ signatureVersion: 'v4', }) -export const addObject = async (file: File, prefix?: string) => { - if (!file) return { Location: '' } - +export const addObject = async ({ originalFilename, filepath }: any, prefix?: string) => { + if (!filepath || !originalFilename) { + return { Location: '' } + } try { - const extName = file?.originalFilename - const fileName = `${prefix ? `${prefix}_` : ''}${uuid()}.${extName}` - - const fileBuffer = fs.readFileSync(file.filepath) - const fileStream = fs.createReadStream(file.filepath) + const fileName = `${prefix ? `${prefix}_` : ''}${uuid()}.${originalFilename}` + const fileBuffer = fs.readFileSync(filepath) + const fileStream = fs.createReadStream(filepath) const hex = crypto.createHash('sha256').update(fileBuffer).digest('base64') const { Location } = await s3 diff --git a/styles/EditEvent.module.scss b/styles/EditEvent.module.scss index bda79bd..bf8820d 100644 --- a/styles/EditEvent.module.scss +++ b/styles/EditEvent.module.scss @@ -26,6 +26,7 @@ .container-input { border-radius: 6px; + column-gap: 10px; display: flex; text-align: center; @@ -56,7 +57,6 @@ color: $gray-800; flex: 0.7; font-size: 22px; - overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } diff --git a/styles/base_components.scss b/styles/base_components.scss index 410a8df..cf64387 100644 --- a/styles/base_components.scss +++ b/styles/base_components.scss @@ -14,7 +14,6 @@ button { a { color: $link; margin-left: 1ch; - text-decoration: underline; &:active { color: $link-active; diff --git a/views/Events/Create/Form.tsx b/views/Events/Create/Form.tsx index f299bfe..a67239e 100644 --- a/views/Events/Create/Form.tsx +++ b/views/Events/Create/Form.tsx @@ -12,8 +12,6 @@ import Icons8 from '@/views/Shared/Icons8' import Picture from '@/views/SVGs/Picture' export interface EventEditableWithFiles extends EventEditable { - image?: FileList - pdf?: FileList time?: string } @@ -115,7 +113,7 @@ const CreateEventForm: FC<{ type="file" accept="image/*" className={styles['input-file']} - {...register('image')} + {...register('imageUrl')} onChange={handleFile} />