Skip to content

Commit

Permalink
feat: update /users routes to use new DB
Browse files Browse the repository at this point in the history
  • Loading branch information
dromzeh committed Jul 14, 2023
1 parent 1cce64c commit e854749
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 156 deletions.
8 changes: 4 additions & 4 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { getGenerator } from "@/routes/oc-generators/getGenerator";
import { getGenerators } from "@/routes/oc-generators/getGenerators";
import { getSearch, getRecentAssets } from "@/routes/search/search";
import { downloadFile } from "@/routes/download/downloadFile";
// import { getUserById } from "@/routes/user/getUserById";
// import { getUserBySearch } from "@/routes/user/getUsersBySearch";
import { getUserByUsername } from "@/routes/user/getUserByUsername";
import { getUserBySearch } from "@/routes/user/getUsersBySearch";
import { allGames } from "@/routes/games/allGames";
import { getAssetFromId } from "@/routes/asset/getAssetFromId";

Expand All @@ -17,10 +17,10 @@ const router = Router();
router
.get("/", errorHandler(index))
.get("/games", errorHandler(allGames))
// .get("/user/:id", errorHandler(getUserById))
.get("/user/:name", errorHandler(getUserByUsername))
.get("/recent", errorHandler(getRecentAssets))
.get("/asset/:id", errorHandler(getAssetFromId))
// .get("/user/search/:name", errorHandler(getUserBySearch))
.get("/user/s/:name", errorHandler(getUserBySearch))
.get("/search", errorHandler(getSearch))
.get("/download/:id", errorHandler(downloadFile))
.get("/oc-generators", errorHandler(getGenerators))
Expand Down
18 changes: 10 additions & 8 deletions src/lib/types/user.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
export interface User {
id: number;
displayName: string;
name: string;
avatarUrl: string;
discordId: number;
bio: string;
assetsUploaded: number;
roles: string;
id: string;
avatar_url: string | null;
banner_url: string | null;
username: string;
username_colour: string;
bio: string | null;
pronouns: string | null;
verified: number;
date_joined: string;
role: string;
}
13 changes: 2 additions & 11 deletions src/routes/asset/getAssetFromId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,8 @@ export const getAssetFromId = async (
const url = new URL(request.url);
const id = url.pathname.split("/")[2];

if (isNaN(parseInt(id))) {
return new Response(
JSON.stringify({
success: false,
status: "error",
error: "404 Not Found",
}),
{
headers: responseHeaders,
}
);
if (!id || isNaN(parseInt(id))) {
throw new Error("No ID provided");
}

const cacheKey = new Request(url.toString(), request);
Expand Down
13 changes: 2 additions & 11 deletions src/routes/download/downloadFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,8 @@ export const downloadFile = async (
const url = new URL(request.url);
const id = url.pathname.split("/")[2];

if (isNaN(parseInt(id))) {
return new Response(
JSON.stringify({
success: false,
status: "error",
error: "404 Not Found",
}),
{
headers: responseHeaders,
}
);
if (!id || isNaN(parseInt(id))) {
throw new Error("No ID provided");
}

const db = await getConnection(env);
Expand Down
93 changes: 0 additions & 93 deletions src/routes/user/getUserById.ts

This file was deleted.

97 changes: 97 additions & 0 deletions src/routes/user/getUserByUsername.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { responseHeaders } from "@/lib/responseHeaders";
import type { User } from "@/lib/types/user";
import type { Asset } from "@/lib/types/asset";
import { getConnection } from "@/lib/planetscale";

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

if (!name) {
throw new Error("No Name provided");
}

const cacheKey = new Request(url.toString(), request);

const cache = caches.default;

let response = await cache.match(cacheKey);

if (response) {
return response;
}

const db = await getConnection(env);

const row = await db
.execute("SELECT * FROM auth_user WHERE username = ?", [name])
.then((row) => row.rows[0] as User | undefined);

const user = {
id: row.id,
username: row.username,
avatar_url: row.avatar_url || null,
banner_url: row.banner_url || null,
bio: row.bio || null,
pronouns: row.pronouns || null,
verified: row.verified,
date_joined: row.date_joined,
roles: row.role,
};

const uploadedAssets = await db
.execute(
"SELECT * FROM assets WHERE uploaded_by = ? ORDER BY uploaded_date DESC LIMIT 5",
[user.id]
)
.then((row) => row.rows as Asset[] | undefined)
.then((row) =>
row?.map((asset) => {
return {
id: asset.id,
name: asset.name,
game: asset.game,
assetCategory: asset.asset_category,
url: asset.url,
tags: asset.tags,
status: asset.status,
uploadedBy: asset.uploaded_by,
uploadedDate: asset.uploaded_date,
fileSize: asset.file_size,
};
})
);

if (!row) {
return new Response(
JSON.stringify({
success: false,
status: "error",
error: "404 Not Found",
}),
{
headers: responseHeaders,
}
);
}

response = new Response(
JSON.stringify({
success: true,
status: "ok",
user,
uploadedAssets,
}),
{
headers: responseHeaders,
}
);

response.headers.set("Cache-Control", "s-maxage=60");
await cache.put(cacheKey, response.clone());

return response;
};
54 changes: 25 additions & 29 deletions src/routes/user/getUsersBySearch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { responseHeaders } from "@/lib/responseHeaders";
import type { User } from "@/lib/types/user";
import { getConnection } from "@/lib/planetscale";

export const getUserBySearch = async (
request: Request,
Expand All @@ -16,39 +17,34 @@ export const getUserBySearch = async (
if (response) {
return response;
}
const row: D1Result<User> = await env.database
.prepare(
`SELECT * FROM users WHERE displayName = ? OR name = ? OR name LIKE ?`
)
.bind(name, name, `%${name}%`)
.run();

if (!row.results.length) {
return new Response(
JSON.stringify({
success: false,
status: "error",
error: "404 Not Found",
}),
{
headers: responseHeaders,
}
);
const db = await getConnection(env);

const row = await db
.execute("SELECT * FROM auth_user WHERE username LIKE ?", [name])
.then((row) => row.rows as User[] | undefined);

if (!row) {
throw new Error("No User found");
}

const results = row.results.map((result) => ({
id: result.id,
displayName: result.displayName,
name: result.name,
url: `/user/${result.id}`,
avatarUrl: result.avatarUrl,
discordId: result.discordId,
bio: result.bio,
assetsUploaded: result.assetsUploaded,
roles: result.roles,
}));
const results = row?.map((user) => {
return {
id: user.id,
username: user.username,
avatar_url: user.avatar_url || null,
banner_url: user.banner_url || null,
bio: user.bio || null,
pronouns: user.pronouns || null,
verified: user.verified,
date_joined: user.date_joined,
roles: user.role,
};
});

results.sort((a, b) => (a.name === name ? -1 : b.name === name ? 1 : 0));
results.sort((a, b) =>
a.username === name ? -1 : b.username === name ? 1 : 0
);

response = new Response(
JSON.stringify({
Expand Down

0 comments on commit e854749

Please sign in to comment.