Closed ezequiel88 closed 2 years ago
Beautiful work! I would need to validate the other fields before saving the images to disk
class x { public async createAnimal(req, res, next): Promise<void> { const userId = response.locals.userId const form = formidable({ multiples: true }) let fields: any = {} let files: any = [] form.on('field', (fieldName, fieldValue) => { fields[fieldName] = fieldName === "vaccines" ? JSON.parse(fieldValue) : fieldValue }) form.on('fileBegin', (formName, file) => { files.push(`public/images/animal/photo-${file.newFilename}.jpg`) file.filepath = `public/images/animal/photo-${file.newFilename}.jpg` }) form.parse(request, ()=>{}) form.once('end', async () => { if (!this.validator.validateAbout(fields.nick)) { next(new ErrorResponse(9127, "Invalid nick", 400)) return } //-> more validations try { const animalModel = new Animal( generateId(), userId, fields.nick, fields.chip, fields.age, fields.gender, fields.about, fields.vaccines, files ) const animal = await this.animalDatabase.createAnimal(animalModel) if (animal instanceof Error) { next(new ErrorResponse(3121, animal.message, 500)) return } // Success response.json(animal) } catch (error: any) { next(new ErrorResponse(3122, error.message, 500)) } }) } }
At the end of the form.parse callback delete the files if there was at least 1 error
Beautiful work! I would need to validate the other fields before saving the images to disk