Skip to content

Commit

Permalink
feat: log
Browse files Browse the repository at this point in the history
Signed-off-by: ZTL-UwU <zhangtianli2006@163.com>
  • Loading branch information
ZTL-UwU committed Dec 14, 2024
1 parent b4f9e3b commit 20fdb13
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion server/trpc/trpc.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { TPermission } from '~~/types';
import type { Context } from './context';
import { initTRPC, TRPCError } from '@trpc/server';
import { consola } from 'consola';
import superjson from 'superjson';
import { ZodError } from 'zod';

Expand Down Expand Up @@ -58,6 +59,39 @@ export function requirePermission(permissions: TPermission[]) {
export const router = t.router;
export const middleware = t.middleware;

export const publicProcedure = t.procedure;
export const loggedProcedure = t.procedure.use(async (opts) => {
const start = new Date();
const result = await opts.next();
const durationMs = Date.now() - start.getTime();

try {
const user = opts.ctx.user === 'ERR_JWT_EXPIRED' ? undefined : opts.ctx.user;
let input = JSON.stringify(opts.rawInput);
if (input?.includes('password') || input?.includes('Password'))
input = '***';

consola.log(
start.toLocaleString('zh-CN'),
'|',
`[${result.ok ? 'OK' : result.error.code}]`,
`[${opts.type}]`,
`[${durationMs}ms]`,
opts.path,
'->',
input,
'|',
user?.permissions,
user?.id,
);

if (!result.ok && result.error.code === 'INTERNAL_SERVER_ERROR') {
consola.error(result.error);
}
} catch {}

return result;
});

export const publicProcedure = loggedProcedure;
export const protectedProcedure = publicProcedure.use(enforceUserIsAuthed).use(requirePermission(['login']));
export const adminProcedure = publicProcedure.use(enforceUserIsAuthed).use(requirePermission(['login', 'admin']));

0 comments on commit 20fdb13

Please sign in to comment.