Skip to content

Code improvement #1

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

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
90 changes: 0 additions & 90 deletions apps/api/index.ts

This file was deleted.

20 changes: 0 additions & 20 deletions apps/api/middleware.ts

This file was deleted.

7 changes: 5 additions & 2 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"module": "index.ts",
"type": "module",
"devDependencies": {
"@types/bun": "latest"
"@types/bun": "latest",
"@types/morgan": "^1.9.9"
},
"peerDependencies": {
"typescript": "^5.0.0"
Expand All @@ -17,6 +18,8 @@
"db": "*",
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
"jwt": "^0.2.0"
"jwt": "^0.2.0",
"morgan": "^1.10.0",
"zod": "^3.24.2"
}
}
File renamed without changes.
148 changes: 148 additions & 0 deletions apps/api/src/controllers/website.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { client } from "db/client";
import type { Request, Response } from "express";
import { WebsiteDataValidation } from "../validations/website";

export const CreateWebsite = async (req: Request, res: Response) => {
try {
const userId = req.userId;

if (!userId) {
res.status(401).json({ success: false, message: "Unauthorized" });
return;
}

const data = WebsiteDataValidation.parse(req.body);

const { url } = data;

const checkIfWebsiteExists = await client.website.findFirst({
where: {
url,
},
});

if (checkIfWebsiteExists) {
res.status(409).json({
success: false,
message: "Website already exists in our database",
});
return;
}

const website = await client.website.create({
data: {
url,
userId,
},
});

res.status(201).json({
success: true,
data: website.id,
message: "Website created successfully",
});
} catch (error) {
console.error("Failed to create website", error);
res.status(500).json({
success: false,
message: "Internal Server Error",
});
}
};

export const GetAllWebsites = async (req: Request, res: Response) => {
try {
const userId = req.userId;

if (!userId) {
res.status(401).json({ success: false, message: "Unauthorized" });
return;
}

const websites = await client.website.findMany({
where: {
userId,
disabled: false,
},
include: {
ticks: true,
},
});

res
.status(200)
.json({ success: true, data: websites, message: "Get all websites" });
} catch (error) {
console.error("Failed to get websites", error);
res.status(500).json({
success: false,
message: "Internal Server Error",
});
}
};

export const GetWebsiteStatus = async (req: Request, res: Response) => {
try {
const userId = req.userId;

if (!userId) {
res.status(401).json({ success: false, message: "Unauthorized" });
return;
}

const websiteId = req.query.websiteId! as unknown as string;

const website = await client.website.findFirst({
where: {
id: websiteId,
userId,
disabled: false,
},
include: {
ticks: true,
},
});

res.status(200).json({
success: true,
data: website,
message: "Website status retrieved successfully",
});
} catch (error) {
console.error("Failed to delete Website", error);
res.status(500).json({ success: false, message: "Internal server error" });
}
};

export const DeleteWebsite = async (req: Request, res: Response) => {
try {
const userId = req.userId;

if (!userId) {
res.status(401).json({ success: false, message: "Unauthorized" });
return;
}

const websiteId = req.body.websiteId; // not nesecarry to validate

await client.website.delete({
where: {
id: websiteId,
userId,
},
});

res.status(200).json({
success: true,
message: "Website deleted successfully",
});
} catch (error) {
console.error("Failed to delete Website", error);
res.status(500).json({ success: false, message: "Internal server error" });
}
};

export const Payout = async (req: Request, res: Response) => {
try {
} catch (error) {}
};
20 changes: 20 additions & 0 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import cors from "cors";
import morgan from "morgan";
import express from "express";
import { websiteRouter } from "./routes/website";
import { Transaction, SystemProgram, Connection } from "@solana/web3.js";

const connection = new Connection("https://api.mainnet-beta.solana.com");
const app = express();

// Middleware
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());

// Routes
app.use("/api/v1/website", websiteRouter);

app.listen(8080, () => {
console.log(`Api server is running at port 8080...`);
});
38 changes: 38 additions & 0 deletions apps/api/src/middleware/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import jwt from "jsonwebtoken";
import { JWT_PUBLIC_KEY } from "../config/config";
import type { NextFunction, Request, Response } from "express";

export function authMiddleware(
req: Request,
res: Response,
next: NextFunction
): void {
try {
const token = req.headers["authorization"];

if (!token) {
res.status(401).json({
success: false,
message: "You must be logged in",
error: "Unauthorized",
});
return;
}

const decoded = jwt.verify(token, JWT_PUBLIC_KEY);

if (!decoded || decoded.sub) {
res.status(401).json({ success: false, error: "Unauthorized" });
return;
}

req.userId = decoded.sub as string;
next();
} catch (error) {
res.status(401).json({
success: false,
message: "Invalid token",
error: "Unauthorized",
});
}
}
17 changes: 17 additions & 0 deletions apps/api/src/routes/website.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import express from "express";
import { authMiddleware } from "../middleware/middleware";
import {
CreateWebsite,
DeleteWebsite,
GetAllWebsites,
GetWebsiteStatus,
Payout,
} from "../controllers/website";

export const websiteRouter = express.Router();

websiteRouter.get("/", authMiddleware, GetAllWebsites);
websiteRouter.post("/create", authMiddleware, CreateWebsite);
websiteRouter.get("/status", authMiddleware, GetWebsiteStatus);
websiteRouter.delete("/delete", authMiddleware, DeleteWebsite);
websiteRouter.post("/payout/:validatorId", authMiddleware, Payout);
5 changes: 5 additions & 0 deletions apps/api/src/validations/website.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { z } from "zod";

export const WebsiteDataValidation = z.object({
url: z.string().url({ message: "Invalid URL format" }),
});
2 changes: 1 addition & 1 deletion apps/frontend/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ function App() {

const token = await getToken();
setIsModalOpen(false)
axios.post(`${API_BACKEND_URL}/api/v1/website`, {
axios.post(`${API_BACKEND_URL}/api/v1/website/create`, {
url,
}, {
headers: {
Expand Down
2 changes: 1 addition & 1 deletion apps/frontend/hooks/useWebsites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function useWebsites() {

async function refreshWebsites() {
const token = await getToken();
const response = await axios.get(`${API_BACKEND_URL}/api/v1/websites`, {
const response = await axios.get(`${API_BACKEND_URL}/api/v1/website/`, {
headers: {
Authorization: token,
},
Expand Down
Loading