refactor: middlewares

This commit is contained in:
wancat committed 2024-02-19 19:08:34 +08:00
1 parent 7c1d83ccd3
commit 5e8df7ae01
8 files changed
+53 -39

No files matched your search

-9
View File
@@ -1,9 +0,0 @@
export default function authRequired(req, res, next) {
if (req.isAuthenticated() && !req.session.newUser) {
next()
return
}
res.status(401).json({
message: 'not authenticated',
})
}
+15
View File
@@ -0,0 +1,15 @@
import type { Request, Response, NextFunction } from 'express'
export default function authRequired(
req: Request,
res: Response,
next: NextFunction
) {
if (req.isAuthenticated() && !('newUser' in req.session)) {
next()
return
}
res.status(401).json({
message: 'not authenticated',
})
}
-13
View File
@@ -1,13 +0,0 @@
import logger from '../utils/logger.js'
export function asyncHandler(fn) {
return (req, res, next) => {
fn(req, res, next).catch(next)
}
}
// eslint-disable-next-line no-unused-vars
export default function errorHandler(err, req, res, next) {
logger.error(err) // Log error stack trace to the console
res.status(500).send({ message: 'Something broke!' }) // Send error response
}
+20
View File
@@ -0,0 +1,20 @@
import type { Request, Response, NextFunction } from 'express'
import logger from '../utils/logger.js'
export function asyncHandler(fn: any) {
return (req: Request, res: Response, next: NextFunction) => {
fn(req, res, next).catch(next)
}
}
// eslint-disable-next-line no-unused-vars
export default function errorHandler(
err: any,
req: Request,
res: Response,
// eslint-disable-next-line no-unused-vars
next: NextFunction
) {
logger.error(err) // Log error stack trace to the console
res.status(500).send({ message: 'Something broke!' }) // Send error response
}
@@ -1,9 +1,11 @@
import rateLimit from 'express-rate-limit'
import type { Options } from 'express-rate-limit'
import type { Request, Response, NextFunction } from 'express'
import config from '../config.js'
function createRateLimiter(options) {
function createRateLimiter(options: Partial<Options>) {
if (config.testing.enabled) {
return (req, res, next) => next()
return (req: Request, res: Response, next: NextFunction) => next()
}
return rateLimit(options)
}
@@ -21,7 +23,7 @@ export const authenticateRateLimit = createRateLimiter({
export const sessionRateLimit = createRateLimiter({
windowMs: 10 * 1000,
max: 1,
keyGenerator: (req) => {
return req.user ? req.user._id : req.ip
keyGenerator: (req: Request) => {
return req.user ? (req.user as any)._id : req.ip || ''
},
})
File renamed without changes.
@@ -1,6 +1,7 @@
import { validationResult } from 'express-validator'
import type { Request, Response, NextFunction } from 'express'
export function noError(req, res, next) {
export function noError(req: Request, res: Response, next: NextFunction) {
const result = validationResult(req)
if (result.isEmpty()) {
next()