Skip to content

Commit

Permalink
feat(web): projects 根据 用户查询
Browse files Browse the repository at this point in the history
  • Loading branch information
xinyao27 committed Jul 14, 2022
1 parent e713ca9 commit 9700c35
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 44 deletions.
13 changes: 7 additions & 6 deletions packages/web/src/libs/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import type { Session, User } from '@prisma/client'
import type { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from 'next'
import { unstable_getServerSession } from 'next-auth'
import { getAuthOptions } from '~/pages/api/auth/[...nextauth]'

export async function getAuth(
req: NextApiRequest,
res: NextApiResponse,
req: NextApiRequest | GetServerSidePropsContext['req'],
res: NextApiResponse | GetServerSidePropsContext['res'],
) {
const authOptions = await getAuthOptions()
const session = await unstable_getServerSession(req, res, authOptions)
const session = (await unstable_getServerSession(req, res, authOptions)) as unknown as (Session & { user: User })
if (!session) {
res.status(401).json({ message: 'Please logged in.' })
if ((res as NextApiResponse).status) (res as NextApiResponse).status(401).json({ message: 'Please logged in.' })
return false
}
return true
return session
}
6 changes: 6 additions & 0 deletions packages/web/src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ export const getAuthOptions = async(): Promise<NextAuthOptions> => {
const options: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
providers: [],
callbacks: {
async session({ session, user }) {
session.user = user
return session
},
},
}
if (setting?.emailServer && setting.emailFrom) {
options.providers.push(EmailProvider({
Expand Down
4 changes: 2 additions & 2 deletions packages/web/src/pages/api/projects/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ export default async function handler(
.createHmac('sha256', secret!)
.update(JSON.stringify(project) + new Date().getTime())
.digest('hex')
const result = await serviceCreateProject({ ...project, apiKey })
const result = await serviceCreateProject({ ...project, apiKey }, auth.user)
res.status(200).json(result)
break
}
case 'GET': {
const result = await serviceGetProjectsWithEventCount()
const result = await serviceGetProjectsWithEventCount(auth.user)
res.status(200).json(result)
break
}
Expand Down
5 changes: 0 additions & 5 deletions packages/web/src/pages/create-project.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Box, Button, Center, FormControl, FormErrorMessage, FormLabel, Input, Select } from '@chakra-ui/react'
import type { Project } from '@prisma/client'
import { useRouter } from 'next/router'
import type { ReactElement } from 'react'
import { useCallback } from 'react'
import { useForm } from 'react-hook-form'
import { useSWRConfig } from 'swr'
Expand Down Expand Up @@ -92,8 +91,4 @@ const CreateProject = () => {
)
}

CreateProject.getLayout = function getLayout(page: ReactElement) {
return page
}

export default CreateProject
14 changes: 12 additions & 2 deletions packages/web/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ import ProjectCard from '~/components/projectCard'
import Wrapper from '~/components/wrapper'
import { serviceGetSetting } from '~/services/bootstrap'
import { serviceGetProjectsWithEventCount } from '~/services/projects'
import { getAuth } from '~/libs/middleware'

interface Props {
setting: Setting | null
projects: ProjectWithEventCount[]
}

export const getServerSideProps: GetServerSideProps<Props> = async() => {
export const getServerSideProps: GetServerSideProps<Props> = async(context) => {
const setting = await serviceGetSetting()
if (!setting) {
return {
Expand All @@ -24,7 +25,16 @@ export const getServerSideProps: GetServerSideProps<Props> = async() => {
},
}
}
const projects = await serviceGetProjectsWithEventCount()
const auth = await getAuth(context.req, context.res)
if (!auth) {
return {
redirect: {
destination: '/api/auth/signin',
permanent: false,
},
}
}
const projects = await serviceGetProjectsWithEventCount(auth.user)
if (!projects || !projects.length) {
return {
redirect: {
Expand Down
16 changes: 9 additions & 7 deletions packages/web/src/services/projects.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Project } from '@prisma/client'
import type { Project, User } from '@prisma/client'
import dayjs from 'dayjs'
import type { ProjectWithEventCount } from 'common'
import { prisma } from '~/db'
Expand All @@ -7,12 +7,13 @@ export async function serviceGetProject(id: number) {
return prisma.project.findUniqueOrThrow({ where: { id } })
}

export async function serviceGetProjects() {
return prisma.project.findMany()
export async function serviceGetProjects(user: User) {
if (!user) return []
return prisma.project.findMany({ where: { users: { some: { userId: user.id } } } })
}

export async function serviceGetProjectsWithEventCount(): Promise<ProjectWithEventCount[]> {
const projects = await serviceGetProjects()
export async function serviceGetProjectsWithEventCount(user: User): Promise<ProjectWithEventCount[]> {
const projects = await serviceGetProjects(user)
const projectWithEventCounts = []
for (const project of projects) {
const eventCount = await serviceGetProjectEventsCount(project.id)
Expand All @@ -24,15 +25,16 @@ export async function serviceGetProjectsWithEventCount(): Promise<ProjectWithEve
return projectWithEventCounts
}

export async function serviceCreateProject(data: Project) {
export async function serviceCreateProject(data: Project, user: User) {
let isDefault = false
const projects = await serviceGetProjects()
const projects = await serviceGetProjects(user)
if (!projects.length) isDefault = true

return prisma.project.create({
data: {
...data,
default: isDefault,
users: { create: { userId: user.id } },
},
})
}
Expand Down
14 changes: 14 additions & 0 deletions prisma/migrations/20220714065351_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
-- CreateTable
CREATE TABLE "UsersOnProjects" (
"userId" TEXT NOT NULL,
"projectId" INTEGER NOT NULL,
"assignedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "UsersOnProjects_pkey" PRIMARY KEY ("userId","projectId")
);

-- AddForeignKey
ALTER TABLE "UsersOnProjects" ADD CONSTRAINT "UsersOnProjects_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "UsersOnProjects" ADD CONSTRAINT "UsersOnProjects_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
56 changes: 34 additions & 22 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,27 @@ model Event {
}

model Issue {
id String @id
apiKey String
type String
metadata Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
events Event[]
users EventUsersOnIssues[]
alertEvents AlertEvent[]
id String @id
apiKey String
type String
metadata Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
events Event[]
users EventUsersOnIssues[]
alertEvents AlertEvent[]
}

model EventUser {
id String @id
ipAddress String
uuid String?
email String?
name String?
metadata Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
issues EventUsersOnIssues[]
id String @id
ipAddress String
uuid String?
email String?
name String?
metadata Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
issues EventUsersOnIssues[]
}

model EventUsersOnIssues {
Expand All @@ -63,7 +63,7 @@ model EventUsersOnIssues {
}

model Setting {
id Int @id @default(autoincrement())
id Int @id @default(autoincrement())
githubClientId String
githubClientSecret String
emailServer String?
Expand All @@ -81,6 +81,7 @@ model Project {
image String?
releases Release[]
alerts Alert[]
users UsersOnProjects[]
}

model Release {
Expand Down Expand Up @@ -139,9 +140,9 @@ model Account {
provider String
providerAccountId String
scope String?
refresh_token String? @db.Text @map("refreshToken")
session_state String? @db.Text @map("sessionState")
id_token String? @db.Text @map("idToken")
refresh_token String? @map("refreshToken") @db.Text
session_state String? @map("sessionState") @db.Text
id_token String? @map("idToken") @db.Text
token_type String? @map("tokenType")
type String
userId String
Expand All @@ -166,6 +167,17 @@ model User {
image String?
accounts Account[]
sessions Session[]
projects UsersOnProjects[]
}

model UsersOnProjects {
userId String
projectId Int
assignedAt DateTime @default(now())
user User @relation(fields: [userId], references: [id])
project Project @relation(fields: [projectId], references: [id])
@@id([userId, projectId])
}

model VerificationToken {
Expand Down

0 comments on commit 9700c35

Please sign in to comment.