Skip to content
This repository has been archived by the owner on Sep 25, 2023. It is now read-only.

refactor: trpc v10 migration WIP #81

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@fastify/cors": "^7.0.0",
"@fastify/websocket": "^5.0.0",
"@swc/helpers": "^0.3.17",
"@trpc/server": "^9.27.1",
"@trpc/server": "10.0.0-proxy-alpha.73",
"@typegoose/typegoose": "^9.11.0",
"bull": "^4.8.5",
"bullmq": "^1.89.1",
Expand Down
7 changes: 6 additions & 1 deletion api/src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import * as bcrypt from 'bcryptjs'
import { WithExcludeClient } from '../db'
// don't make it an alias, the seed command will fail
import { getEnv, isInstituteRole } from '../lib/helpers'
import { SessionUser } from '../rpc/context'

export interface JwtPayload {
id: number
Expand All @@ -24,7 +25,11 @@ export async function hashPass(password: string) {

export function prismaQueryHelper(client: WithExcludeClient) {
return {
async getAccount(role: 'STUDENT' | 'INSTITUTE' | 'INSTITUTE_MOD' | 'ADMIN', email?: string, id?: number) {
async getAccount(session: SessionUser) {
const role = session?.user?.role
const email = session?.user?.email
const id = session?.user?.id

let account: any

if (role === 'STUDENT') {
Expand Down
9 changes: 0 additions & 9 deletions api/src/rpc/createRouter.ts

This file was deleted.

36 changes: 36 additions & 0 deletions api/src/rpc/middlewares.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { TRPCError } from '@trpc/server'
import { isRole } from '../lib'
import { trpc } from './trpc'

export const sessionMiddleware = trpc.middleware(async ({ ctx, next }) => {
if (ctx.session === null)
throw new TRPCError({
code: 'UNAUTHORIZED',
})

const nextCtx = await next({
ctx: { session: ctx.session },
})

return nextCtx
})

export const instituteMiddleware = trpc.middleware(async ({ ctx, next }) => {
if (ctx.session === null || !isRole(ctx.session.user.role).instituteOrMod)
throw new TRPCError({ code: 'UNAUTHORIZED' })

return await next({
ctx: { session: ctx.session },
})
})

export const adminMiddleware = trpc.middleware(async ({ ctx, next }) => {
if (ctx.session?.user.role !== 'ADMIN')
throw new TRPCError({
code: 'UNAUTHORIZED',
})

return await next({
ctx: { session: ctx.session },
})
})
7 changes: 7 additions & 0 deletions api/src/rpc/procedures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { adminMiddleware, instituteMiddleware, sessionMiddleware } from './middlewares'
import { trpc } from './trpc'

export const procedureWithSession = trpc.procedure.use(sessionMiddleware)
export const procedureWithInstitute = trpc.procedure.use(instituteMiddleware)
export const procedureWithStudent = trpc.procedure.use(sessionMiddleware)
export const procedureWithAdmin = trpc.procedure.use(sessionMiddleware).use(adminMiddleware)
43 changes: 12 additions & 31 deletions api/src/rpc/routers/_appRouter.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { trpc } from '../trpc'
import { batchRouter } from './batch'
/**
* This file contains the root router of your tRPC-backend
*/
import superjson from 'superjson'
import { createRouter } from '../createRouter'
import { accountRouter } from './accounts'
import { authRouter } from './auth'
import { courseRouter } from './course'
Expand All @@ -13,31 +9,16 @@ import { studentRouter } from './student'
import { ticketRouter } from './ticket'
import { notificationRouter } from './notifications'

/**
* Create your application's root router
* If you want to use SSG, you need export this
* @link https://trpc.io/docs/ssg
* @link https://trpc.io/docs/router
*/
export const appRouter = createRouter()
/**
* Add data transformers
* @link https://trpc.io/docs/data-transformers
*/
.transformer(superjson)
/**
* Optionally do custom error (type safe!) formatting
* @link https://trpc.io/docs/error-formatting
*/
// .formatError(({ shape, error }) => { })
.merge('account.', accountRouter)
.merge('auth.', authRouter)
.merge('institute.', instituteRouter)
.merge('department.', departmentRouter)
.merge('course.', courseRouter)
.merge('batch.', batchRouter)
.merge('student.', studentRouter)
.merge('ticket.', ticketRouter)
.merge('notification.', notificationRouter)
export const appRouter = trpc.router({
account: accountRouter,
auth: authRouter,
institute: instituteRouter,
department: departmentRouter,
course: courseRouter,
batch: batchRouter,
student: studentRouter,
ticket: ticketRouter,
notification: notificationRouter,
})

export type AppRouter = typeof appRouter
80 changes: 27 additions & 53 deletions api/src/rpc/routers/accounts.ts
Original file line number Diff line number Diff line change
@@ -1,69 +1,43 @@
import { TRPCError } from '@trpc/server'
import { createRouter } from '../createRouter'
import { trpc } from '../trpc'
import { z } from 'zod'
import { createInstituteSchema, tourSchema } from '@mirai/app'

export const accountRouter = createRouter()
.middleware(async ({ ctx, next }) => {
if (ctx.session === null)
throw new TRPCError({
code: 'UNAUTHORIZED',
})

const nextCtx = await next({
ctx: { ...ctx, session: ctx.session },
import { procedureWithAdmin, procedureWithSession } from '../procedures'

export const accountRouter = trpc.router({
toggle_tour: procedureWithSession.input(tourSchema).mutation(async ({ ctx, input: { id, showTour } }) => {
await ctx.prisma.account.update({
where: { id },
data: { showTour },
select: { id: true, showTour: true },
})
}),

return nextCtx
})
.mutation('toggle_tour', {
input: tourSchema,
async resolve({ ctx, input: { id, showTour } }) {
await ctx.prisma.account.update({
where: { id },
data: { showTour },
select: { id: true, showTour: true },
})
},
})
.middleware(async ({ ctx, next }) => {
if (ctx.session?.user.role !== 'ADMIN')
create_institute: procedureWithAdmin.input(createInstituteSchema).mutation(async ({ ctx, input }) => {
const isDupId = await ctx.prisma.institute.findFirst({ where: { code: input.code }, select: { id: true } })

if (isDupId !== null) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'Duplicate Institute code',
code: 'BAD_REQUEST',
})
}

const nextCtx = await next({
ctx: { ...ctx, session: ctx.session },
const institute = await ctx.prisma.institute.create({
data: input,
})

return nextCtx
})
.mutation('create_institute', {
input: createInstituteSchema,
async resolve({ ctx, input }) {
const isDupId = await ctx.prisma.institute.findFirst({ where: { code: input.code }, select: { id: true } })

if (isDupId != null) {
throw new TRPCError({
message: 'Duplicate Institute code',
code: 'BAD_REQUEST',
})
}
return institute
}),

const institute = await ctx.prisma.institute.create({
data: input,
})

return institute
},
})
.mutation('update_institute', {
input: createInstituteSchema.merge(z.object({ instituteId: z.number() })),
async resolve({ ctx, input }) {
update_institute: procedureWithAdmin
.input(createInstituteSchema.merge(z.object({ instituteId: z.number() })))
.mutation(async ({ ctx, input }) => {
const { instituteId, ...data } = input

await ctx.prisma.institute.update({
where: { id: instituteId },
data,
})
},
})
}),
})
Loading