Skip to content

Commit

Permalink
feat: rewrite to hono sdflkjfsd;
Browse files Browse the repository at this point in the history
  • Loading branch information
dromzeh committed Aug 4, 2023
1 parent 246d51e commit 5fb7550
Show file tree
Hide file tree
Showing 31 changed files with 300 additions and 339 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@planetscale/database": "^1.8.0",
"@prisma/client": "^5.0.0",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"hono": "^3.3.4",
"itty-router": "^4.0.14",
"lucia": "^2.0.0",
"prettier": "^3.0.0",
Expand Down
11 changes: 11 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

44 changes: 0 additions & 44 deletions src/handler.ts

This file was deleted.

41 changes: 37 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
import { router } from "@/handler";
import { Hono } from "hono";
import { Env } from "./worker-configuration";
import assetRoute from "./routes/asset/assetRoute";
import discordRoute from "./routes/discord/discordRoute";
import ocGeneratorRoute from "./routes/oc-generators/ocGeneratorRoutes";
import searchRoute from "./routes/search/searchRoute";
import gamesRoute from "./routes/games/gamesRoute";
import userRoute from "./routes/user/userRoute";

export default {
fetch: router.handle,
};
interface Bindings extends Env {
[key: string]: unknown;
}

const app = new Hono<{ Bindings: Bindings }>();

app.get("/status", (c) => {
c.status(200);
return c.json({ status: "ok" });
});
app.get("/", (c) => {
c.status(200);
return c.json({ status: "ok", routes: app.routes });
});
app.route("/asset", assetRoute);
app.route("/discord", discordRoute);
app.route("/oc-generators", ocGeneratorRoute);
app.route("/search", searchRoute);
app.route("/games", gamesRoute);
app.route("/user", userRoute);
app.all("*", (c) => {
c.status(404);
return c.json({ status: "not found" });
});

// https://hono.dev/api/hono#showroutes
app.showRoutes();

export default app;
4 changes: 0 additions & 4 deletions src/lib/helpers/getQueryParams.ts

This file was deleted.

22 changes: 11 additions & 11 deletions src/lib/helpers/responses/notFoundResponse.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
// helper function to create a 404 Not Found response
export function createNotFoundResponse(errorMessage, responseHeaders) {
const responseBody = {
success: false,
status: "error",
error: "404 Not Found",
message: errorMessage,
};

return new Response(JSON.stringify(responseBody), {
status: 404,
headers: responseHeaders,
});
return new Response(
JSON.stringify({
success: false,
status: "error",
error: errorMessage,
}),
{
status: 404,
headers: responseHeaders,
}
);
}
3 changes: 2 additions & 1 deletion src/lib/planetscale.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { connect } from "@planetscale/database";
import { Env } from "../worker-configuration";

// useful wrapper for planetscale connection
export function getConnection(env) {
export function getConnection(env: Env) {
const config = {
// this can be set with "wrangler secret put" or through the planetscale integration on cf dashboard
host: env.DATABASE_HOST,
Expand Down
47 changes: 26 additions & 21 deletions src/lib/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,33 @@ type queryParameter = string | number;

export const getSearchResults = async (
query: string,
game: string[],
asset: string[],
tags: string[],
env: Env
gameArray: string[],
assetArray: string[],
tagsArray: string[],
c
): Promise<Asset[]> => {
let sqlQuery = `SELECT * FROM assets WHERE 1=1`;
const parameters = [];

sqlQuery = addQueryToSqlQuery(query, sqlQuery, parameters);
sqlQuery = addGameToSqlQuery(game, sqlQuery, parameters);
sqlQuery = addAssetToSqlQuery(asset, sqlQuery, parameters);
sqlQuery = addTagsToSqlQuery(tags, sqlQuery, parameters);
sqlQuery = addGameToSqlQuery(gameArray, sqlQuery, parameters);
sqlQuery = addAssetToSqlQuery(assetArray, sqlQuery, parameters);
sqlQuery = addTagsToSqlQuery(tagsArray, sqlQuery, parameters);

sqlQuery += ` ORDER BY uploaded_date DESC`;

sqlQuery = limitResults(sqlQuery);

if (!query && !game.length && !asset.length && !tags.length) {
if (
!query &&
!gameArray.length &&
!assetArray.length &&
!tagsArray.length
) {
sqlQuery = `SELECT * FROM assets ORDER BY uploaded_date DESC LIMIT 30`;
}

const db = await getConnection(env);
const db = await getConnection(c.env);

return await db
.execute(sqlQuery, parameters)
Expand All @@ -46,42 +51,42 @@ const addQueryToSqlQuery = (
};

const addGameToSqlQuery = (
game: string[],
gameArray: string[],
sqlQuery: string,
parameters: queryParameter[]
): string => {
if (game.length) {
sqlQuery += ` AND game IN (${game.map(() => "?").join(",")})`;
parameters.push(...game);
if (gameArray.length) {
sqlQuery += ` AND game IN (${gameArray.map(() => "?").join(",")})`;
parameters.push(...gameArray);
}
return sqlQuery;
};

const addAssetToSqlQuery = (
asset: string[],
assetArray: string[],
sqlQuery: string,
parameters: queryParameter[]
): string => {
if (asset.length) {
sqlQuery += ` AND asset_category IN (${asset
if (assetArray.length) {
sqlQuery += ` AND asset_category IN (${assetArray
.map(() => "?")
.join(",")})`;
parameters.push(...asset);
parameters.push(...assetArray);
}
return sqlQuery;
};

const addTagsToSqlQuery = (
tags: string[],
tagsArray: string[],
sqlQuery: string,
parameters: queryParameter[]
): string => {
if (tags.length) {
sqlQuery += ` AND tags IN (${tags
if (tagsArray.length) {
sqlQuery += ` AND tags IN (${tagsArray
.map(() => "?")
.join(",")
.toUpperCase()})`;
parameters.push(...tags);
parameters.push(...tagsArray);
}
return sqlQuery;
};
Expand Down
5 changes: 1 addition & 4 deletions src/lib/types/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ export interface LoginBody {
username: string;
password: string;
}

export interface RegisterBody {
username: string;
export interface RegisterBody extends LoginBody {
email: string;
password: string;
passwordConfirm: string;
}
23 changes: 0 additions & 23 deletions src/middleware/errorHandler.ts

This file was deleted.

15 changes: 15 additions & 0 deletions src/routes/asset/assetRoute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Hono } from "hono";
import { getAssetFromId } from "./getAssetFromId";
import { downloadAsset } from "./downloadAsset";

const assetRoute = new Hono();

assetRoute.get("/:id", async (c) => {
return getAssetFromId(c);
});

assetRoute.get("/download/:assetId", async (c) => {
return downloadAsset(c);
});

export default assetRoute;
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,13 @@ import type { Asset } from "@/lib/types/asset";
import { getConnection } from "@/lib/planetscale";
import { createNotFoundResponse } from "@/lib/helpers/responses/notFoundResponse";

export const downloadFile = async (
request: Request,
env: Env
): Promise<Response> => {
const url = new URL(request.url);
const id = url.pathname.split("/")[2];
export const downloadAsset = async (c) => {
const { assetId } = c.req.param();

if (!id || isNaN(parseInt(id))) throw new Error("No ID provided");

const db = await getConnection(env);
const db = await getConnection(c.env);

const row = await db
.execute("SELECT * FROM assets WHERE id = ?", [id])
.execute("SELECT * FROM assets WHERE id = ?", [assetId])
.then((row) => row.rows[0] as Asset | undefined);

if (!row)
Expand All @@ -30,7 +24,7 @@ export const downloadFile = async (

await db.execute(
"UPDATE assets SET download_count = download_count + 1 WHERE id = ?",
[id]
[assetId]
);

return new Response(blob, {
Expand Down
26 changes: 9 additions & 17 deletions src/routes/asset/getAssetFromId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,15 @@ import type { Asset } from "@/lib/types/asset";
import { getConnection } from "@/lib/planetscale";
import { createNotFoundResponse } from "@/lib/helpers/responses/notFoundResponse";

export const getAssetFromId = async (
request: Request,
env: Env
): Promise<Response> => {
const url = new URL(request.url);
const id = url.pathname.split("/")[2];

if (!id || isNaN(parseInt(id))) throw new Error("No ID provided");

const cacheKey = new Request(url.toString(), request);
export const getAssetFromId = async (c) => {
const { id } = c.req.param();
const cacheKey = new Request(c.req.url.toString(), c.req);
const cache = caches.default;
let response = await cache.match(cacheKey);

if (response) return response;

const db = await getConnection(env);
const db = await getConnection(c.env);

const row = await db
.execute("SELECT * FROM assets WHERE id = ?", [id])
Expand Down Expand Up @@ -62,16 +55,15 @@ export const getAssetFromId = async (
};
});

response = new Response(
JSON.stringify({
response = c.json(
{
success: true,
status: "ok",
asset,
similarAssets,
}),
{
headers: responseHeaders,
}
},
200,
responseHeaders
);

response.headers.set("Cache-Control", "s-maxage=604800");
Expand Down
Loading

0 comments on commit 5fb7550

Please sign in to comment.