Skip to content

Commit

Permalink
Adds user, repo, and prisma functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
sudoFerraz committed Feb 7, 2024
1 parent f0b4a5d commit 5a34bc8
Show file tree
Hide file tree
Showing 17 changed files with 265 additions and 23 deletions.
8 changes: 8 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema

# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"

NEXTAUTH_SECRET=""

GITHUB_ID=""
Expand Down
7 changes: 7 additions & 0 deletions .example.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema

# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,14 @@ yarn-error.log*

# local env files
.env*.local
.env

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

#local database data
/data/
5 changes: 5 additions & 0 deletions globals.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PrismaClient } from "@prisma/client";

declare global {
var prisma: PrismaClient;
}
1 change: 1 addition & 0 deletions next-auth.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ declare module "next-auth" {
interface Session {
accessToken?: string;
githubLogin?: string;
userId?: string;
}
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@mdx-js/loader": "^3.0.0",
"@mdx-js/react": "^3.0.0",
"@next/mdx": "^14.1.0",
"@prisma/client": "5.9.1",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-dropdown-menu": "^2.0.6",
Expand All @@ -30,6 +31,7 @@
"next-auth": "^4.24.5",
"next-themes": "^0.2.1",
"prettier": "^3.2.4",
"prisma": "^5.9.1",
"react": "^18",
"react-dom": "^18",
"remark-gfm": "^4.0.0",
Expand Down
27 changes: 27 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model User {
id String @id @default(uuid())
username String @db.VarChar(255)
email String @unique
created_at DateTime @default(now()) @db.Timestamp(6)
GithubRepo GithubRepo[]
}

model GithubRepo {
id String @id @default(uuid())
user_id String
user User @relation(fields: [user_id], references: [id])
name String
full_name String
}
16 changes: 12 additions & 4 deletions src/app/api/auth/[...nextauth]/options.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { AuthOptions } from "next-auth";
import { JWT } from "next-auth/jwt";
import GithubProvider from "next-auth/providers/github";
import { GithubUserDto } from "./types/githubUser.dto";
import { synchronizeUser } from "./syncUser";

export const options: AuthOptions = {
providers: [
Expand All @@ -21,7 +23,7 @@ export const options: AuthOptions = {
token.id = account.id;
}
if (profile) {
token.githubLogin = transformProfile(profile);
token.githubLogin = transformProfile(profile)?.login;
}
return token;
}
Expand All @@ -31,15 +33,21 @@ export const options: AuthOptions = {
if (token) {
session.accessToken = token.accessToken?.toString();
session.githubLogin = token.githubLogin?.toString();
if (session.user?.email && session.githubLogin) {
session.userId = await synchronizeUser(
session.user?.email,
session.githubLogin,
);
}
}

return session;
},
},
};

export function transformProfile(profile: any): string | null {
export function transformProfile(profile: any): GithubUserDto {
const stringifiedProfile = JSON.stringify(profile);
const parsedProfile = JSON.parse(stringifiedProfile);
return parsedProfile["login"];
const parsedProfile = JSON.parse(stringifiedProfile) as GithubUserDto;
return parsedProfile;
}
20 changes: 20 additions & 0 deletions src/app/api/auth/[...nextauth]/syncUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import prisma from "db";

export async function synchronizeUser(
email: string,
username: string,
): Promise<string> {
const foundUser = await prisma.user.findUnique({
where: { email: email },
});
if (!foundUser) {
const createdUser = await prisma.user.create({
data: {
username: username,
email: email,
},
});
return createdUser.id;
}
return foundUser.id;
}
48 changes: 48 additions & 0 deletions src/app/api/auth/[...nextauth]/types/githubUser.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export interface GithubUserDto {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
name: string;
company: string;
blog: string;
location: string;
email: string;
hireable: boolean;
bio: string;
twitter_username: string;
public_repos: number;
public_gists: number;
followers: number;
following: number;
created_at: string;
updated_at: string;
private_gists: number;
total_private_repos: number;
owned_private_repos: number;
disk_usage: number;
collaborators: number;
two_factor_authentication: boolean;
plan: GithubPlanDto;
}

export interface GithubPlanDto {
name: string;
space: number;
collaborators: number;
private_repos: number;
}
45 changes: 42 additions & 3 deletions src/app/api/github/repo/route.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { NextResponse } from "next/server";
import prisma from "db";
import { NextResponse, NextRequest } from "next/server";
import { fetchPaginatedGithubRepoResult } from "./fetchRepositories";
import { getServerSession } from "next-auth";
import { options } from "../../auth/[...nextauth]/options";
import { register } from "module";

export async function GET() {
const session = await getServerSession(options);
console.log("route!");
console.log(session);
if (session?.accessToken && session?.githubLogin) {
const githubRepos = await fetchPaginatedGithubRepoResult(
session.accessToken,
Expand All @@ -16,3 +16,42 @@ export async function GET() {
}
return NextResponse.json({ success: false, gitRepos: [] });
}

export type GitRepoRegisterDto = {
name: string;
full_name: string;
};

export async function POST(req: NextRequest) {
try {
const session = await getServerSession(options);
const registerRepoDto = (await req.json()) as GitRepoRegisterDto;
if (session?.userId) {
const foundRepo = await prisma.githubRepo.findFirst({
where: {
user_id: session.userId,
name: registerRepoDto.name,
full_name: registerRepoDto.full_name,
},
});
if (!foundRepo) {
await prisma.githubRepo.create({
data: {
user_id: session.userId,
name: registerRepoDto.name,
full_name: registerRepoDto.full_name,
},
});
console.log("criou");
return NextResponse.json({ success: true, created: true });
}
console.log("achou");
return NextResponse.json({ success: true, created: false });
}
console.log("falhou");
return NextResponse.json({ success: false, created: false });
} catch (error) {
console.log(error);
return NextResponse.json({ success: false, created: false });
}
}
33 changes: 22 additions & 11 deletions src/app/gitrepo/columns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { Button } from "@/components/ui/button";
import { MoreHorizontal } from "lucide-react";
import axios from "axios";
import {
DropdownMenu,
DropdownMenuContent,
Expand All @@ -28,22 +29,32 @@ export type GitRepoView = {
export const columns: ColumnDef<GitRepoView>[] = [
{
id: "select",
// header: ({ table }) => (
// <Checkbox
// checked={
// table.getIsAllPageRowsSelected() ||
// (table.getIsSomePageRowsSelected() && "indeterminate")
// }
// onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
// aria-label="Select all"
// />
// ),
header: () => <div className="text-left"> Is Registered </div>,
cell: ({ row }) => {
const repo = row.original;
// const [open, setOpen] = useState(false);
// const [result, setResult] = useState<BasicIpfsData>();
// const note = row.original;
//
const handleRegisterRepo = async (register: boolean) => {
if (register) {
const { data } = await axios.post(`/api/github/repo`, {
name: repo.name,
full_name: repo.full_name,
});
}
};

return (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
onCheckedChange={(value) => {
console.log("VALUE OF CHECKBOX:");
console.log(value);
console.log(row.getValue("name"));
handleRegisterRepo(!!value);
row.toggleSelected(!!value);
}}
aria-label="Select row"
/>
);
Expand Down
1 change: 0 additions & 1 deletion src/app/gitrepo/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { fetchPaginatedGithubRepoResult } from "../api/github/repo/fetchReposito
import { DataTable } from "./data-table";
import { GitRepoView, columns } from "./columns";

// function to check if number is even or odd
export default async function GitRepo() {
const session = await getServerSession(options);
let githubRepos: GithubRepoDto[] = [];
Expand Down
14 changes: 14 additions & 0 deletions src/lib/prisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { PrismaClient } from "@prisma/client";

let prisma: PrismaClient;

if (process.env.NODE_ENV === "production") {
prisma = new PrismaClient();
} else {
if (!global.prisma) {
global.prisma = new PrismaClient();
}
prisma = global.prisma;
}

export default prisma;
6 changes: 3 additions & 3 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
return twMerge(clsx(inputs));
}
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
}
],
"paths": {
"@/*": ["./src/*"]
"@/*": ["./src/*"],
"db": ["./src/lib/prisma"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
Expand Down
Loading

0 comments on commit 5a34bc8

Please sign in to comment.