1
0
Fork 0
mirror of https://github.com/Chocobozzz/PeerTube.git synced 2025-10-06 03:50:26 +02:00

Refactor uploadx middlewares

This commit is contained in:
Chocobozzz 2024-02-14 10:20:02 +01:00 committed by Chocobozzz
parent e286db3a39
commit f7e4f62870
14 changed files with 182 additions and 166 deletions

View file

@ -1,13 +1,15 @@
import express from 'express'
import express, { Request, Response, NextFunction, RequestHandler } from 'express'
import { buildLogger } from '@server/helpers/logger.js'
import { getResumableUploadPath } from '@server/helpers/upload.js'
import { CONFIG } from '@server/initializers/config.js'
import { LogLevel, Uploadx } from '@uploadx/core'
import { FileQuery, LogLevel, Uploadx, Metadata as UploadXMetadata } from '@uploadx/core'
import { extname } from 'path'
import { authenticate } from '@server/middlewares/auth.js'
import { resumableInitValidator } from '@server/middlewares/validators/resumable-upload.js'
const logger = buildLogger('uploadx')
const uploadx = new Uploadx({
export const uploadx = new Uploadx({
directory: getResumableUploadPath(),
expiration: { maxAge: undefined, rolling: true },
@ -32,6 +34,60 @@ const uploadx = new Uploadx({
filename: file => `${file.userId}-${file.id}${extname(file.metadata.filename)}`
})
export {
uploadx
export function safeUploadXCleanup (file: FileQuery) {
uploadx.storage.delete(file)
.catch(err => logger.error('Cannot delete the file %s', file.name, { err }))
}
export function buildUploadXFile <T extends UploadXMetadata> (reqBody: T) {
return {
...reqBody,
path: getResumableUploadPath(reqBody.name),
filename: reqBody.metadata.filename
}
}
export function setupUploadResumableRoutes (options: {
router: express.Router
routePath: string
uploadInitBeforeMiddlewares?: RequestHandler[]
uploadInitAfterMiddlewares?: RequestHandler[]
uploadedMiddlewares?: ((req: Request<any>, res: Response, next: NextFunction) => void)[]
uploadedController: (req: Request<any>, res: Response, next: NextFunction) => void
uploadDeleteMiddlewares?: RequestHandler[]
}) {
const {
router,
routePath,
uploadedMiddlewares = [],
uploadedController,
uploadInitBeforeMiddlewares = [],
uploadInitAfterMiddlewares = [],
uploadDeleteMiddlewares = []
} = options
router.post(routePath,
authenticate,
...uploadInitBeforeMiddlewares,
resumableInitValidator,
...uploadInitAfterMiddlewares,
(req, res) => uploadx.upload(req, res) // Prevent next() call, explicitely tell to uploadx it's the end
)
router.delete(routePath,
authenticate,
...uploadDeleteMiddlewares,
(req, res) => uploadx.upload(req, res) // Prevent next() call, explicitely tell to uploadx it's the end
)
router.put(routePath,
authenticate,
uploadx.upload, // uploadx doesn't next() before the file upload completes
...uploadedMiddlewares,
uploadedController
)
}