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

Update server and db dependencies #7

Open
wants to merge 5 commits into
base: main
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 apps/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"build": "next build",
"start": "next start",
"lint": "next lint",
"vercel-build": "DATABASE_URL=$MIGRATE_DB_URL prisma generate && DATABASE_URL=$MIGRATE_DB_URL prisma migrate deploy && next build"
"vercel-build": "DATABASE_URL=$DATABASE_URL prisma generate && DATABASE_URL=$DATABASE_URL prisma migrate deploy && next build"
},
"dependencies": {
"@expo/next-adapter": "^3.1.20",
Expand Down
3 changes: 2 additions & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
],
"private": true,
"dependencies": {
"@trpc/server": "^9.15.0",
"@trpc/server": "10.0.0-proxy-beta.17",
"bcrypt": "^5.0.1",
"jsonwebtoken": "^8.5.1",
"superjson": "^1.10.0",
"zod": "^3.17.2"
},
"devDependencies": {
Expand Down
9 changes: 5 additions & 4 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { createRouter } from './routers/context'
import { authRouter } from './routers/auth'
import { postRouter } from './routers/post'
import { t } from './trpc'

export const appRouter = createRouter()
.merge('auth.', authRouter)
.merge('post.', postRouter)
export const appRouter = t.router({
auth: authRouter,
post: postRouter,
})

export type AppRouter = typeof appRouter
1 change: 1 addition & 0 deletions packages/api/src/inferance-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { inferProcedureInput, inferProcedureOutput } from '@trpc/server'
* This is a helper method to infer the output of a query resolver
* @example type HelloOutput = inferQueryOutput<'hello'>
*/
//TODO: update or remove these?
export type inferQueryOutput<
TRouteKey extends keyof AppRouter['_def']['queries']
> = inferProcedureOutput<AppRouter['_def']['queries'][TRouteKey]>
Expand Down
45 changes: 21 additions & 24 deletions packages/api/src/routers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
import { createSession } from '../utils/auth'
import { createRouter, protectedRoute } from './context'
import { protectedProcedure } from './context'
import signIn, { SignInSchema } from '../services/auth/signIn'
import signUp, { SignUpSchema } from '../services/auth/signUp'

export const authRouter = createRouter()
.mutation('signIn', {
input: SignInSchema,
resolve: async ({ input: { email, password } }) => {
return signIn({ email, password })
},
})
.mutation('signUp', {
input: SignUpSchema,
resolve: async ({ input: { email, password } }) => {
const user = await signUp({ email, password })
const token = await createSession(user)
return { token }
},
})
.merge(
'me',
protectedRoute.query('', {
resolve: async ({ ctx }) => {
return ctx.user
},
})
)
import { t } from '.././trpc'

export const authRouter = t.router({
signIn: t.procedure.input(SignInSchema).mutation((req) => {
const { input } = req

return signIn({ email: input.email, password: input.password })
}),
signUp: t.procedure.input(SignUpSchema).mutation(async (req) => {
const input = req.input

const user = await signUp({ email: input.email, password: input.password })
const token = await createSession(user)
return { token }
}),
me: protectedProcedure.query(async (req) => {
const { ctx } = req
return ctx.user
}),
})
31 changes: 16 additions & 15 deletions packages/api/src/routers/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import crypto from 'crypto'
import { getUserFromHeader } from '../utils/auth'
import { User } from '.prisma/client'
import { prismaClient } from 'db'
import { t } from '../trpc'

const ADMIN_ROLES = ['ADMIN', 'SUPERADMIN']

Expand All @@ -30,23 +31,23 @@ export const createContext = async ({
prisma: prismaClient,
}
}

export const protectedRoute = createRouter().middleware(
async ({ ctx, next }) => {
const user = await getUserFromHeader(ctx.headers)
if (!user) {
throw new TRPCError({
message: `Unauthenticated when trying to access ${ctx.req.url}`,
code: 'UNAUTHORIZED',
})
}
ctx.user = user
ctx.isAdmin = isAdmin(user.role)
return next()
export const protectedRoute = t.middleware(async (req) => {
const { ctx, next } = req
const user = await getUserFromHeader(ctx.headers)
if (!user) {
throw new TRPCError({
message: `Unauthenticated when trying to access ${ctx.req.url}`,
code: 'UNAUTHORIZED',
})
}
)
ctx.user = user
ctx.isAdmin = isAdmin(user.role)
return next()
})

export const protectedProcedure = t.procedure.use(protectedRoute)

export const adminRoute = createRouter().middleware(async ({ ctx, next }) => {
export const adminRoute = t.middleware(async ({ ctx, next }) => {
const user = await getUserFromHeader(ctx.headers)

if (!user) {
Expand Down
69 changes: 38 additions & 31 deletions packages/api/src/routers/post.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import { createRouter, protectedRoute } from './context'
import { z } from 'zod'
import { protectedProcedure } from './context'
import { t } from '.././trpc'

export const postRouter = protectedRoute
.query('get-all', {
async resolve({ ctx }) {
return await ctx.prisma.post.findMany({
include: {
author: true,
},
export const postRouter = t.router({
getAll: protectedProcedure.query(async (req) => {
const { ctx } = req
return await ctx.prisma.post.findMany({
include: {
author: true,
},
})
}),
getById: protectedProcedure
.input(
z.object({
id: z.string().uuid(),
})
},
})
.query('get-by-id', {
input: z.object({
id: z.string().uuid(),
}),
async resolve({ input, ctx }) {
)
.query(async (req) => {
const { ctx, input } = req
return await ctx.prisma.post.findFirst({
where: {
id: input.id,
Expand All @@ -27,33 +30,37 @@ export const postRouter = protectedRoute
title: 'asc',
},
})
},
})
.mutation('create', {
input: z.object({
authorId: z.string(),
title: z.string(),
content: z.string(),
}),
async resolve({ input, ctx }) {
create: protectedProcedure
.input(
z.object({
authorId: z.string(),
title: z.string(),
content: z.string(),
})
)
.mutation(async (req) => {
const { input, ctx } = req
return await ctx.prisma.post.create({
data: {
authorId: input.authorId,
title: input.title,
content: input.content,
},
})
},
})
.mutation('delete', {
input: z.object({
id: z.string().uuid(),
}),
async resolve({ input, ctx }) {
delete: protectedProcedure
.input(
z.object({
id: z.string().uuid(),
})
)
.mutation(async (req) => {
const { input, ctx } = req
return await ctx.prisma.post.delete({
where: {
id: input.id,
},
})
},
})
}),
})
15 changes: 15 additions & 0 deletions packages/api/src/trpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { initTRPC } from '@trpc/server'
import superjson from 'superjson'
import { Context } from './routers/context'

export const t = initTRPC.context<Context>().create({
transformer: superjson,
errorFormatter({ shape }) {
return {
...shape,
data: {
...shape.data,
},
}
},
})
8 changes: 5 additions & 3 deletions packages/app/features/post/details-screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ const TextStyled = styled(Text, 'mb-4 text-center')
export function PostDetailScreen() {
const [id] = useParam('id')

const { data, isLoading } = trpc.useQuery(['post.get-by-id', { id: id! }], {
enabled: !!id,
})
//TODO: confirm this
const { data, isLoading } = trpc.post.getById.useQuery({ id: id! }, {
enabled: !!id,
trpc: {}
})

if (isLoading)
return (
Expand Down
3 changes: 2 additions & 1 deletion packages/app/features/post/list-screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import { GoBack } from 'app/components/GoBack'
const Card = styled(View, 'bg-white shadow-sm mb-4 rounded-lg p-6 border')

export function PostListScreen() {
const { data: posts } = trpc.useQuery(['post.get-all'])
// TODO: confirm this
const { data: posts } = trpc.post.getAll.useQuery()

return (
<View tw="flex-1 justify-center items-center p-4">
Expand Down
10 changes: 5 additions & 5 deletions packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
"dependencies": {
"@react-navigation/native": "^6.0.8",
"@react-navigation/native-stack": "^6.5.0",
"@trpc/client": "^9.15.0",
"@trpc/next": "^9.15.0",
"@trpc/react": "^9.15.0",
"@trpc/server": "^9.15.0",
"@trpc/client": "10.0.0-proxy-beta.17",
"@trpc/next": "10.0.0-proxy-beta.17",
"@trpc/react": "10.0.0-proxy-beta.17",
"@trpc/server": "10.0.0-proxy-beta.17",
"api": "*",
"dripsy": "^3.6.0",
"expo-linking": "^3.0.0",
"expo-updates": "^0.14.3",
"jwt-decode": "^3.1.2",
"lib": "*",
"moti": "canary",
"react-query": "^3.34.7",
"@tanstack/react-query": "^4.10.3",
"solito": "latest",
"twrnc": "^3.3.3",
"universal": "*"
Expand Down
26 changes: 15 additions & 11 deletions packages/app/provider/APIProvider/APIProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import { trpc } from 'app/utils/trpc'
import { useState } from 'react'
import { QueryClient, QueryClientProvider } from 'react-query'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import SafeStorage from 'lib/safe-storage'
import Config from 'app/config'
import { httpBatchLink } from '@trpc/client'

const createTrpcClient = () => {
return trpc.createClient({
url: Config.apiUrl,
async headers() {
const sessionToken = await SafeStorage.get('sessionToken')

return {
authorization: sessionToken ? `Bearer ${sessionToken}` : undefined,
'Content-Type': 'application/json',
Accept: 'application/json',
}
},
links: [
httpBatchLink({
url: Config.apiUrl,
async headers() {
const sessionToken = SafeStorage.get('sessionToken')
return {
authorization: sessionToken ? `Bearer ${sessionToken}` : undefined,
'Content-Type': 'application/json',
Accept: 'application/json',
}
},
}),
],
})
}

Expand Down
15 changes: 8 additions & 7 deletions packages/app/provider/AuthProvider/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import SafeStorage from 'lib/safe-storage'
import { trpc } from 'app/utils/trpc'
import jwtDecode from 'jwt-decode'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useQueryClient } from 'react-query'
import { useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'solito/router'
import { AuthInterface } from './types'
import { routes } from 'app/navigation/routePaths'
Expand Down Expand Up @@ -45,7 +45,7 @@ const useAuthenticate = (setSessionToken: (token: string) => void) => {

export const useSignIn = (setSessionToken: (token: string) => void) => {
const authenticate = useAuthenticate(setSessionToken)
const loginMutation = trpc.useMutation('auth.signIn', {
const loginMutation = trpc.auth.signIn.useMutation({
onSuccess: (data) => {
authenticate(data.token)
},
Expand All @@ -59,7 +59,7 @@ export const useSignIn = (setSessionToken: (token: string) => void) => {

export const useSignUp = (setSessionToken: (token: string) => void) => {
const authenticate = useAuthenticate(setSessionToken)
const signupMutation = trpc.useMutation('auth.signUp', {
const signupMutation = trpc.auth.signUp.useMutation({
onSuccess: (data) => {
authenticate(data.token)
},
Expand All @@ -72,10 +72,11 @@ export const useSignUp = (setSessionToken: (token: string) => void) => {
}

export const useGetMe = (sessionToken: string) => {
return trpc.useQuery(['auth.me'], {
enabled: !!sessionToken,
retry: false,
})
return trpc.auth.me.useQuery(undefined, {
enabled: !!sessionToken,
retry: false,
trpc: {}
})
}

export const useLogout = (setSessionToken: (token: string) => void) => {
Expand Down
Loading