generated from avior/template-web-astro
70 lines
2.5 KiB
TypeScript
70 lines
2.5 KiB
TypeScript
import * as Sentry from '@sentry/node'
|
|
import { defineMiddleware } from 'astro/middleware'
|
|
import Logger from 'config/logger'
|
|
import { getEnv, requireEnv } from 'libs/env'
|
|
import ResponseBuilder from 'libs/response-builder'
|
|
|
|
const dsn = getEnv('SENTRY_DSN')
|
|
if (dsn) {
|
|
Sentry.init({
|
|
dsn: dsn,
|
|
debug: getEnv('SENTRY_DEBUG') === 'true',
|
|
environment: requireEnv('NODE_ENV'),
|
|
serverName: requireEnv('APP_URL'),
|
|
includeLocalVariables: true,
|
|
release: getEnv('GIT_TAG') ?? requireEnv('GIT_COMMIT')
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Simple Middleware that handle the logging of requests and handling processing errors
|
|
*/
|
|
export default defineMiddleware(async ({ request, url }, next) => {
|
|
const now = new Date()
|
|
// Date of request User-Agent 32 first chars request Method
|
|
let prefix = `\x1b[22m ${request.headers.get('user-agent')?.slice(0, 32).padEnd(32)} ${request.method.padEnd(7)}`
|
|
|
|
const fullURL = url.toString()
|
|
const path = fullURL.slice(fullURL.indexOf(url.pathname, fullURL.indexOf(url.host)))
|
|
|
|
// Log start of request
|
|
if (!import.meta.env.PROD) {
|
|
// time of request
|
|
prefix = ''
|
|
// HTTP Status Code path of request Time to run request
|
|
Logger.info(`${prefix} ${''.padStart(5, ' ')} ${path}`)
|
|
} else {
|
|
// HTTP Status Code Time to run request path of request
|
|
Logger.info(`${prefix} ${''.padStart(5, ' ')} ${''.padStart(7, ' ')} ${path}`)
|
|
}
|
|
|
|
|
|
// Handle if the request die
|
|
try {
|
|
const res = await next()
|
|
|
|
if (import.meta.env.PROD) {
|
|
// HTTP Status time to execute path of request
|
|
Logger.info(`${prefix} \x1b[34m[${'status' in res ? res.status : '???'}]\x1b[0m \x1b[2m${(new Date().getTime() - now.getTime()).toFixed(0).padStart(5, ' ')}ms\x1b[22m ${path}`)
|
|
}
|
|
|
|
return res
|
|
} catch (err) {
|
|
if (import.meta.env.PROD) {
|
|
// time to execute path of request
|
|
Logger.info(`${prefix} \x1b[34m[500]\x1b[0m \x1b[2m${(new Date().getTime() - now.getTime()).toFixed(0).padStart(5, ' ')}ms\x1b[22m ${path}`)
|
|
}
|
|
|
|
// log the error inside the browser
|
|
Logger.critical(err)
|
|
|
|
// send the error to Glitchtip
|
|
Sentry.captureException(err)
|
|
|
|
return new ResponseBuilder()
|
|
.status(500)
|
|
.body('An error occured while processing your request')
|
|
.build()
|
|
}
|
|
})
|