Skip to content

Commit

Permalink
create uploadFile middleware & endpoint, with Multer and diskStorage b…
Browse files Browse the repository at this point in the history
  • Loading branch information
abelpriem committed Feb 26, 2024
1 parent 1424063 commit 20896ba
Show file tree
Hide file tree
Showing 9 changed files with 202 additions and 10 deletions.
8 changes: 7 additions & 1 deletion staff/abel-prieto/PROYECT/API/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

`Retrieve User`

- Request: GET /users Authorization: Bearer '65d0e63fa0232cfaf1c8c411'
- Request: GET /users Authorization: Bearer ${session.sessionUserId}
- Response: 200 "Content-Type": application/json { username, [ group ], [ role ] }
- Response (error) : 500|404|406 "Content-Type": application/json { error, message }

Expand All @@ -25,3 +25,9 @@
- Request: GET /users
- Response: 200 "Content-Type": application/json { username, [ group ], [ role ] }
- Response (error) : 500|404|406 "Content-Type": application/json { error, message }

`Upload Files` ⚠️

- Request: POST /upload Authorization: Bearer ${session.sessionUserId}
- Response: 201
- Response (error) : 500 "Content-Type": application/json { error, message }
5 changes: 1 addition & 4 deletions staff/abel-prieto/PROYECT/API/data/models.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,7 @@ const file = new Schema({
},
type: {
type: String,
enum: ["file", "folder"],
parent: {
ref: 'File'
}
enum: ["file", "folder"]
},
permissions: {
type: Number,
Expand Down
4 changes: 3 additions & 1 deletion staff/abel-prieto/PROYECT/API/handlers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import authenticateUserHandler from './authenticateUserHandler.js'
import registerUserHandler from './registerUserHandler.js'
import retrieveUserHandler from './retrieveUserHandler.js'
import retrieveGuestHandler from './retrieveGuestHandler.js'
import uploadFileHandler from './uploadFileHandler.js'

export {
authenticateUserHandler,
registerUserHandler,
retrieveUserHandler,
retrieveGuestHandler
retrieveGuestHandler,
uploadFileHandler
}
42 changes: 42 additions & 0 deletions staff/abel-prieto/PROYECT/API/handlers/uploadFileHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import fs from 'fs'
import uploadFile from '../logic/uploadFile.js'
import { errors } from 'com'
const { NotFoundError, ContentError } = errors

function saveFile(file) {
const newPath = `./uploads/${file.originalname}`
fs.renameSync(file.path, newPath)

return
}

export default (req, res) => {
const userId = req.headers.authorization.substring(7)
const { originalname: name, mimetype: type } = req.file

saveFile(req.file)

try {
uploadFile(userId, name, type)
.then(({ user, file }) => res.json({ user, file, message: 'Upload file!' }))
.catch(error => {
let status = 500

if (error instanceof NotFoundError) {
status = 404
}

res.status(status).json({ error: error.constructor.name, message: error.message })

return
})
} catch (error) {
let status = 500

if (error instanceof ContentError || error instanceof TypeError) {
status = 406
}

res.status(status).json({ error: error.constructor.name, message: error.message })
}
}
9 changes: 8 additions & 1 deletion staff/abel-prieto/PROYECT/API/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import mongoose from 'mongoose'
import express from 'express'
import dotenv from 'dotenv'
import cors from 'cors'
import multer from 'multer'
import {
authenticateUserHandler,
registerUserHandler,
retrieveUserHandler,
retrieveGuestHandler
retrieveGuestHandler,
uploadFileHandler
} from './handlers/index.js'

dotenv.config()
Expand All @@ -16,6 +18,8 @@ mongoose.connect(process.env.URL_MONGODB_HIINIT_API)
const server = express()
const jsonBodyParser = express.json()

const upload = multer({ dest: 'uploads/' })

server.use(cors())

// ALL API REQUEST
Expand All @@ -33,6 +37,9 @@ mongoose.connect(process.env.URL_MONGODB_HIINIT_API)
// RETRIEVE GUEST
server.get('/users', retrieveGuestHandler)

// UPLOAD FILE
server.post('/upload', upload.single('file'), uploadFileHandler)

server.listen(process.env.PORT, () => console.log(`server online! Listen on: ${process.env.PORT}`))
})
.catch(error => console.error(error))
4 changes: 2 additions & 2 deletions staff/abel-prieto/PROYECT/API/logic/retrieveGuest.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { User } from "../data/models.js"
import { errors } from "com"
const { SystemError, NotFoundError} = errors
const { SystemError, NotFoundError } = errors

function retrieveGuest() {
return User.findOne({ email: '[email protected]' }).lean()
.catch(error => { throw new SystemError(error.message)})
.catch(error => { throw new SystemError(error.message) })
.then(guest => {
if (!guest) {
throw new NotFoundError('Guest not found. Try again')
Expand Down
38 changes: 38 additions & 0 deletions staff/abel-prieto/PROYECT/API/logic/uploadFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { User, File } from '../data/models.js'
import { errors } from 'com'
const { SystemError, NotFoundError } = errors

async function uploadFile(userId, name, type) {
try {
const user = await User.findById(userId).lean()

if (!user) {
throw new NotFoundError('User not found. Try again')
}

// const { username, email, password, group, __v, role, ...cleanedUser } = user

delete user.__v
delete user.username
delete user.email
delete user.password
delete user.group
delete user.role

const file = await File.create({ name: name, owner: userId, type: type, permissions: 3 })

// const { _id, owner, permissions, __v, ...cleanedFile } = file

delete file._id
delete file.owner
delete file.permissions
delete file.__v

return { user, file }
// return { user: cleanedUser, file: cleanedFile }
} catch (error) {
throw new SystemError(error.message)
}
}

export default uploadFile
2 changes: 1 addition & 1 deletion staff/abel-prieto/PROYECT/API/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"jsonwebtoken": "^9.0.2",
"mocha": "^10.3.0",
"mongoose": "^8.1.2",
"multer": "^1.4.5-lts.1",
"multer": "1.4.5-lts.1",
"pnpm": "^8.15.2"
},
"type": "module"
Expand Down
100 changes: 100 additions & 0 deletions staff/abel-prieto/PROYECT/API/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 20896ba

Please sign in to comment.