Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add logging, shared types #2

Merged
merged 2 commits into from
Sep 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"@fastify/type-provider-typebox": "^5.0.0",
"fastify": "^5.0.0",
"pino": "^9.4.0",
"pino-pretty": "^11.2.2"
"pino-pretty": "^11.2.2",
"shared": "../shared"
}
}
14 changes: 3 additions & 11 deletions server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
import server from './server'
import { logger } from './util/logger'

async function run (): Promise<void> {
console.log('2')

let app
try {
app = await server()
} catch (e) {
console.error(e)
}
console.log('3')
const app = await server()
await app?.listen({
host: '0.0.0.0',
port: 8080
})
}

console.log('1')
run()
.then(r => {})
.catch(async err => {
// logger.error({ err }, 'Error in running app')
logger.error({ err }, 'Error in running app')
// close any db stuff
process.exit()
})
10 changes: 4 additions & 6 deletions server/src/routes/add/root.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { Type, TypeBoxTypeProvider, FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox'
import { TypeBoxTypeProvider, FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox'
import { AddResponseSchema, AddRequestSchema } from 'shared'

// maybe use a generic argument for FastifyPluginAsync if we use options with fastify instance
const add: FastifyPluginAsyncTypebox = async (fastifyApp, { }): Promise<void> => {
const fastify = fastifyApp.withTypeProvider<TypeBoxTypeProvider>()

fastify.get('/', {
schema: {
querystring: Type.Object({
a: Type.Number(),
b: Type.Number()
}),
querystring: AddRequestSchema,
response: {
200: Type.Object({result: Type.Number()})
200: AddResponseSchema
}
}
}, async (request, reply) => {
Expand Down
13 changes: 4 additions & 9 deletions server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,12 @@ import {
UnauthenticatedClientError,
sendBasicMessageResponse,
} from './util/errors'
import { logger } from './util/logger'

// const logger = l
import { logger, fastifyLogOpts } from './util/logger'

export default async function server (): Promise<FastifyInstance> {
console.log('11')
// const logger = mylogger()
const fastify = Fastify({
logger: true
logger: fastifyLogOpts
})
console.log('12')

fastify.setValidatorCompiler(TypeBoxValidatorCompiler)

Expand Down Expand Up @@ -57,10 +52,10 @@ export default async function server (): Promise<FastifyInstance> {
} else if (error instanceof ConflictError || error instanceof UnmodifiableError) {
await sendBasicMessageResponse(409, reply, error.message)
} else if (error instanceof DatabaseError) {
fastify.log.error({err: error}, 'Critical database error')
logger.error({err: error}, 'Critical database error')
await sendBasicMessageResponse(500, reply, error.message)
} else {
fastify.log.error({err: error}, 'Unknown internal server error')
logger.error({err: error}, 'Unknown internal server error')
await sendBasicMessageResponse(error.statusCode ?? 500, reply, error.message)
}
}
Expand Down
38 changes: 12 additions & 26 deletions server/src/util/logger.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,21 @@
import { pino } from 'pino'
// export const logger = pino({
// transport: {
// target: 'pino-pretty',
// options: { translateTime: 'UTC:yyyy-mm-dd\'T\'HH:MM:ss.l\'Z\'' }
// }
// })

const ENV_LEVELS: Record<string, string> = {
production: 'info',
test: 'silent',
default: 'debug'
}
export function logger() {
const opts = {
level: ENV_LEVELS[process.env.NODE_ENV ?? 'default'],
messageKey: 'message',
formatters: {
level: (level: any) => ({ level }) // display the level not the number value of the level
},
base: {}, // don't display the process pid, nor hostname
redact: {
// redact bearer tokens and JWTs
paths: ['req.headers.authorization', 'req.headers.assertion', 'req.headers["x-jwt-assertion"]', 'req.headers["x-jwt-assertion-original"]'],
censor: '***'
},
transport: {
target: 'pino-pretty',
options: {translateTime: 'UTC:yyyy-mm-dd\'T\'HH:MM:ss.l\'Z\''}
}

const loggerOptions = {
level: ENV_LEVELS[process.env.NODE_ENV ?? 'default'],
formatters: {
level: (level: any) => ({ level }) // display the level not the number value of the level
},
base: {}, // don't display the process pid, nor hostname
transport: {
target: 'pino-pretty',
options: {translateTime: 'SYS:HH:MM:ss Z-07:00'}
}
return pino(opts)
}

// export default logger;
export const fastifyLogOpts = {...loggerOptions, messageKey: 'message' }
export const logger = pino(loggerOptions)
6 changes: 6 additions & 0 deletions shared/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@fastify/cors": "^8.3.0",
"@fastify/helmet": "^10.1.1",
"@fastify/sensible": "^5.2.0",
"@sinclair/typebox": "^0.33.12",
"fastify": "^4.18.0",
"fastify-cli": "^5.7.1",
"fastify-plugin": "^4.5.0",
Expand All @@ -26,4 +27,4 @@
"typescript": "^5.0.2",
"vite": "^4.4.5"
}
}
}
2 changes: 2 additions & 0 deletions shared/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Add
export { AddResponseSchema, AddRequestSchema, type AddRequest, type AddResponse } from './model/add.model'
13 changes: 13 additions & 0 deletions shared/src/model/add.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Static, Type } from '@sinclair/typebox'

export const AddResponseSchema = Type.Object({
result: Type.Number()
})
export type AddResponse = Static<typeof AddResponseSchema>

export const AddRequestSchema = Type.Object({
a: Type.Number(),
b: Type.Number()
})
export type AddRequest = Static<typeof AddRequestSchema>

1 change: 1 addition & 0 deletions web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "vite",
"dev": "vite",
"build": "tsc && vite build",
"serve": "vite preview",
"reload": "npm run build && npm run serve",
Expand Down
10 changes: 4 additions & 6 deletions web/src/client/add.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import {Client} from "./client";
import { AddRequest } from 'shared'

export async function add(client: Client, a: number, b: number): Promise<number> {
return await client.get<number>('/add', {
a,
b
})
}
export async function add(client: Client, params: AddRequest): Promise<number> {
return await client.get<number>('/add', params)
}
2 changes: 1 addition & 1 deletion web/src/components/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const Main = memo(() => {
if (!client) {
return
}
const response = await add(client, 1, 2);
const response = await add(client, {a:1, b:2});
return response;
});

Expand Down
Loading