rhythia-api 84.0.0 → 85.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ {
2
+ "trailingComma": "es5",
3
+ "tabWidth": 2,
4
+ "semi": true,
5
+ "singleQuote": false
6
+ }
@@ -1,74 +1,74 @@
1
- import { NextResponse } from "next/server";
2
- import z from "zod";
3
- import { Database } from "../types/database";
4
- import { protectedApi, validUser } from "../utils/requestUtils";
5
- import { supabase } from "../utils/supabase";
6
-
7
- export const Schema = {
8
- input: z.strictObject({
9
- session: z.string(),
10
- data: z.object({
11
- avatar_url: z.string().optional(),
12
- about_me: z.string().optional(),
13
- username: z.string().optional(),
14
- }),
15
- }),
16
- output: z.object({
17
- error: z.string().optional(),
18
- }),
19
- };
20
-
21
- export async function POST(res: Response): Promise<NextResponse> {
22
- return protectedApi({
23
- response: res,
24
- schema: Schema,
25
- authorization: validUser,
26
- activity: handler,
27
- });
28
- }
29
-
30
- export async function handler(
31
- data: (typeof Schema)["input"]["_type"]
32
- ): Promise<NextResponse<(typeof Schema)["output"]["_type"]>> {
33
- const user = (await supabase.auth.getUser(data.session)).data.user!;
34
- let userData: Database["public"]["Tables"]["profiles"]["Update"];
35
-
36
- // Find user's entry
37
- {
38
- let { data: queryUserData, error } = await supabase
39
- .from("profiles")
40
- .select("*")
41
- .eq("uid", user.id);
42
-
43
- if (!queryUserData?.length) {
44
- return NextResponse.json(
45
- {
46
- error: "User cannot be retrieved from session",
47
- },
48
- { status: 404 }
49
- );
50
- }
51
- userData = queryUserData[0];
52
- }
53
-
54
- const upsertPayload: Database["public"]["Tables"]["profiles"]["Update"] = {
55
- id: userData.id,
56
- ...data.data,
57
- };
58
-
59
- const upsertResult = await supabase
60
- .from("profiles")
61
- .upsert(upsertPayload)
62
- .select();
63
-
64
- if (upsertResult.status == 409) {
65
- return NextResponse.json(
66
- {
67
- error: "Can't update, username might be used by someone else!",
68
- },
69
- { status: 404 }
70
- );
71
- }
72
-
73
- return NextResponse.json({});
74
- }
1
+ import { NextResponse } from "next/server";
2
+ import z from "zod";
3
+ import { Database } from "../types/database";
4
+ import { protectedApi, validUser } from "../utils/requestUtils";
5
+ import { supabase } from "../utils/supabase";
6
+
7
+ export const Schema = {
8
+ input: z.strictObject({
9
+ session: z.string(),
10
+ data: z.object({
11
+ avatar_url: z.string().optional(),
12
+ about_me: z.string().optional(),
13
+ username: z.string().optional(),
14
+ }),
15
+ }),
16
+ output: z.object({
17
+ error: z.string().optional(),
18
+ }),
19
+ };
20
+
21
+ export async function POST(request: Request): Promise<NextResponse> {
22
+ return protectedApi({
23
+ request,
24
+ schema: Schema,
25
+ authorization: validUser,
26
+ activity: handler,
27
+ });
28
+ }
29
+
30
+ export async function handler(
31
+ data: (typeof Schema)["input"]["_type"]
32
+ ): Promise<NextResponse<(typeof Schema)["output"]["_type"]>> {
33
+ const user = (await supabase.auth.getUser(data.session)).data.user!;
34
+ let userData: Database["public"]["Tables"]["profiles"]["Update"];
35
+
36
+ // Find user's entry
37
+ {
38
+ let { data: queryUserData, error } = await supabase
39
+ .from("profiles")
40
+ .select("*")
41
+ .eq("uid", user.id);
42
+
43
+ if (!queryUserData?.length) {
44
+ return NextResponse.json(
45
+ {
46
+ error: "User cannot be retrieved from session",
47
+ },
48
+ { status: 404 }
49
+ );
50
+ }
51
+ userData = queryUserData[0];
52
+ }
53
+
54
+ const upsertPayload: Database["public"]["Tables"]["profiles"]["Update"] = {
55
+ id: userData.id,
56
+ ...data.data,
57
+ };
58
+
59
+ const upsertResult = await supabase
60
+ .from("profiles")
61
+ .upsert(upsertPayload)
62
+ .select();
63
+
64
+ if (upsertResult.status == 409) {
65
+ return NextResponse.json(
66
+ {
67
+ error: "Can't update, username might be used by someone else!",
68
+ },
69
+ { status: 404 }
70
+ );
71
+ }
72
+
73
+ return NextResponse.json({});
74
+ }
@@ -1,68 +1,68 @@
1
- import { NextResponse } from "next/server";
2
- import z from "zod";
3
- import { protectedApi, validUser } from "../utils/requestUtils";
4
- import { supabase } from "../utils/supabase";
5
-
6
- export const Schema = {
7
- input: z.strictObject({
8
- session: z.string(),
9
- page: z.number().optional(),
10
- }),
11
- output: z.object({
12
- error: z.string().optional(),
13
- total: z.number().optional(),
14
- leaderboard: z
15
- .array(
16
- z.object({
17
- flag: z.string().nullable(),
18
- id: z.number(),
19
- username: z.string().nullable(),
20
- play_count: z.number().nullable(),
21
- skill_points: z.number().nullable(),
22
- total_score: z.number().nullable(),
23
- })
24
- )
25
- .optional(),
26
- }),
27
- };
28
-
29
- export async function POST(res: Response): Promise<NextResponse> {
30
- return protectedApi({
31
- response: res,
32
- schema: Schema,
33
- authorization: validUser,
34
- activity: handler,
35
- });
36
- }
37
-
38
- export async function handler(
39
- data: (typeof Schema)["input"]["_type"]
40
- ): Promise<NextResponse<(typeof Schema)["output"]["_type"]>> {
41
- const range = [0, 100];
42
- if (data.page) {
43
- range[0] = 100 * data.page;
44
- range[1] = range[0] + 100;
45
- }
46
-
47
- const countQuery = await supabase
48
- .from("profiles")
49
- .select("*", { count: "exact", head: true });
50
-
51
- let { data: queryData, error } = await supabase
52
- .from("profiles")
53
- .select("*")
54
- .order("skill_points", { ascending: false })
55
- .range(range[0], range[1]);
56
-
57
- return NextResponse.json({
58
- total: countQuery.count || 0,
59
- leaderboard: queryData?.map((user) => ({
60
- flag: user.flag,
61
- id: user.id,
62
- play_count: user.play_count,
63
- skill_points: user.skill_points,
64
- total_score: user.total_score,
65
- username: user.username,
66
- })),
67
- });
68
- }
1
+ import { NextResponse } from "next/server";
2
+ import z from "zod";
3
+ import { protectedApi, validUser } from "../utils/requestUtils";
4
+ import { supabase } from "../utils/supabase";
5
+
6
+ export const Schema = {
7
+ input: z.strictObject({
8
+ session: z.string(),
9
+ page: z.number().optional(),
10
+ }),
11
+ output: z.object({
12
+ error: z.string().optional(),
13
+ total: z.number().optional(),
14
+ leaderboard: z
15
+ .array(
16
+ z.object({
17
+ flag: z.string().nullable(),
18
+ id: z.number(),
19
+ username: z.string().nullable(),
20
+ play_count: z.number().nullable(),
21
+ skill_points: z.number().nullable(),
22
+ total_score: z.number().nullable(),
23
+ })
24
+ )
25
+ .optional(),
26
+ }),
27
+ };
28
+
29
+ export async function POST(res: Response): Promise<NextResponse> {
30
+ return protectedApi({
31
+ response: res,
32
+ schema: Schema,
33
+ authorization: validUser,
34
+ activity: handler,
35
+ });
36
+ }
37
+
38
+ export async function handler(
39
+ data: (typeof Schema)["input"]["_type"]
40
+ ): Promise<NextResponse<(typeof Schema)["output"]["_type"]>> {
41
+ const range = [0, 100];
42
+ if (data.page) {
43
+ range[0] = 100 * data.page;
44
+ range[1] = range[0] + 100;
45
+ }
46
+
47
+ const countQuery = await supabase
48
+ .from("profiles")
49
+ .select("*", { count: "exact", head: true });
50
+
51
+ let { data: queryData, error } = await supabase
52
+ .from("profiles")
53
+ .select("*")
54
+ .order("skill_points", { ascending: false })
55
+ .range(range[0], range[1]);
56
+
57
+ return NextResponse.json({
58
+ total: countQuery.count || 0,
59
+ leaderboard: queryData?.map((user) => ({
60
+ flag: user.flag,
61
+ id: user.id,
62
+ play_count: user.play_count,
63
+ skill_points: user.skill_points,
64
+ total_score: user.total_score,
65
+ username: user.username,
66
+ })),
67
+ });
68
+ }
package/api/getProfile.ts CHANGED
@@ -1,115 +1,115 @@
1
- import { geolocation } from "@vercel/edge";
2
- import { NextResponse } from "next/server";
3
- import z from "zod";
4
- import { Database } from "../types/database";
5
- import { protectedApi, validUser } from "../utils/requestUtils";
6
- import { supabase } from "../utils/supabase";
7
-
8
- export const Schema = {
9
- input: z.strictObject({
10
- session: z.string(),
11
- id: z.number().optional(),
12
- }),
13
- output: z.object({
14
- error: z.string().optional(),
15
- user: z
16
- .object({
17
- about_me: z.string().nullable(),
18
- avatar_url: z.string().nullable(),
19
- badges: z.any().nullable(),
20
- created_at: z.number().nullable(),
21
- flag: z.string().nullable(),
22
- id: z.number(),
23
- uid: z.string().nullable(),
24
- username: z.string().nullable(),
25
- verified: z.boolean().nullable(),
26
- play_count: z.number().nullable(),
27
- skill_points: z.number().nullable(),
28
- squares_hit: z.number().nullable(),
29
- total_score: z.number().nullable(),
30
- position: z.number().nullable(),
31
- })
32
- .optional(),
33
- }),
34
- };
35
-
36
- export async function POST(res: Response): Promise<NextResponse> {
37
- return protectedApi({
38
- response: res,
39
- schema: Schema,
40
- authorization: validUser,
41
- activity: handler,
42
- });
43
- }
44
-
45
- export async function handler(
46
- data: (typeof Schema)["input"]["_type"],
47
- req: Request
48
- ): Promise<NextResponse<(typeof Schema)["output"]["_type"]>> {
49
- let profiles: Database["public"]["Tables"]["profiles"]["Row"][] = [];
50
-
51
- // Fetch by id
52
- if (data.id !== undefined) {
53
- let { data: queryData, error } = await supabase
54
- .from("profiles")
55
- .select("*")
56
- .eq("id", data.id);
57
-
58
- console.log(profiles, error);
59
-
60
- if (!queryData?.length) {
61
- return NextResponse.json(
62
- {
63
- error: "User not found",
64
- },
65
- { status: 404 }
66
- );
67
- }
68
-
69
- profiles = queryData;
70
- } else {
71
- // Fetch by session id
72
- const user = (await supabase.auth.getUser(data.session)).data.user!;
73
-
74
- let { data: queryData, error } = await supabase
75
- .from("profiles")
76
- .select("*")
77
- .eq("uid", user.id);
78
-
79
- console.log(profiles, error);
80
- if (!queryData?.length) {
81
- const geo = geolocation(req);
82
- const data = await supabase
83
- .from("profiles")
84
- .upsert({
85
- uid: user.id,
86
- about_me: "",
87
- avatar_url: user.user_metadata.avatar_url,
88
- badges: ["Early Bird"],
89
- username: user.user_metadata.full_name,
90
- flag: (geo.country || "US").toUpperCase(),
91
- created_at: Date.now(),
92
- })
93
- .select();
94
-
95
- profiles = data.data!;
96
- } else {
97
- profiles = queryData;
98
- }
99
- }
100
-
101
- const user = profiles[0];
102
-
103
- // Query to count how many players have more skill points than the specific player
104
- const { count: playersWithMorePoints, error: rankError } = await supabase
105
- .from("profiles")
106
- .select("*", { count: "exact", head: true })
107
- .gt("skill_points", user.skill_points);
108
-
109
- return NextResponse.json({
110
- user: {
111
- ...user,
112
- position: (playersWithMorePoints || 0) + 1,
113
- },
114
- });
115
- }
1
+ import { geolocation } from "@vercel/edge";
2
+ import { NextResponse } from "next/server";
3
+ import z from "zod";
4
+ import { Database } from "../types/database";
5
+ import { protectedApi, validUser } from "../utils/requestUtils";
6
+ import { supabase } from "../utils/supabase";
7
+
8
+ export const Schema = {
9
+ input: z.strictObject({
10
+ session: z.string(),
11
+ id: z.number().optional(),
12
+ }),
13
+ output: z.object({
14
+ error: z.string().optional(),
15
+ user: z
16
+ .object({
17
+ about_me: z.string().nullable(),
18
+ avatar_url: z.string().nullable(),
19
+ badges: z.any().nullable(),
20
+ created_at: z.number().nullable(),
21
+ flag: z.string().nullable(),
22
+ id: z.number(),
23
+ uid: z.string().nullable(),
24
+ username: z.string().nullable(),
25
+ verified: z.boolean().nullable(),
26
+ play_count: z.number().nullable(),
27
+ skill_points: z.number().nullable(),
28
+ squares_hit: z.number().nullable(),
29
+ total_score: z.number().nullable(),
30
+ position: z.number().nullable(),
31
+ })
32
+ .optional(),
33
+ }),
34
+ };
35
+
36
+ export async function POST(request: Request): Promise<NextResponse> {
37
+ return protectedApi({
38
+ request,
39
+ schema: Schema,
40
+ authorization: validUser,
41
+ activity: handler,
42
+ });
43
+ }
44
+
45
+ export async function handler(
46
+ data: (typeof Schema)["input"]["_type"],
47
+ req: Request
48
+ ): Promise<NextResponse<(typeof Schema)["output"]["_type"]>> {
49
+ let profiles: Database["public"]["Tables"]["profiles"]["Row"][] = [];
50
+
51
+ // Fetch by id
52
+ if (data.id !== undefined) {
53
+ let { data: queryData, error } = await supabase
54
+ .from("profiles")
55
+ .select("*")
56
+ .eq("id", data.id);
57
+
58
+ console.log(profiles, error);
59
+
60
+ if (!queryData?.length) {
61
+ return NextResponse.json(
62
+ {
63
+ error: "User not found",
64
+ },
65
+ { status: 404 }
66
+ );
67
+ }
68
+
69
+ profiles = queryData;
70
+ } else {
71
+ // Fetch by session id
72
+ const user = (await supabase.auth.getUser(data.session)).data.user!;
73
+
74
+ let { data: queryData, error } = await supabase
75
+ .from("profiles")
76
+ .select("*")
77
+ .eq("uid", user.id);
78
+
79
+ console.log(profiles, error);
80
+ if (!queryData?.length) {
81
+ const geo = geolocation(req);
82
+ const data = await supabase
83
+ .from("profiles")
84
+ .upsert({
85
+ uid: user.id,
86
+ about_me: "",
87
+ avatar_url: user.user_metadata.avatar_url,
88
+ badges: ["Early Bird"],
89
+ username: user.user_metadata.full_name,
90
+ flag: (geo.country || "US").toUpperCase(),
91
+ created_at: Date.now(),
92
+ })
93
+ .select();
94
+
95
+ profiles = data.data!;
96
+ } else {
97
+ profiles = queryData;
98
+ }
99
+ }
100
+
101
+ const user = profiles[0];
102
+
103
+ // Query to count how many players have more skill points than the specific player
104
+ const { count: playersWithMorePoints, error: rankError } = await supabase
105
+ .from("profiles")
106
+ .select("*", { count: "exact", head: true })
107
+ .gt("skill_points", user.skill_points);
108
+
109
+ return NextResponse.json({
110
+ user: {
111
+ ...user,
112
+ position: (playersWithMorePoints || 0) + 1,
113
+ },
114
+ });
115
+ }
@@ -1,46 +1,44 @@
1
- import { NextResponse } from "next/server";
2
- import z from "zod";
3
- import { protectedApi } from "../utils/requestUtils";
4
- import { supabase } from "../utils/supabase";
5
-
6
- export const Schema = {
7
- input: z.strictObject({
8
- text: z.string(),
9
- }),
10
- output: z.object({
11
- error: z.string().optional(),
12
- results: z
13
- .array(
14
- z.object({
15
- id: z.number(),
16
- username: z.string().nullable(),
17
- })
18
- )
19
- .optional(),
20
- }),
21
- };
22
-
23
- export async function POST(res: Response): Promise<NextResponse> {
24
- return protectedApi({
25
- response: res,
26
- schema: Schema,
27
- authorization: () => {},
28
- activity: handler,
29
- });
30
- }
31
-
32
- export async function handler(
33
- data: (typeof Schema)["input"]["_type"]
34
- ): Promise<NextResponse<(typeof Schema)["output"]["_type"]>> {
35
- const { data: searchData, error } = await supabase
36
- .from("profiles")
37
- .select()
38
- .ilike("username", `%${data.text}%`)
39
- .limit(10);
40
- return NextResponse.json({
41
- results: (searchData || []).map((data) => ({
42
- id: data.id,
43
- username: data.username,
44
- })),
45
- });
46
- }
1
+ import { NextResponse } from "next/server";
2
+ import z from "zod";
3
+ import { protectedApi } from "../utils/requestUtils";
4
+ import { supabase } from "../utils/supabase";
5
+
6
+ export const Schema = {
7
+ input: z.strictObject({
8
+ text: z.string(),
9
+ }),
10
+ output: z.object({
11
+ error: z.string().optional(),
12
+ results: z
13
+ .array(
14
+ z.object({
15
+ id: z.number(),
16
+ username: z.string().nullable(),
17
+ })
18
+ )
19
+ .optional(),
20
+ }),
21
+ };
22
+
23
+ export async function POST(request: Request) {
24
+ return protectedApi({
25
+ request,
26
+ schema: Schema,
27
+ authorization: () => {},
28
+ activity: handler,
29
+ });
30
+ }
31
+
32
+ export async function handler(data: (typeof Schema)["input"]["_type"]) {
33
+ const { data: searchData, error } = await supabase
34
+ .from("profiles")
35
+ .select()
36
+ .ilike("username", `%${data.text}%`)
37
+ .limit(10);
38
+ return NextResponse.json({
39
+ results: (searchData || []).map((data) => ({
40
+ id: data.id,
41
+ username: data.username,
42
+ })),
43
+ });
44
+ }
@@ -1,95 +1,106 @@
1
- import { NextResponse } from "next/server";
2
- import z from "zod";
3
- import { protectedApi } from "../utils/requestUtils";
4
- import { supabase } from "../utils/supabase";
5
-
6
- export const Schema = {
7
- input: z.strictObject({
8
- session: z.string(),
9
- data: z.strictObject({
10
- token: z.string(),
11
- relayHwid: z.string(),
12
- songId: z.string(),
13
- noteResults: z.record(z.boolean()),
14
- triggers: z.array(z.array(z.number())),
15
- mapHash: z.string(),
16
- mapTitle: z.string(),
17
- mapDifficulty: z.number(),
18
- mapNoteCount: z.number(),
19
- mapLength: z.number(),
20
- }),
21
- }),
22
- output: z.object({
23
- error: z.string().optional(),
24
- }),
25
- };
26
-
27
- export async function POST(res: Response): Promise<NextResponse> {
28
- return protectedApi({
29
- response: res,
30
- schema: Schema,
31
- authorization: () => {},
32
- activity: handler,
33
- });
34
- }
35
-
36
- export async function handler({
37
- data,
38
- session,
39
- }: (typeof Schema)["input"]["_type"]): Promise<
40
- NextResponse<(typeof Schema)["output"]["_type"]>
41
- > {
42
- const user = (await supabase.auth.getUser(session)).data.user!;
43
-
44
- let { data: userData, error: userError } = await supabase
45
- .from("profiles")
46
- .select("*")
47
- .eq("uid", user.id);
48
-
49
- if (!userData?.length)
50
- return NextResponse.json(
51
- {
52
- error: "User doesn't exist",
53
- },
54
- { status: 500 }
55
- );
56
-
57
- let { data: beatmaps, error } = await supabase
58
- .from("beatmaps")
59
- .select("*")
60
- .eq("beatmapHash", data.mapHash);
61
-
62
- let newPlaycount = 1;
63
-
64
- if (beatmaps?.length) {
65
- newPlaycount = (beatmaps[0].playcount || 1) + 1;
66
- }
67
-
68
- const upsertData = await supabase
69
- .from("beatmaps")
70
- .upsert({
71
- beatmapHash: data.mapHash,
72
- title: data.mapTitle,
73
- playcount: newPlaycount,
74
- difficulty: data.mapDifficulty,
75
- noteCount: data.mapNoteCount,
76
- length: data.mapLength,
77
- })
78
- .select();
79
-
80
- const insertData = await supabase
81
- .from("scores")
82
- .upsert({
83
- beatmapHash: data.mapHash,
84
- noteResults: data.noteResults,
85
- replayHwid: data.relayHwid,
86
- songId: data.songId,
87
- triggers: data.triggers,
88
- userId: userData[0].id,
89
- passed: data.mapNoteCount == Object.keys(data.noteResults).length,
90
- misses: Object.values(data.noteResults).filter((e) => !e).length,
91
- })
92
- .select();
93
-
94
- return NextResponse.json({});
95
- }
1
+ import { NextResponse } from "next/server";
2
+ import z from "zod";
3
+ import { protectedApi } from "../utils/requestUtils";
4
+ import { supabase } from "../utils/supabase";
5
+
6
+ export const Schema = {
7
+ input: z.strictObject({
8
+ session: z.string(),
9
+ data: z.strictObject({
10
+ token: z.string(),
11
+ relayHwid: z.string(),
12
+ songId: z.string(),
13
+ noteResults: z.record(z.boolean()),
14
+ triggers: z.array(z.array(z.number())),
15
+ mapHash: z.string(),
16
+ mapTitle: z.string(),
17
+ mapDifficulty: z.number(),
18
+ mapNoteCount: z.number(),
19
+ mapLength: z.number(),
20
+ }),
21
+ }),
22
+ output: z.object({
23
+ error: z.string().optional(),
24
+ }),
25
+ };
26
+
27
+ export async function POST(request: Request): Promise<NextResponse> {
28
+ return protectedApi({
29
+ request,
30
+ schema: Schema,
31
+ authorization: () => {},
32
+ activity: handler,
33
+ });
34
+ }
35
+
36
+ export async function handler({
37
+ data,
38
+ session,
39
+ }: (typeof Schema)["input"]["_type"]): Promise<
40
+ NextResponse<(typeof Schema)["output"]["_type"]>
41
+ > {
42
+ const user = (await supabase.auth.getUser(session)).data.user!;
43
+
44
+ let { data: userData, error: userError } = await supabase
45
+ .from("profiles")
46
+ .select("*")
47
+ .eq("uid", user.id);
48
+
49
+ if (!userData?.length)
50
+ return NextResponse.json(
51
+ {
52
+ error: "User doesn't exist",
53
+ },
54
+ { status: 500 }
55
+ );
56
+
57
+ let { data: beatmaps, error } = await supabase
58
+ .from("beatmaps")
59
+ .select("*")
60
+ .eq("beatmapHash", data.mapHash);
61
+
62
+ let newPlaycount = 1;
63
+
64
+ if (beatmaps?.length) {
65
+ newPlaycount = (beatmaps[0].playcount || 1) + 1;
66
+ }
67
+
68
+ const upsertData = await supabase
69
+ .from("beatmaps")
70
+ .upsert({
71
+ beatmapHash: data.mapHash,
72
+ title: data.mapTitle,
73
+ playcount: newPlaycount,
74
+ difficulty: data.mapDifficulty,
75
+ noteCount: data.mapNoteCount,
76
+ length: data.mapLength,
77
+ })
78
+ .select();
79
+
80
+ const insertData = await supabase
81
+ .from("scores")
82
+ .upsert({
83
+ beatmapHash: data.mapHash,
84
+ noteResults: data.noteResults,
85
+ replayHwid: data.relayHwid,
86
+ songId: data.songId,
87
+ triggers: data.triggers,
88
+ userId: userData[0].id,
89
+ passed: data.mapNoteCount == Object.keys(data.noteResults).length,
90
+ misses: Object.values(data.noteResults).filter((e) => !e).length,
91
+ })
92
+ .select();
93
+
94
+ const insertUserData = await supabase
95
+ .from("profiles")
96
+ .upsert({
97
+ id: userData[0].id,
98
+ play_count: (userData[0].play_count || 0) + 1,
99
+ squares_hit:
100
+ (userData[0].squares_hit || 0) +
101
+ Object.values(data.noteResults).filter((e) => e).length,
102
+ })
103
+ .select();
104
+
105
+ return NextResponse.json({});
106
+ }
package/handleApi.ts CHANGED
@@ -1,19 +1,19 @@
1
- import { z } from "zod";
2
- let env = "development";
3
- export function setEnvironment(
4
- stage: "development" | "testing" | "production"
5
- ) {
6
- env = stage;
7
- }
8
- export function handleApi<
9
- T extends { url: string; input: z.ZodObject<any>; output: z.ZodObject<any> }
10
- >(apiSchema: T) {
11
- return async (input: T["input"]["_type"]): Promise<T["output"]["_type"]> => {
12
- const response = await fetch(`https://${env}.rhythia.com${apiSchema.url}`, {
13
- method: "POST",
14
- body: JSON.stringify(input),
15
- });
16
- const output = await response.json();
17
- return output;
18
- };
19
- }
1
+ import { z } from "zod";
2
+ let env = "development";
3
+ export function setEnvironment(
4
+ stage: "development" | "testing" | "production"
5
+ ) {
6
+ env = stage;
7
+ }
8
+ export function handleApi<
9
+ T extends { url: string; input: z.ZodObject<any>; output: z.ZodObject<any> }
10
+ >(apiSchema: T) {
11
+ return async (input: T["input"]["_type"]): Promise<T["output"]["_type"]> => {
12
+ const response = await fetch(`https://${env}.rhythia.com${apiSchema.url}`, {
13
+ method: "POST",
14
+ body: JSON.stringify(input),
15
+ });
16
+ const output = await response.json();
17
+ return output;
18
+ };
19
+ }
package/index.html CHANGED
@@ -1,3 +1,3 @@
1
- <html>
2
- <div>Rhythia API</div>
1
+ <html>
2
+ <div>Rhythia API</div>
3
3
  </html>
package/index.ts CHANGED
@@ -5,16 +5,16 @@ import { Schema as EditProfile } from "./api/editProfile"
5
5
  export { Schema as SchemaEditProfile } from "./api/editProfile"
6
6
  export const editProfile = handleApi({url:"/api/editProfile",...EditProfile})
7
7
 
8
- // ./api/getLeaderboard.ts API
9
- import { Schema as GetLeaderboard } from "./api/getLeaderboard"
10
- export { Schema as SchemaGetLeaderboard } from "./api/getLeaderboard"
11
- export const getLeaderboard = handleApi({url:"/api/getLeaderboard",...GetLeaderboard})
12
-
13
8
  // ./api/getProfile.ts API
14
9
  import { Schema as GetProfile } from "./api/getProfile"
15
10
  export { Schema as SchemaGetProfile } from "./api/getProfile"
16
11
  export const getProfile = handleApi({url:"/api/getProfile",...GetProfile})
17
12
 
13
+ // ./api/getLeaderboard.ts API
14
+ import { Schema as GetLeaderboard } from "./api/getLeaderboard"
15
+ export { Schema as SchemaGetLeaderboard } from "./api/getLeaderboard"
16
+ export const getLeaderboard = handleApi({url:"/api/getLeaderboard",...GetLeaderboard})
17
+
18
18
  // ./api/searchUsers.ts API
19
19
  import { Schema as SearchUsers } from "./api/searchUsers"
20
20
  export { Schema as SchemaSearchUsers } from "./api/searchUsers"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rhythia-api",
3
- "version": "84.0.0",
3
+ "version": "85.0.0",
4
4
  "main": "index.ts",
5
5
  "scripts": {
6
6
  "update": "bun ./scripts/update.ts",
@@ -1,76 +1,76 @@
1
- import fs from "fs";
2
- import * as git from "isomorphic-git";
3
- import http from "isomorphic-git/http/node";
4
- import path from "path";
5
-
6
- // Set up the repository URL
7
- const repoUrl = `https://${process.env.GIT_KEY}@github.com/cunev/rhythia-api.git`;
8
-
9
- const sourceBranch = process.env.SOURCE_BRANCH!;
10
- const targetBranch = process.env.TARGET_BRANCH!;
11
-
12
- async function cloneBranch() {
13
- const dir = path.join("/tmp", "repo");
14
-
15
- try {
16
- // Ensure the directory is clean before cloning
17
- if (fs.existsSync(dir)) {
18
- fs.rmdirSync(dir, { recursive: true });
19
- console.log(`Deleted existing directory: ${dir}`);
20
- }
21
-
22
- // Clone the repository into a temporary directory
23
- await git.clone({
24
- fs,
25
- http,
26
- dir,
27
- url: repoUrl,
28
- ref: sourceBranch,
29
- singleBranch: true,
30
- depth: 1,
31
- });
32
- console.log(`Cloned ${sourceBranch} branch from remote repository.`);
33
-
34
- // Check out the source branch
35
- await git.checkout({ fs, dir, ref: sourceBranch });
36
- console.log(`Checked out to branch: ${sourceBranch}`);
37
-
38
- // Pull the latest changes from the source branch
39
- await git.pull({
40
- fs,
41
- http,
42
- dir,
43
- ref: sourceBranch,
44
- singleBranch: true,
45
- author: {
46
- name: process.env.GIT_USER,
47
- email: "you@example.com", // Replace with the actual email
48
- },
49
- });
50
- console.log(`Pulled latest changes from branch: ${sourceBranch}`);
51
-
52
- // Create and checkout the target branch from the source branch
53
- await git.branch({ fs, dir, ref: targetBranch });
54
- await git.checkout({ fs, dir, ref: targetBranch });
55
- console.log(`Created and checked out to branch: ${targetBranch}`);
56
-
57
- // Push the new branch to the remote repository
58
- await git.push({
59
- fs,
60
- http,
61
- dir,
62
- remote: "origin",
63
- ref: targetBranch,
64
- force: true,
65
- onAuth: () => ({
66
- username: process.env.GIT_KEY, // GitHub token or password
67
- password: "",
68
- }),
69
- });
70
- console.log(`Pushed new branch to remote: ${targetBranch}`);
71
- } catch (error) {
72
- console.error("Error performing Git operations:", error.message);
73
- }
74
- }
75
-
76
- cloneBranch();
1
+ import fs from "fs";
2
+ import * as git from "isomorphic-git";
3
+ import http from "isomorphic-git/http/node";
4
+ import path from "path";
5
+
6
+ // Set up the repository URL
7
+ const repoUrl = `https://${process.env.GIT_KEY}@github.com/cunev/rhythia-api.git`;
8
+
9
+ const sourceBranch = process.env.SOURCE_BRANCH!;
10
+ const targetBranch = process.env.TARGET_BRANCH!;
11
+
12
+ async function cloneBranch() {
13
+ const dir = path.join("/tmp", "repo");
14
+
15
+ try {
16
+ // Ensure the directory is clean before cloning
17
+ if (fs.existsSync(dir)) {
18
+ fs.rmdirSync(dir, { recursive: true });
19
+ console.log(`Deleted existing directory: ${dir}`);
20
+ }
21
+
22
+ // Clone the repository into a temporary directory
23
+ await git.clone({
24
+ fs,
25
+ http,
26
+ dir,
27
+ url: repoUrl,
28
+ ref: sourceBranch,
29
+ singleBranch: true,
30
+ depth: 1,
31
+ });
32
+ console.log(`Cloned ${sourceBranch} branch from remote repository.`);
33
+
34
+ // Check out the source branch
35
+ await git.checkout({ fs, dir, ref: sourceBranch });
36
+ console.log(`Checked out to branch: ${sourceBranch}`);
37
+
38
+ // Pull the latest changes from the source branch
39
+ await git.pull({
40
+ fs,
41
+ http,
42
+ dir,
43
+ ref: sourceBranch,
44
+ singleBranch: true,
45
+ author: {
46
+ name: process.env.GIT_USER,
47
+ email: "you@example.com", // Replace with the actual email
48
+ },
49
+ });
50
+ console.log(`Pulled latest changes from branch: ${sourceBranch}`);
51
+
52
+ // Create and checkout the target branch from the source branch
53
+ await git.branch({ fs, dir, ref: targetBranch });
54
+ await git.checkout({ fs, dir, ref: targetBranch });
55
+ console.log(`Created and checked out to branch: ${targetBranch}`);
56
+
57
+ // Push the new branch to the remote repository
58
+ await git.push({
59
+ fs,
60
+ http,
61
+ dir,
62
+ remote: "origin",
63
+ ref: targetBranch,
64
+ force: true,
65
+ onAuth: () => ({
66
+ username: process.env.GIT_KEY, // GitHub token or password
67
+ password: "",
68
+ }),
69
+ });
70
+ console.log(`Pushed new branch to remote: ${targetBranch}`);
71
+ } catch (error) {
72
+ console.error("Error performing Git operations:", error.message);
73
+ }
74
+ }
75
+
76
+ cloneBranch();
package/scripts/update.ts CHANGED
@@ -1,49 +1,49 @@
1
- import { $ } from "bun";
2
- import { readdirSync, readFileSync, writeFileSync } from "fs";
3
- import { lowerFirst, upperFirst } from "lodash";
4
- import path from "path";
5
- const packageJson = JSON.parse(readFileSync("./package.json", "utf-8"));
6
-
7
- const versions = packageJson.version.split(".");
8
- versions[0] = Number(versions[0]) + 1;
9
-
10
- packageJson.version = versions.join(".");
11
-
12
- writeFileSync("./package.json", JSON.stringify(packageJson, null, 2));
13
-
14
- const apis = readdirSync("./api");
15
-
16
- const exports: string[] = [];
17
- exports.push(`import { handleApi } from "./handleApi"`);
18
-
19
- for (const api of apis) {
20
- if (
21
- !readFileSync(path.join("./api", api), "utf-8").includes(
22
- "export const Schema"
23
- )
24
- ) {
25
- continue;
26
- }
27
- exports.push(`\n// ./api/${api} API`);
28
-
29
- const apiName = path.parse(api).name;
30
- exports.push(
31
- `import { Schema as ${upperFirst(apiName)} } from "./api/${apiName}"`
32
- );
33
- exports.push(
34
- `export { Schema as Schema${upperFirst(apiName)} } from "./api/${apiName}"`
35
- );
36
-
37
- exports.push(
38
- `export const ${lowerFirst(
39
- apiName
40
- )} = handleApi({url:"/api/${apiName}",...${upperFirst(apiName)}})`
41
- );
42
- }
43
- exports.push(`export { handleApi } from "./handleApi"`);
44
-
45
- writeFileSync("./index.ts", exports.join("\n"));
46
-
47
- // const conf = readFileSync("./.cred", "utf-8");
48
- // await $`npm logout`.nothrow();
49
- await $`yarn publish`;
1
+ import { $ } from "bun";
2
+ import { readdirSync, readFileSync, writeFileSync } from "fs";
3
+ import { lowerFirst, upperFirst } from "lodash";
4
+ import path from "path";
5
+ const packageJson = JSON.parse(readFileSync("./package.json", "utf-8"));
6
+
7
+ const versions = packageJson.version.split(".");
8
+ versions[0] = Number(versions[0]) + 1;
9
+
10
+ packageJson.version = versions.join(".");
11
+
12
+ writeFileSync("./package.json", JSON.stringify(packageJson, null, 2));
13
+
14
+ const apis = readdirSync("./api");
15
+
16
+ const exports: string[] = [];
17
+ exports.push(`import { handleApi } from "./handleApi"`);
18
+
19
+ for (const api of apis) {
20
+ if (
21
+ !readFileSync(path.join("./api", api), "utf-8").includes(
22
+ "export const Schema"
23
+ )
24
+ ) {
25
+ continue;
26
+ }
27
+ exports.push(`\n// ./api/${api} API`);
28
+
29
+ const apiName = path.parse(api).name;
30
+ exports.push(
31
+ `import { Schema as ${upperFirst(apiName)} } from "./api/${apiName}"`
32
+ );
33
+ exports.push(
34
+ `export { Schema as Schema${upperFirst(apiName)} } from "./api/${apiName}"`
35
+ );
36
+
37
+ exports.push(
38
+ `export const ${lowerFirst(
39
+ apiName
40
+ )} = handleApi({url:"/api/${apiName}",...${upperFirst(apiName)}})`
41
+ );
42
+ }
43
+ exports.push(`export { handleApi } from "./handleApi"`);
44
+
45
+ writeFileSync("./index.ts", exports.join("\n"));
46
+
47
+ // const conf = readFileSync("./.cred", "utf-8");
48
+ // await $`npm logout`.nothrow();
49
+ await $`yarn publish`;
@@ -1,51 +1,55 @@
1
- import { NextResponse } from "next/server";
2
- import { supabase } from "./supabase";
3
-
4
- export async function protectedApi({
5
- response,
6
- schema,
7
- authorization,
8
- activity,
9
- }: {
10
- response: Response;
11
- schema: { input: Zod.ZodObject<any>; output: Zod.ZodObject<any> };
12
- authorization: Function;
13
- activity: Function;
14
- }) {
15
- let data;
16
-
17
- try {
18
- const toParse = await response.json();
19
- data = schema.input.parse(toParse);
20
- } catch (error) {
21
- return NextResponse.json({ error: error.toString() }, { status: 400 });
22
- }
23
-
24
- const authorizationReponse = await authorization(data);
25
- if (authorizationReponse) {
26
- return authorizationReponse;
27
- }
28
-
29
- return await activity(data, response);
30
- }
31
-
32
- export async function validUser(data) {
33
- if (!data.session) {
34
- return NextResponse.json(
35
- {
36
- error: "Session is missing",
37
- },
38
- { status: 501 }
39
- );
40
- }
41
-
42
- const user = await supabase.auth.getUser(data.session);
43
- if (user.error || !user.data.user) {
44
- return NextResponse.json(
45
- {
46
- error: "Invalid user session",
47
- },
48
- { status: 400 }
49
- );
50
- }
51
- }
1
+ import { NextResponse } from "next/server";
2
+ import { supabase } from "./supabase";
3
+ import { ZodObject } from "zod";
4
+
5
+ interface Props<
6
+ K = (...args: any[]) => Promise<NextResponse<any>>,
7
+ T = ZodObject<any>
8
+ > {
9
+ request: Request;
10
+ schema: { input: T; output: T };
11
+ authorization?: Function;
12
+ activity: K;
13
+ }
14
+
15
+ export async function protectedApi({
16
+ request,
17
+ schema,
18
+ authorization,
19
+ activity,
20
+ }: Props) {
21
+ try {
22
+ const toParse = await request.json();
23
+ const data = schema.input.parse(toParse);
24
+ if (authorization) {
25
+ const authorizationResponse = await authorization(data);
26
+ if (authorizationResponse) {
27
+ return authorizationResponse;
28
+ }
29
+ }
30
+ return await activity(data, request);
31
+ } catch (error) {
32
+ return NextResponse.json({ error: error.toString() }, { status: 400 });
33
+ }
34
+ }
35
+
36
+ export async function validUser(data) {
37
+ if (!data.session) {
38
+ return NextResponse.json(
39
+ {
40
+ error: "Session is missing",
41
+ },
42
+ { status: 501 }
43
+ );
44
+ }
45
+
46
+ const user = await supabase.auth.getUser(data.session);
47
+ if (user.error || !user.data.user) {
48
+ return NextResponse.json(
49
+ {
50
+ error: "Invalid user session",
51
+ },
52
+ { status: 400 }
53
+ );
54
+ }
55
+ }
package/utils/supabase.ts CHANGED
@@ -1,13 +1,13 @@
1
- import { createClient } from "@supabase/supabase-js";
2
- import { Database } from "../types/database";
3
-
4
- export const supabase = createClient<Database>(
5
- `https://pfkajngbllcbdzoylrvp.supabase.co`,
6
- process.env.ADMIN_KEY || "key",
7
- {
8
- auth: {
9
- autoRefreshToken: false,
10
- persistSession: false,
11
- },
12
- }
13
- );
1
+ import { createClient } from "@supabase/supabase-js";
2
+ import { Database } from "../types/database";
3
+
4
+ export const supabase = createClient<Database>(
5
+ `https://pfkajngbllcbdzoylrvp.supabase.co`,
6
+ process.env.ADMIN_KEY || "key",
7
+ {
8
+ auth: {
9
+ autoRefreshToken: false,
10
+ persistSession: false,
11
+ },
12
+ }
13
+ );
package/vercel.json CHANGED
@@ -1,13 +1,13 @@
1
- {
2
- "headers": [
3
- {
4
- "source": "/api/(.*)",
5
- "headers": [
6
- { "key": "Access-Control-Allow-Credentials", "value": "true" },
7
- { "key": "Access-Control-Allow-Origin", "value": "*" },
8
- { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
9
- { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
10
- ]
11
- }
12
- ]
1
+ {
2
+ "headers": [
3
+ {
4
+ "source": "/api/(.*)",
5
+ "headers": [
6
+ { "key": "Access-Control-Allow-Credentials", "value": "true" },
7
+ { "key": "Access-Control-Allow-Origin", "value": "*" },
8
+ { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
9
+ { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
10
+ ]
11
+ }
12
+ ]
13
13
  }