Skip to content

Commit

Permalink
added types, services and repository api route
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhruwang committed Jan 19, 2024
1 parent d04cbe2 commit 9e9f937
Show file tree
Hide file tree
Showing 12 changed files with 195 additions and 137 deletions.
11 changes: 11 additions & 0 deletions app/api/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { getApiKeyFromKey } from "@/lib/apikey"

export async function isApiKeyValid(request: Request): Promise<boolean> {
const apiKey = request.headers.get("x-api-key")
if (!apiKey) {
return false
}

const apiKeyData = await getApiKeyFromKey(apiKey)
return Boolean(apiKeyData)
}
40 changes: 0 additions & 40 deletions app/api/me/route.ts

This file was deleted.

54 changes: 54 additions & 0 deletions app/api/repository/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// pages/api/repository.js
import { db } from "@/lib/db"

import { isApiKeyValid } from "../auth"

export async function GET(request) {
if (!isApiKeyValid(request)) return
const { searchParams } = new URL(request.url)
const repositoryId = searchParams.get("id")

if (!repositoryId) {
return new Response("Repository ID is required", { status: 400 })
}

const repository = await db.repository.findUnique({
where: { id: repositoryId },
})

if (!repository) {
return new Response("Repository not found", { status: 404 })
}

return new Response(JSON.stringify(repository), {
headers: { "Content-Type": "application/json" },
status: 200,
})
}

//this route is for teting purpose
export async function POST(request) {
const data = await request.json()

try {
const newRepository = await db.repository.create({
data: {
githubId: data.githubId,
name: data.name,
description: data.description,
homepage: data.homepage,
topics: data.topics,
default_branch: data.default_branch,
installationId: data.installationId,
levels: data.levels,
},
})

return new Response(JSON.stringify(newRepository), {
headers: { "Content-Type": "application/json" },
status: 201,
})
} catch (error) {
return new Response(error.message, { status: 500 })
}
}
23 changes: 22 additions & 1 deletion lib/apikey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { db } from "@/lib/db"

import { TApiKey, TApiKeyCreateInput } from "./types/apiKey"

export const getHash = (key: string): string =>
createHash("sha256").update(key).digest("hex")
export const getApiKey = async (apiKeyId: string): Promise<TApiKey | null> => {
try {
const apiKeyData = await db.apiKey.findUnique({
Expand Down Expand Up @@ -53,7 +55,6 @@ export async function createApiKey(
respositoryId: { connect: { id: respositoryId } },
},
})
console.log({ ...result, apiKey: key })
return { ...result, apiKey: key }
} catch (error) {
throw error
Expand All @@ -73,3 +74,23 @@ export const deleteApiKey = async (id: string): Promise<TApiKey | null> => {
throw error
}
}

export const getApiKeyFromKey = async (
apiKey: string
): Promise<TApiKey | null> => {
if (!apiKey) {
throw new Error("API key required")
}
const hashedKey = getHash(apiKey)
try {
const apiKeyData = await db.apiKey.findUnique({
where: {
hashedKey,
},
})

return apiKeyData
} catch (error) {
throw error
}
}
16 changes: 16 additions & 0 deletions lib/types/installation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { z } from "zod"

import { ZMembership } from "./membership"
import { ZRepository } from "./repository"

const InstallationTypeEnum = z.enum(["TYPE1", "TYPE2"])

export const ZInstallation = z.object({
id: z.string().cuid2(),
githubId: z.number().int().nonnegative(),
type: InstallationTypeEnum,
memberships: z.array(ZMembership),
repositories: z.array(ZRepository),
})

export type TInstallation = z.infer<typeof ZInstallation>
2 changes: 1 addition & 1 deletion lib/types/level.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { z } from "zod"
export const ZLevel = z.object({
id: z.string().cuid2(),
name: z.string(),
pointThreshold: z.string(), // Assuming pointThreshold is stored as a string
pointThreshold: z.string(),
repositoryId: z.string().cuid2(),
})

Expand Down
16 changes: 16 additions & 0 deletions lib/types/membership.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { z } from "zod"

import { ZInstallation } from "./installation"
import { ZUser } from "./user"

const MembershipRoleEnum = z.enum(["owner", "member"])

export const ZMembership = z.object({
installationId: z.string().cuid2(),
userId: z.string().cuid2(),
role: MembershipRoleEnum,
installation: ZInstallation,
user: ZUser,
})

export type TMembership = z.infer<typeof ZMembership>
19 changes: 19 additions & 0 deletions lib/types/pointTransaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { z } from "zod"

import { ZRepository } from "./repository"
import { ZUser } from "./user"

export const ZPointTransaction = z.object({
id: z.string().cuid2(),
points: z.number().int(),
description: z.string(),
url: z.string().url().optional(),
userId: z.string().cuid2(),
repositoryId: z.string().cuid2(),
createdAt: z.date(),
updatedAt: z.date(),
user: ZUser,
repository: ZRepository,
})

export type TPointTransaction = z.infer<typeof ZPointTransaction>
33 changes: 18 additions & 15 deletions lib/types/repository.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,34 @@
import { z } from "zod"

import { ZApiKey } from "./apiKey"
import { ZInstallation } from "./installation"
import { ZLevel } from "./level"
import { ZPointTransaction } from "./pointTransaction"

export const ZRepository = z.object({
id: z.string().cuid2(),
githubId: z.number().int().nonnegative(),
name: z.string(),
description: z.string().nullable(),
isPrivate: z.boolean(),
createdAt: z.date(),
updatedAt: z.date(),
ownerId: z.string().cuid2(),
ownerType: z.enum(["ORGANIZATION", "USER"]),
userId: z.string().cuid2(),
apiKeys: z.array(ZApiKey),
// Include other fields if needed
description: z.string().optional(),
homepage: z.string().url().optional(),
topics: z.array(z.string()),
default_branch: z.string(),
installationId: z.string().cuid2(),
levels: z.array(ZLevel),
pointTransactions: z.array(ZPointTransaction),
installation: ZInstallation,
})

export type TRepository = z.infer<typeof ZRepository>

export const ZRepositoryCreateInput = z.object({
githubId: z.number().int().nonnegative(),
name: z.string(),
description: z.string().optional(),
isPrivate: z.boolean().optional(),
ownerId: z.string().cuid2(),
ownerType: z.enum(["ORGANIZATION", "USER"]),
userId: z.string().cuid2(),
// Include other fields required for creation
homepage: z.string().url().optional(),
topics: z.array(z.string()),
default_branch: z.string(),
installationId: z.string().cuid2(),
levels: z.union([z.array(z.unknown()), z.record(z.unknown())]).optional(),
})

export type TRepositoryCreateInput = z.infer<typeof ZRepositoryCreateInput>
14 changes: 14 additions & 0 deletions lib/types/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { z } from "zod"

import { ZUser } from "./user"

export const ZSession = z.object({
id: z.string().cuid2(),
sessionToken: z.string(),
userId: z.string().cuid2(),
expires: z.date(),

user: ZUser.optional(),
})

export type TSession = z.infer<typeof ZSession>
24 changes: 24 additions & 0 deletions lib/types/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { z } from "zod"

import { ZAccount } from "./account"
import { ZMembership } from "./membership"
import { ZPointTransaction } from "./pointTransaction"
import { ZSession } from "./session"

export const ZUser = z.object({
id: z.string().cuid2(),
githubId: z.number().int().nonnegative().optional(),
name: z.string().optional(),
email: z.string().email().optional(),
emailVerified: z.date().optional(),
image: z.string().url().optional(),
address: z.string().optional(),
createdAt: z.date(),
updatedAt: z.date(),
accounts: z.array(ZAccount),
sessions: z.array(ZSession),
pointTransactions: z.array(ZPointTransaction),
memberships: z.array(ZMembership),
})

export type TUser = z.infer<typeof ZUser>
80 changes: 0 additions & 80 deletions prisma/migrations/20240119111335_add_api_key/migration.sql

This file was deleted.

0 comments on commit 9e9f937

Please sign in to comment.