mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-02-14 05:14:54 +00:00
refactor(infra): directory structure (#4615)
This commit is contained in:
52
packages/backend/server/src/middleware/exception-logger.ts
Normal file
52
packages/backend/server/src/middleware/exception-logger.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { GqlContextType } from '@nestjs/graphql';
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
import { REQUEST_ID } from '../constants';
|
||||
const TrivialExceptions = [NotFoundException];
|
||||
|
||||
@Catch()
|
||||
export class ExceptionLogger implements ExceptionFilter {
|
||||
private logger = new Logger('ExceptionLogger');
|
||||
|
||||
catch(exception: Error, host: ArgumentsHost) {
|
||||
// with useGlobalFilters, the context is always HTTP
|
||||
const ctx = host.switchToHttp();
|
||||
|
||||
const request = ctx.getRequest<Request>();
|
||||
const requestId = request?.header(REQUEST_ID);
|
||||
|
||||
const shouldVerboseLog = !TrivialExceptions.some(
|
||||
e => exception instanceof e
|
||||
);
|
||||
this.logger.error(
|
||||
new Error(
|
||||
`${requestId ? `requestId-${requestId}: ` : ''}${exception.message}${
|
||||
shouldVerboseLog ? '\n' + exception.stack : ''
|
||||
}}`,
|
||||
{ cause: exception }
|
||||
)
|
||||
);
|
||||
|
||||
if (host.getType<GqlContextType>() === 'graphql') {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = ctx.getResponse<Response>();
|
||||
if (exception instanceof HttpException) {
|
||||
response.status(exception.getStatus()).json(exception.getResponse());
|
||||
} else {
|
||||
response.status(500).json({
|
||||
statusCode: 500,
|
||||
error: exception.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
27
packages/backend/server/src/middleware/timing.ts
Normal file
27
packages/backend/server/src/middleware/timing.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import onHeaders from 'on-headers';
|
||||
|
||||
export const serverTimingAndCache = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
req.res = res;
|
||||
const now = process.hrtime();
|
||||
|
||||
onHeaders(res, () => {
|
||||
const delta = process.hrtime(now);
|
||||
const costInMilliseconds = (delta[0] + delta[1] / 1e9) * 1000;
|
||||
|
||||
const serverTiming = res.getHeader('Server-Timing') as string | undefined;
|
||||
const serverTimingValue = `${
|
||||
serverTiming ? `${serverTiming}, ` : ''
|
||||
}total;dur=${costInMilliseconds}`;
|
||||
|
||||
res.setHeader('Server-Timing', serverTimingValue);
|
||||
});
|
||||
|
||||
res.setHeader('Cache-Control', 'max-age=0, private, must-revalidate');
|
||||
|
||||
next();
|
||||
};
|
||||
Reference in New Issue
Block a user