Skip to content

Commit

Permalink
fix: fix overall server setup
Browse files Browse the repository at this point in the history
  • Loading branch information
zAlweNy26 committed Oct 13, 2024
1 parent 2545fac commit d864167
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 32 deletions.
3 changes: 2 additions & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,9 @@ export const serverContext = new Elysia({ name: 'server-context' }).use(httpErro
rh: rabbitHole,
log,
db,
}).onBeforeHandle(({ headers, HttpError }) => {
}).onBeforeHandle({ as: 'scoped' }, ({ headers, path, HttpError }) => {
const apiKey = headers.token, realKey = parsedEnv.apiKey
if (path.startsWith('/docs')) return
if (realKey && realKey !== apiKey)
throw HttpError.Unauthorized('Invalid API key')
}).derive({ as: 'global' }, ({ headers }) => {
Expand Down
4 changes: 2 additions & 2 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ export const httpError = new Elysia({ name: 'http-error' })
description: 'The model for an HTTP error response',
}),
})
.onError(({ code, error, set }) => {
.onError({ as: 'global' }, ({ code, error, set }) => {
if (code === 'HTTP_ERROR') {
set.status = error.status
set.headers['content-type'] = 'application/json+problem'
set.headers['content-type'] = 'application/json'
return {
code: error.message,
status: error.status,
Expand Down
43 changes: 20 additions & 23 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { createConsola } from 'consola'
import { getColor } from 'consola/utils'
import { Table } from 'console-table-printer'
import { format } from 'date-fns'
import { Logestic, type LogesticOptions } from 'logestic'
import { Logestic } from 'logestic'
import { catPaths, LogLevel, parsedEnv } from './utils.ts'

const logger = createConsola({
Expand Down Expand Up @@ -103,25 +103,22 @@ export const log = Object.freeze({
debug: logger.debug,
})

export function httpLogger(options?: LogesticOptions) {
return new Logestic({
showLevel: true,
...options,
}).use(['time', 'method', 'path', 'duration']).format({
onSuccess({ time, method, path, duration }) {
const dateTime = chalk.gray(format(time, 'dd/MM/yyyy HH:mm:ss'))
const methodPath = chalk.cyan(`${method} ${decodeURIComponent(path)}`)
return `${dateTime} ${methodPath} ${Number(duration) / 1000}ms`
},
onFailure({ request, datetime, error }) {
const { method, url } = request
const err = error as HttpError
const baseUrl = url.substring(catPaths.baseUrl.length - 1)
const dateTime = chalk.gray(format(datetime, 'dd/MM/yyyy HH:mm:ss'))
const methodPath = chalk.red(`${method} ${decodeURIComponent(baseUrl)}`)
const errorCode = chalk.bgRed(`[${err.status} - ${err.message}]`)
const errorText = `${errorCode} ${chalk.red(err.cause)}`
return `${dateTime} ${methodPath}\n${errorText}`
},
})
}
export const httpLogger = new Logestic({
showLevel: true,
}).use(['time', 'method', 'path', 'duration']).format({
onSuccess({ time, method, path, duration }) {
const dateTime = chalk.gray(format(time, 'dd/MM/yyyy HH:mm:ss'))
const methodPath = chalk.cyan(`${method} ${decodeURIComponent(path)}`)
return `${dateTime} ${methodPath} ${Number(duration) / 1000}ms`
},
onFailure({ request, datetime, error }) {
const { method, url } = request
const err = error as HttpError
const baseUrl = url.substring(catPaths.baseUrl.length - 1)
const dateTime = chalk.gray(format(datetime, 'dd/MM/yyyy HH:mm:ss'))
const methodPath = chalk.red(`${method} ${decodeURIComponent(baseUrl)}`)
const errorCode = chalk.bgRed(`[${err.status} - ${err.message}]`)
const errorText = `${errorCode} ${chalk.red(err.cause)}`
return `${dateTime} ${methodPath}\n${errorText}`
},
})
7 changes: 4 additions & 3 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import { Elysia } from 'elysia'
import { checkPort } from 'get-port-please'
import isDocker from 'is-docker'
import pkg from '~/package.json'
import { swaggerTags } from './context.ts'
import { serverContext, swaggerTags } from './context.ts'
import { httpLogger, log } from './logger.ts'
import { logWelcome, parsedEnv } from './utils.ts'

const app = new Elysia()
.use(httpLogger())
.use(httpLogger)
.use(serverTiming())
.use(cors({
origin: parsedEnv.corsAllowedOrigins,
Expand Down Expand Up @@ -42,7 +42,7 @@ const app = new Elysia()
version: pkg.version,
},
tags: Object.values(swaggerTags),
security: [{ apiKey: ['token'] }],
security: [{ token: [] }],
components: {
securitySchemes: {
token: {
Expand All @@ -62,6 +62,7 @@ const app = new Elysia()
},
},
}))
.use(serverContext)
.use(generalRoutes)
.use(settingsRoutes)
.use(llmRoutes)
Expand Down
14 changes: 11 additions & 3 deletions src/routes/general.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,21 @@ export const generalRoutes = new Elysia({
params: t.Object({
userId: t.String({ default: 'user' }),
}),
query: t.Object({
save: t.Optional(t.Boolean()),
token: t.Optional(t.String()),
}),
body: t.Intersect([
t.Object({
text: t.String(),
save: t.Optional(t.Boolean()),
}),
t.Record(t.String(), t.Any()),
]),
beforeHandle: ({ query, HttpError }) => {
const apiKey = query.token, realKey = parsedEnv.apiKey
if (realKey && realKey !== apiKey)
throw HttpError.Unauthorized('Invalid API key')
},
open: async (ws) => {
const { data: { params } } = ws
const user = params.userId
Expand All @@ -36,10 +44,10 @@ export const generalRoutes = new Elysia({
cat.removeStray(user)
log.debug(`User ${user} disconnected from the WebSocket.`)
},
message: ({ data: { params, body } }) => {
message: ({ data: { params, body, query } }) => {
const user = params.userId
const stray = cat.getStray(user)!
stray.run(body, body.save).then(stray.send).catch(log.error)
stray.run(body, query.save).then(stray.send).catch(log.error)
},
error: ({ error }) => {
log.dir(error)
Expand Down

0 comments on commit d864167

Please sign in to comment.