Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 33 additions & 40 deletions controllers/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
Expand All @@ -128,40 +122,39 @@ 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)
}

if (!eventId) {
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)
Expand Down
7 changes: 3 additions & 4 deletions pages/eventos/crear.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,12 @@ const Create: NextPage = () => {

const submitHandler = async (formValues: EventEditableWithFiles, e: FormEvent<HTMLFormElement>) => {
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',
Expand Down
24 changes: 8 additions & 16 deletions pages/eventos/editar/[id].tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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<HTMLFormElement>) => {
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)
}
}

Expand Down
16 changes: 7 additions & 9 deletions services/AWS/s3.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion styles/EditEvent.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

.container-input {
border-radius: 6px;
column-gap: 10px;
display: flex;
text-align: center;

Expand Down Expand Up @@ -56,7 +57,6 @@
color: $gray-800;
flex: 0.7;
font-size: 22px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Expand Down
1 change: 0 additions & 1 deletion styles/base_components.scss
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ button {
a {
color: $link;
margin-left: 1ch;
text-decoration: underline;

&:active {
color: $link-active;
Expand Down
6 changes: 2 additions & 4 deletions views/Events/Create/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -115,7 +113,7 @@ const CreateEventForm: FC<{
type="file"
accept="image/*"
className={styles['input-file']}
{...register('image')}
{...register('imageUrl')}
onChange={handleFile}
/>
<label htmlFor="image-file" className={styles.image}>
Expand Down Expand Up @@ -162,7 +160,7 @@ const CreateEventForm: FC<{
id="pdf-file"
className={styles['input-file']}
accept="application/pdf"
{...register('pdf', { required: false })}
{...register('requirementsUrl', { required: false })}
onChange={handleFile}
/>
<label htmlFor="pdf-file" className={styles.pdf}>
Expand Down
19 changes: 13 additions & 6 deletions views/Events/Edit/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import Icons8 from '@/views/Shared/Icons8'
import Picture from '@/views/SVGs/Picture'

export interface EventEditableWithFiles extends EventEditable {
image?: FileList
pdf?: FileList
time?: string
}

Expand Down Expand Up @@ -65,7 +63,6 @@ const EditEventForm: FC<MutableEventFormProps> = ({ onSubmit, loading, originalD
const showModal = () => {
DeleteModal('evento', async (confirmed: boolean) => {
if (confirmed) {
// Add petition Delete
await fetch(`/api/events/${originalEvent?.id}`, { method: 'DELETE' })
router.push('/eventos')
}
Expand Down Expand Up @@ -144,7 +141,7 @@ const EditEventForm: FC<MutableEventFormProps> = ({ onSubmit, loading, originalD
type="file"
accept="image/*"
className={styles['input-file']}
{...register('image')}
{...register('imageUrl')}
onChange={handleFile}
/>
<label htmlFor="image-file" className={styles.image}>
Expand Down Expand Up @@ -192,15 +189,25 @@ const EditEventForm: FC<MutableEventFormProps> = ({ onSubmit, loading, originalD
id="pdf-file"
className={styles['input-file']}
accept="application/pdf"
{...register('pdf', { required: false })}
{...register('requirementsUrl', { required: false })}
onChange={handleFile}
/>
<label htmlFor="pdf-file" className={styles.pdf}>
<figure>
<Icons8 name="installing-updates" iconStyle="ios" size={35} className={styles['btn-icon']} />
<Icons8 name="uninstalling-updates" iconStyle="ios" size={35} className={styles['btn-icon']} />
</figure>
<span className={styles.label}>{pdfFile?.name ? `${pdfFile?.name}` : 'Añadir PDF'}</span>
</label>
{originalEvent?.requirementsUrl && (
<a href={originalEvent?.requirementsUrl} download id="pdf-download">
<label htmlFor="pdf-download" className={styles.pdf}>
<figure>
<Icons8 name="installing-updates" iconStyle="ios" size={35} className={styles['btn-icon']} />
</figure>
<span className={styles.label}>Descargar PDF</span>
</label>
</a>
)}
</div>
<section className={styles['buttons-container']}>
<Button iconName="" className={styles['button-cancel']} onClick={() => router.push('/eventos')}>
Expand Down