Skip to content

Commit

Permalink
refactor: migrate thread solves
Browse files Browse the repository at this point in the history
  • Loading branch information
ghostdevv committed Oct 31, 2024
1 parent 04b9d4a commit caa1be6
Show file tree
Hide file tree
Showing 5 changed files with 221 additions and 18 deletions.
50 changes: 50 additions & 0 deletions pocketbase/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ package main
import (
"log"

"github.com/labstack/echo/v5"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/plugins/migratecmd"

_ "svelte-bot-db/migrations"
Expand All @@ -16,6 +22,50 @@ func main() {
Automigrate: true,
})

app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
e.Router.GET("/api/sdb/increment-solve-count/:userId", func(c echo.Context) error {
userId := c.PathParam("userId")

_, err := app.Dao().FindFirstRecordByFilter(
"threadSolves", "user_id = {:userId}",
dbx.Params{"userId": userId},
)

if err != nil {
threadSolvesCollection, err := app.Dao().FindCollectionByNameOrId("threadSolves")
if err != nil {
return err
}

record := models.NewRecord(threadSolvesCollection)
form := forms.NewRecordUpsert(app, record)

form.LoadData(map[string]any{
"user_id": userId,
"count": 0,
})

if err := form.Submit(); err != nil {
return err
}
}

_, err = app.Dao().
DB().
NewQuery("UPDATE threadSolves SET count = count + 1 WHERE user_id = {:userId}").
Bind(dbx.Params{"userId": userId}).
Execute()

if err != nil {
return err
}

return c.String(200, "Incremented")
}, apis.ActivityLogger(app), apis.RequireAdminAuth())

return nil
})

if err := app.Start(); err != nil {
log.Fatal(err)
}
Expand Down
144 changes: 144 additions & 0 deletions pocketbase/migrations/1730345630_created_thread_solves.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package migrations

import (
"encoding/json"

"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)

func init() {
m.Register(func(db dbx.Builder) error {
threadSolvesData := `{
"id": "tn4t8pzh448d674",
"created": "2024-10-31 03:33:50.146Z",
"updated": "2024-10-31 03:33:50.146Z",
"name": "threadSolves",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "tqe9e1ik",
"name": "user_id",
"type": "text",
"required": true,
"presentable": false,
"unique": false,
"options": {
"min": 1,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "galb9ert",
"name": "count",
"type": "number",
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": 0,
"max": null,
"noDecimal": true
}
}
],
"indexes": [
"CREATE UNIQUE INDEX ` + "`" + `idx_Wdx95vJ` + "`" + ` ON ` + "`" + `thread_solves` + "`" + ` (` + "`" + `user_id` + "`" + `)"
],
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
"options": {}
}`

threadSolvesCollection := &models.Collection{}
if err := json.Unmarshal([]byte(threadSolvesData), &threadSolvesCollection); err != nil {
return err
}

if err := daos.New(db).SaveCollection(threadSolvesCollection); err != nil {
return err
}

leaderboardData := `{
"id": "i0vp31j3wwgak0u",
"created": "2024-10-31 03:41:35.465Z",
"updated": "2024-10-31 03:41:35.465Z",
"name": "leaderboard",
"type": "view",
"system": false,
"schema": [
{
"system": false,
"id": "pmjhypaj",
"name": "user_id",
"type": "text",
"required": true,
"presentable": false,
"unique": false,
"options": {
"min": 1,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "amvyvs1f",
"name": "count",
"type": "number",
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": 0,
"max": null,
"noDecimal": true
}
}
],
"indexes": [],
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
"options": {
"query": "SELECT\n id, user_id, count\nFROM threadSolves\nORDER BY count\n DESC\nLIMIT 10"
}
}`

leaderboardCollection := &models.Collection{}
if err := json.Unmarshal([]byte(leaderboardData), &leaderboardCollection); err != nil {
return err
}

return daos.New(db).SaveCollection(leaderboardCollection)
}, func(db dbx.Builder) error {
dao := daos.New(db)

leaderboardCollection, err := dao.FindCollectionByNameOrId("i0vp31j3wwgak0u")
if err != nil {
return err
}

if err := dao.DeleteCollection(leaderboardCollection); err != nil {
return err
}

threadSolvesCollection, err := dao.FindCollectionByNameOrId("tn4t8pzh448d674")
if err != nil {
return err
}

return dao.DeleteCollection(threadSolvesCollection)
})
}
28 changes: 16 additions & 12 deletions src/commands/thread/stats.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { build_embed, wrap_in_embed } from '../../utils/embed_helpers.js';
import { supabase } from '../../db/supabase';
import { pb } from '../../db/pocketbase';
import { command } from 'jellycommands';

export default command({
Expand Down Expand Up @@ -40,20 +40,23 @@ export default command({
interaction.options.getUser('user') ?? interaction.user
).id;

const { data, error } = await supabase
.from('thread_solves')
.select('count')
.eq('user_id', user_id)
.maybeSingle();
const data = await pb
.collection('threadSolves')
.getFirstListItem(
pb.filter('user_id = {:id}', {
id: interaction.user.id,
}),
)
.catch(() => null);

if (error) {
if (!data) {
await interaction.followUp('Something went wrong');
return;
}

await interaction.followUp(
wrap_in_embed(
data?.count
data.count
? // prettier-ignore
`<@${user_id}> has solved ${data.count} thread${data.count === 1 ? '' : 's'}. Thank you for your contribution.`
: `<@${user_id}> has not solved any threads yet.`,
Expand All @@ -63,11 +66,12 @@ export default command({
}

case 'server': {
const { data, error } = await supabase
.from('leaderboard')
.select('*');
const data = await pb
.collection('leaderboard')
.getFullList()
.catch(() => null);

if (error || !data?.length) {
if (!data) {
await interaction.followUp('Could not fetch data');
return;
}
Expand Down
9 changes: 9 additions & 0 deletions src/db/pocketbase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ interface TagsCollection extends BaseModel {
content: string;
}

interface ThreadSolvesCollection extends BaseModel {
user_id: string;
count: number;
}

type LeaderboardView = Pick<ThreadSolvesCollection, 'id' | 'user_id' | 'count'>;

interface TypedPocketbase extends Pocketbase {
collection(idOrName: 'tags'): RecordService<TagsCollection>;
collection(idOrName: 'threadSolves'): RecordService<ThreadSolvesCollection>;
collection(idOrName: 'leaderboard'): RecordService<LeaderboardView>;
}
8 changes: 2 additions & 6 deletions src/utils/threads.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import { GuildMember, Snowflake, ThreadChannel } from 'discord.js';
import { has_any_role_or_id } from './snowflake.js';
import { THREAD_ADMIN_IDS } from '../config.js';
import { supabase } from '../db/supabase';
import { pb } from '../db/pocketbase.js';
import { no_op } from './promise.js';

export async function increment_solve_count(id: Snowflake) {
const { error } = await supabase.rpc('increment_solve_count', {
solver_id: id,
});

if (error) throw new Error(error.message);
await pb.send(`/api/sdb/increment-solve-count/${id}`, {});
}

export async function check_autothread_permissions(
Expand Down

0 comments on commit caa1be6

Please sign in to comment.