Skip to content

Commit

Permalink
add downloadFile logic & handler b00tc4mp#361
Browse files Browse the repository at this point in the history
  • Loading branch information
Abel Prieto committed Mar 12, 2024
1 parent 25a7d00 commit feac0e5
Show file tree
Hide file tree
Showing 11 changed files with 57 additions and 14 deletions.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import jwt from 'jsonwebtoken'
import fs from 'fs'
import path from 'path'
import downloadFile from '../logic/downloadFile.js'
import { errors } from 'com'

Expand All @@ -16,7 +14,7 @@ export default async (req, res) => {
try {
const file = await downloadFile(userId, fileId)

res.download(file)
res.download(file.path)
} catch (error) {
let status = 500

Expand Down
33 changes: 22 additions & 11 deletions staff/abel-prieto/PROYECT/API/logic/downloadFile.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,43 @@
import fs from 'fs'
import path from 'path'
import fs from 'fs/promises'
import { User, File } from '../data/models.js'
import { validate, errors } from 'com'
const { SystemError, NotFoundError, AuthorizationError } = errors

async function saveCopyFile(oldPath, newPath) {
try {
await fs.copyFile(oldPath, newPath)
} catch (error) {
throw new SystemError(`Failed to download file: ${error.message}`)
}
}

export default async function downloadFile(userId, fileId) {
validate.id(userId, 'ID User')
validate.id(fileId, 'ID File')

try {
const user = await User.findById(userId)

const user = await User.findById(userId).lean()
if (!user) {
throw new NotFoundError('User not found')
}

const file = await File.findById(fileId)

const file = await File.findById(fileId).lean()
if (!file) {
throw new NotFoundError('File not found')
}

if (file.owner === user.id || user.role[0] === 'admin') {
const originalName = file.originalName
const filePath = `./uploads/${file._id.toString()}`
const isOwner = user.id === file.owner
const isAdmin = user.role && user.role.includes('admin')

if (isOwner || isAdmin) {
const originalName = file.name
const oldPath = `./uploads/${file._id.toString()}`
const newPath = `./downloads/${originalName}`

await saveCopyFile(oldPath, newPath)

// Devolvemos la info de la ruta y el nombre original
return { filePath, originalName }
// Devuelvo la info de la nueva ruta y el nombre original
return { path: newPath, originalName }
} else {
throw new AuthorizationError('Authorization denied. Try again')
}
Expand Down
Empty file.
Empty file.
14 changes: 14 additions & 0 deletions staff/abel-prieto/PROYECT/API/test/downloadFile.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import mongoose from 'mongoose'
import downloadFile from '../logic/downloadFile.js'

mongoose.connect('mongodb://127.0.0.1/hiinit')
.then(() => {
try {
downloadFile('65e8bd456728f7c2d66bd330', '65eb3695de39ba551ad01d77')
.then(() => console.log('file successfully download!'))
.catch(error => console.error(error))
} catch (error) {
console.log(error)
}
})
.catch(error => console.error(error))
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<script>
const req = {
method: 'GET',
headers: {
'Authorization': 'Bearer 65e8c8c89653e312c3490947'
}
}

fetch('http://localhost:9001/download/65ef4d6574acbaf3bf0c839d', req)
.catch(error => console.error(error))
.then(res => {
if (res.ok) {
res.json()
.catch(error => console.error(error))
.then(body => console.log(res.status, body))
} else {
console.error(res.status)
}
})
</script>
Binary file not shown.
Binary file not shown.
File renamed without changes.
Binary file not shown.

0 comments on commit feac0e5

Please sign in to comment.