Compare commits
10
Commits
898ae2dd56
...
e78dd0d833
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e78dd0d833 | ||
|
|
f9a35ee230 | ||
|
|
0eec0affbe | ||
|
|
ec9f27ee26 | ||
|
|
016eddcce7 | ||
|
|
03c5f73891 | ||
|
|
8ff46104f1 | ||
|
|
97442265ba | ||
|
|
b2cd402adc | ||
|
|
9c193c3530 |
@@ -1,112 +1,65 @@
|
||||
name: Deploy
|
||||
name: Build & Deploy (Nix)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
concurrency:
|
||||
group: deploy-production
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/booster-role
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
environment: orangevps
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
- uses: DeterminateSystems/nix-installer-action@v16
|
||||
with:
|
||||
bun-version: latest
|
||||
determinate: false
|
||||
extra-conf: |
|
||||
sandbox = false
|
||||
accept-flake-config = true
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
- name: Type check
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Run tests
|
||||
run: bun test
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Set lowercase image name
|
||||
run: echo "IMAGE_NAME=${IMAGE_NAME,,}" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v3
|
||||
- uses: DeterminateSystems/magic-nix-cache-action@v8
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
use-flakehub: false
|
||||
|
||||
- name: Build and push image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.IMAGE_NAME }}:latest
|
||||
${{ env.IMAGE_NAME }}:${{ github.sha }}
|
||||
|
||||
- name: Deploy on VPS
|
||||
uses: appleboy/ssh-action@v1.2.0
|
||||
- name: Build & Deploy
|
||||
env:
|
||||
IMAGE_NAME: ${{ env.IMAGE_NAME }}
|
||||
GHCR_USERNAME: ${{ github.actor }}
|
||||
GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}
|
||||
DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }}
|
||||
DISCORD_GUILD_ID: ${{ secrets.DISCORD_GUILD_ID }}
|
||||
DATABASE_URL: ${{ secrets.DATABASE_URL }}
|
||||
BOOSTER_ROLE_ANCHOR_ROLE_ID: ${{ secrets.BOOSTER_ROLE_ANCHOR_ROLE_ID }}
|
||||
BOOSTER_ELIGIBILITY_ROLE_ID: ${{ secrets.BOOSTER_ELIGIBILITY_ROLE_ID }}
|
||||
BOOSTER_GREETING_CHANNEL_ID: ${{ secrets.BOOSTER_GREETING_CHANNEL_ID }}
|
||||
LOG_LEVEL: ${{ secrets.LOG_LEVEL }}
|
||||
with:
|
||||
host: ${{ secrets.VPS_HOST }}
|
||||
username: ${{ secrets.VPS_USER }}
|
||||
key: ${{ secrets.VPS_SSH_KEY }}
|
||||
envs: IMAGE_NAME,GHCR_USERNAME,GHCR_TOKEN,DISCORD_TOKEN,DISCORD_CLIENT_ID,DISCORD_GUILD_ID,DATABASE_URL,BOOSTER_ROLE_ANCHOR_ROLE_ID,BOOSTER_ELIGIBILITY_ROLE_ID,BOOSTER_GREETING_CHANNEL_ID,LOG_LEVEL
|
||||
script: |
|
||||
VPS_HOST: ${{ secrets.VPS_HOST }}
|
||||
VPS_USER: ${{ secrets.VPS_USER }}
|
||||
VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
|
||||
run: |
|
||||
set -eu
|
||||
STORE_PATH=$(nix build . --impure --option sandbox false --no-link --print-out-paths | tail -1)
|
||||
echo "Store path: $STORE_PATH"
|
||||
|
||||
key_file=$(mktemp /tmp/deploy-key.XXXXXX)
|
||||
printf '%s\n' "$VPS_SSH_KEY" > "$key_file"
|
||||
chmod 600 "$key_file"
|
||||
sed -i 's/\r$//' "$key_file"
|
||||
ssh-keygen -y -f "$key_file" >/dev/null 2>&1 || { echo "SSH key invalid"; exit 1; }
|
||||
|
||||
export NIX_SSHOPTS="-i $key_file -o StrictHostKeyChecking=no"
|
||||
nix copy --to "ssh://${VPS_USER}@${VPS_HOST}" "$STORE_PATH" 2>&1
|
||||
|
||||
ssh -i "$key_file" -o StrictHostKeyChecking=no "${VPS_USER}@${VPS_HOST}" "
|
||||
set -eu
|
||||
mkdir -p /opt/booster-role
|
||||
cd /opt/booster-role
|
||||
|
||||
cat > .env <<EOF
|
||||
DISCORD_TOKEN=${DISCORD_TOKEN}
|
||||
DISCORD_CLIENT_ID=${DISCORD_CLIENT_ID}
|
||||
DISCORD_GUILD_ID=${DISCORD_GUILD_ID}
|
||||
DATABASE_URL=${DATABASE_URL:?DATABASE_URL is required}
|
||||
BOOSTER_ROLE_ANCHOR_ROLE_ID=${BOOSTER_ROLE_ANCHOR_ROLE_ID}
|
||||
BOOSTER_ELIGIBILITY_ROLE_ID=${BOOSTER_ELIGIBILITY_ROLE_ID:-1206431347925852162}
|
||||
BOOSTER_GREETING_CHANNEL_ID=${BOOSTER_GREETING_CHANNEL_ID}
|
||||
LOG_LEVEL=${LOG_LEVEL:-info}
|
||||
EOF
|
||||
|
||||
cat > docker-compose.yml <<EOF
|
||||
services:
|
||||
booster-role:
|
||||
image: ${IMAGE_NAME}:latest
|
||||
container_name: booster-role
|
||||
restart: unless-stopped
|
||||
env_file:
|
||||
- .env
|
||||
EOF
|
||||
|
||||
echo "$GHCR_TOKEN" | docker login ghcr.io -u "$GHCR_USERNAME" --password-stdin
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
docker image prune -f
|
||||
if [ -d /nix/var/nix/profiles/booster-role ] && [ ! -L /nix/var/nix/profiles/booster-role ]; then
|
||||
rm -rf /nix/var/nix/profiles/booster-role
|
||||
fi
|
||||
nix-env --profile /nix/var/nix/profiles/booster-role --set $STORE_PATH
|
||||
systemctl daemon-reload
|
||||
systemctl enable booster-role 2>/dev/null || true
|
||||
systemctl restart booster-role
|
||||
for i in \$(seq 1 30); do
|
||||
systemctl is-active --quiet booster-role && break
|
||||
sleep 1
|
||||
done
|
||||
systemctl is-active booster-role || {
|
||||
echo \"=== SERVICE FAILED — journal ===\"
|
||||
journalctl -u booster-role -n 40 --no-pager
|
||||
exit 1
|
||||
}
|
||||
systemctl status booster-role --no-pager 2>&1 | head -8
|
||||
" 2>&1
|
||||
|
||||
+5
-1
@@ -10,4 +10,8 @@ COPY src ./src
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
CMD ["bun", "run", "src/index.ts"]
|
||||
COPY src/db ./src/db
|
||||
COPY drizzle.config.ts ./
|
||||
RUN bun add -d drizzle-kit
|
||||
|
||||
CMD ["sh", "-c", "bun run db:migrate; bun run src/index.ts"]
|
||||
Generated
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"nodes": {
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1731533236,
|
||||
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1785301185,
|
||||
"narHash": "sha256-eoS3KQTO0aPWXZvIaRbRAzSSHW3l5wdMFXtT1ISfoKA=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "9bc02893134c733dd85de46ee4fb2fac696b5529",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixpkgs-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
description = "Booster Role Discord Bot (Nix build)";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, flake-utils }:
|
||||
flake-utils.lib.eachDefaultSystem (system:
|
||||
let
|
||||
pkgs = import nixpkgs { inherit system; };
|
||||
in
|
||||
{
|
||||
packages.default = pkgs.stdenvNoCC.mkDerivation {
|
||||
pname = "booster-role";
|
||||
version = "0.1.0";
|
||||
src = ./.;
|
||||
|
||||
nativeBuildInputs = [ pkgs.bun ];
|
||||
|
||||
buildPhase = ''
|
||||
export HOME="$TMPDIR"
|
||||
bun install --frozen-lockfile
|
||||
bun run typecheck
|
||||
bun test
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin $out/lib/booster-role
|
||||
cp -r package.json bun.lock tsconfig.json drizzle.config.ts $out/lib/booster-role/
|
||||
cp -r src $out/lib/booster-role/src
|
||||
cp -r node_modules $out/lib/booster-role/node_modules
|
||||
cat > $out/bin/booster-role << WRAPPER
|
||||
#!${pkgs.runtimeShell}
|
||||
cd $out/lib/booster-role
|
||||
export NODE_ENV=production
|
||||
${pkgs.bun}/bin/bun run db:migrate
|
||||
exec ${pkgs.bun}/bin/bun run src/index.ts
|
||||
WRAPPER
|
||||
chmod +x $out/bin/booster-role
|
||||
'';
|
||||
};
|
||||
|
||||
devShells.default = pkgs.mkShell {
|
||||
buildInputs = [ pkgs.bun ];
|
||||
};
|
||||
});
|
||||
}
|
||||
+18
-1
@@ -1,10 +1,12 @@
|
||||
import type { Client } from "discord.js";
|
||||
import type { AppConfig } from "../config";
|
||||
import { createDb } from "../db";
|
||||
import { logger } from "../logger";
|
||||
import { BoosterRoleService } from "../services/boosterRoleService";
|
||||
import { DrizzleBoosterRoleStore } from "../services/drizzleBoosterRoleStore";
|
||||
import { DiscordRoleRepository } from "../services/discordRoleRepository";
|
||||
import { handleGuildMemberUpdate } from "./events/guildMemberUpdate";
|
||||
import { sendBoostGreeting } from "./events/boostGreeting";
|
||||
import { handleInteraction } from "./interactionHandler";
|
||||
|
||||
export function attachBotHandlers(client: Client, config: AppConfig): void {
|
||||
@@ -26,13 +28,28 @@ export function attachBotHandlers(client: Client, config: AppConfig): void {
|
||||
});
|
||||
|
||||
client.on("guildMemberUpdate", async (oldMember, newMember) => {
|
||||
const eligibilityRoleId = config.boosterEligibilityRoleId;
|
||||
|
||||
// Detect boost gain: member just acquired the booster eligibility role
|
||||
const hadBooster = oldMember.roles.cache.has(eligibilityRoleId);
|
||||
const hasBooster = newMember.roles.cache.has(eligibilityRoleId);
|
||||
if (!hadBooster && hasBooster && config.boosterGreetingChannelId) {
|
||||
const channel = newMember.guild.channels.cache.get(config.boosterGreetingChannelId);
|
||||
if (channel && "send" in channel) {
|
||||
await sendBoostGreeting(channel as { send(input: { content: string }): Promise<unknown> }, newMember.id, config.boosterGreetingChannelId).catch((err) => {
|
||||
logger.error("Failed to send boost greeting", { error: String(err), userId: newMember.id });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Handle boost loss (existing behaviour)
|
||||
const service = new BoosterRoleService(
|
||||
store,
|
||||
new DiscordRoleRepository(newMember.guild),
|
||||
{ anchorPosition: resolveAnchorPosition(newMember.guild, config.boosterRoleAnchorRoleId) }
|
||||
);
|
||||
|
||||
await handleGuildMemberUpdate(oldMember, newMember, service, config.boosterEligibilityRoleId);
|
||||
await handleGuildMemberUpdate(oldMember, newMember, service, eligibilityRoleId);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { sendBoostGreeting } from "./boostGreeting";
|
||||
|
||||
describe("sendBoostGreeting", () => {
|
||||
test("sends boost greeting to the given channel", async () => {
|
||||
const sent: string[] = [];
|
||||
const channel = {
|
||||
send: async (input: { content: string }): Promise<void> => {
|
||||
sent.push(input.content);
|
||||
},
|
||||
};
|
||||
|
||||
await sendBoostGreeting(channel, "user-123", "channel-456");
|
||||
|
||||
expect(sent.length).toBe(1);
|
||||
expect(sent[0]).toContain("<@user-123>");
|
||||
expect(sent[0]).toContain("/booster-role claim");
|
||||
expect(sent[0]).toContain("di sini");
|
||||
});
|
||||
|
||||
test("handles different user and channel IDs", async () => {
|
||||
const sent: string[] = [];
|
||||
const channel = {
|
||||
send: async (input: { content: string }): Promise<void> => {
|
||||
sent.push(input.content);
|
||||
},
|
||||
};
|
||||
|
||||
await sendBoostGreeting(channel, "other-user", "other-channel");
|
||||
|
||||
expect(sent[0]).toContain("<@other-user>");
|
||||
expect(sent[0]).toContain("di sini");
|
||||
});
|
||||
});
|
||||
@@ -1,60 +1,31 @@
|
||||
import { logger } from "../../logger";
|
||||
|
||||
type GuildTextChannel = {
|
||||
send(input: { content: string }): Promise<unknown>;
|
||||
};
|
||||
|
||||
type GuildMember = {
|
||||
id: string;
|
||||
guild: {
|
||||
id: string;
|
||||
channels: {
|
||||
cache: {
|
||||
get(channelId: string): GuildTextChannel | undefined;
|
||||
};
|
||||
};
|
||||
};
|
||||
user?: { id: string };
|
||||
};
|
||||
const greetings = [
|
||||
(userId: string) =>
|
||||
`🎉 Makasih udah ngeboost <@${userId}>! Sekarang kamu bisa claim custom role pake \`/booster-role claim\` di sini.`,
|
||||
(userId: string) =>
|
||||
`🔥 <@${userId}> baru aja ngeboost! Langsung aja claim custom role kamu pake \`/booster-role claim\` di sini.`,
|
||||
(userId: string) =>
|
||||
`✨ Thank you <@${userId}> for the boost! Claim custom role kamu pake \`/booster-role claim\` di sini ya.`,
|
||||
(userId: string) =>
|
||||
`👑 <@${userId}> ngeboost server! Yuk langsung claim custom role pake \`/booster-role claim\` di sini.`,
|
||||
(userId: string) =>
|
||||
`🎊 Ada booster baru nih, <@${userId}>! Jangan lupa claim custom role kamu pake \`/booster-role claim\` di sini.`,
|
||||
];
|
||||
|
||||
/**
|
||||
* Sends a welcome message to the configured greeting channel when a member
|
||||
* newly acquires the booster eligibility role (i.e. just boosted the server).
|
||||
*
|
||||
* Only fires on a *gain* transition (hadBoosterRole = false → hasBoosterRole = true).
|
||||
*/
|
||||
export function handleBoostGreeting(
|
||||
oldMember: GuildMember,
|
||||
newMember: GuildMember,
|
||||
greetingChannelId: string | null,
|
||||
): void {
|
||||
if (!greetingChannelId) return;
|
||||
|
||||
const hadBoosterRole = oldMember.roles.cache.has(/** @type {any} */ (null) as any);
|
||||
// Actually detect the gain: we need the actual role ID. The caller should pass it.
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a welcome message when a member newly acquires the booster eligibility role.
|
||||
* Must be called with the booster eligibility role ID to check correctly.
|
||||
* Sends a random welcome message via the given channel when a member newly
|
||||
* acquires the booster eligibility role (i.e. just boosted the server).
|
||||
*/
|
||||
export async function sendBoostGreeting(
|
||||
member: { id: string; guild: { id: string; channels: { cache: { get(channelId: string): { send(input: { content: string }): Promise<unknown> } | undefined } } } },
|
||||
channel: { send(input: { content: string }): Promise<unknown> },
|
||||
userId: string,
|
||||
greetingChannelId: string,
|
||||
): Promise<void> {
|
||||
const channel = member.guild.channels.cache.get(greetingChannelId);
|
||||
if (!channel) {
|
||||
logger.warn("Boost greeting channel not found", { channelId: greetingChannelId, guildId: member.guild.id });
|
||||
return;
|
||||
}
|
||||
const pick = Math.floor(Math.random() * greetings.length);
|
||||
const message = greetings[pick](userId);
|
||||
|
||||
await channel.send({
|
||||
content: `🎉 Thank you for boosting <@${member.user?.id ?? member.id}>! You can now claim a custom role using \`/booster-role claim\` in <#${greetingChannelId}>.`
|
||||
});
|
||||
await channel.send({ content: message });
|
||||
|
||||
logger.info("Boost greeting sent", {
|
||||
userId: member.user?.id ?? member.id,
|
||||
guildId: member.guild.id,
|
||||
channelId: greetingChannelId,
|
||||
});
|
||||
logger.info("Boost greeting sent", { userId, channelId: greetingChannelId, variant: pick });
|
||||
}
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ const store = new DrizzleBoosterRoleStore(db);
|
||||
client.once("clientReady", () => {
|
||||
logger.info("Discord client ready", { bot: client.user?.tag ?? "unknown bot" });
|
||||
|
||||
// Start periodic cleanup for boost ends missed during downtime
|
||||
// Start periodic cleanup for boost ends missed during downtime
|
||||
startBoostCleanup(
|
||||
client,
|
||||
store,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { startBoostCleanup } from "./boostCleanupService";
|
||||
import type { BoosterRoleRecord } from "./drizzleBoosterRoleStore";
|
||||
import type { BoosterRoleRecord, BoosterRoleUpdate } from "./drizzleBoosterRoleStore";
|
||||
import type { RoleRepository } from "./discordRoleRepository";
|
||||
|
||||
class MemoryStore {
|
||||
@@ -18,6 +18,13 @@ class MemoryStore {
|
||||
this.records.set(`${record.guildId}:${record.userId}`, record);
|
||||
}
|
||||
|
||||
async update(guildId: string, userId: string, changes: BoosterRoleUpdate) {
|
||||
const key = `${guildId}:${userId}`;
|
||||
const record = this.records.get(key);
|
||||
if (!record) return;
|
||||
this.records.set(key, { ...record, ...changes });
|
||||
}
|
||||
|
||||
async delete(guildId: string, userId: string) {
|
||||
this.records.delete(`${guildId}:${userId}`);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { BoosterRoleService } from "./boosterRoleService";
|
||||
import type { BoosterRoleRecord } from "./drizzleBoosterRoleStore";
|
||||
import type { BoosterRoleRecord, BoosterRoleUpdate } from "./drizzleBoosterRoleStore";
|
||||
import type { RoleRepository } from "./discordRoleRepository";
|
||||
|
||||
class MemoryRoleStore {
|
||||
@@ -18,6 +18,13 @@ class MemoryRoleStore {
|
||||
this.records.set(`${record.guildId}:${record.userId}`, record);
|
||||
}
|
||||
|
||||
async update(guildId: string, userId: string, changes: BoosterRoleUpdate): Promise<void> {
|
||||
const key = `${guildId}:${userId}`;
|
||||
const record = this.records.get(key);
|
||||
if (!record) return;
|
||||
this.records.set(key, { ...record, ...changes });
|
||||
}
|
||||
|
||||
async delete(guildId: string, userId: string): Promise<void> {
|
||||
this.records.delete(`${guildId}:${userId}`);
|
||||
}
|
||||
@@ -115,6 +122,7 @@ describe("BoosterRoleService", () => {
|
||||
await service.renameRole({ guildId: "guild", userId: "user", name: "Renamed" });
|
||||
|
||||
expect(roles.roles.get(claimed.roleId)?.name).toBe("Renamed");
|
||||
expect(await store.findByUser("guild", "user")).toEqual(expect.objectContaining({ name: "Renamed" }));
|
||||
await expect(service.renameRole({ guildId: "guild", userId: "attacker", name: "Stolen" })).rejects.toThrow("No booster role found");
|
||||
});
|
||||
|
||||
@@ -127,6 +135,7 @@ describe("BoosterRoleService", () => {
|
||||
await service.setRoleIcon({ guildId: "guild", userId: "user", icon: { contentType: "image/png", size: 128_000, dataUri: "data:image/png;base64,abc" } });
|
||||
|
||||
expect(roles.roles.get(claimed.roleId)?.icon).toBe("data:image/png;base64,abc");
|
||||
expect(await store.findByUser("guild", "user")).toEqual(expect.objectContaining({ icon: "data:image/png;base64,abc" }));
|
||||
await expect(service.setRoleIcon({ guildId: "guild", userId: "attacker", icon: { contentType: "image/png", size: 128_000, dataUri: "data:image/png;base64,abc" } })).rejects.toThrow("No booster role found");
|
||||
});
|
||||
|
||||
@@ -175,6 +184,7 @@ describe("BoosterRoleService", () => {
|
||||
const updated = roles.getRole(claimed.roleId);
|
||||
expect(updated).not.toBeNull();
|
||||
expect(updated!.colors).toEqual({ primaryColor: "#FF0000" });
|
||||
expect(await store.findByUser("guild", "user")).toEqual(expect.objectContaining({ color: "#FF0000", color2: null }));
|
||||
|
||||
// Other user cannot recolor
|
||||
await expect(service.recolorRole({ guildId: "guild", userId: "attacker", color: "#00FF00" })).rejects.toThrow("No booster role found");
|
||||
@@ -191,6 +201,7 @@ describe("BoosterRoleService", () => {
|
||||
const updated = roles.getRole(claimed.roleId);
|
||||
expect(updated).not.toBeNull();
|
||||
expect(updated!.colors).toEqual({ primaryColor: "#FF0000", secondaryColor: "#0000FF" });
|
||||
expect(await store.findByUser("guild", "user")).toEqual(expect.objectContaining({ color: "#FF0000", color2: "#0000FF" }));
|
||||
});
|
||||
|
||||
test("deletes the stored role owned by the user", async () => {
|
||||
|
||||
@@ -108,6 +108,7 @@ export class BoosterRoleService {
|
||||
const name = validateRoleName(input.name);
|
||||
assertRoleNameIsAvailable(name, (await this.roles.listRoles()).filter((role) => role.id !== record.roleId));
|
||||
await this.roles.updateRole(record.roleId, { name });
|
||||
await this.store.update(guildId, userId, { name, updatedAt: this.now() });
|
||||
}
|
||||
|
||||
async recolorRole(input: { guildId: string; userId: string; color: string; color2?: string | null }): Promise<void> {
|
||||
@@ -118,6 +119,7 @@ export class BoosterRoleService {
|
||||
const secondaryColor = normalizeOptionalHexColor(color2 ?? null);
|
||||
const colors = resolveGradientColors(primaryColor, secondaryColor);
|
||||
await this.roles.updateRole(record.roleId, { colors });
|
||||
await this.store.update(guildId, userId, { color: primaryColor, color2: secondaryColor, updatedAt: this.now() });
|
||||
}
|
||||
|
||||
async setRoleIcon(input: { guildId: string; userId: string; icon: RoleIcon }): Promise<void> {
|
||||
@@ -126,6 +128,7 @@ export class BoosterRoleService {
|
||||
assertCanManageStoredRole(this.identity(record), { guildId, userId, roleId: record.roleId });
|
||||
this.validateRoleIcon(icon);
|
||||
await this.roles.updateRole(record.roleId, { icon: icon.dataUri });
|
||||
await this.store.update(guildId, userId, { icon: icon.dataUri, updatedAt: this.now() });
|
||||
}
|
||||
|
||||
async deleteRole(input: { guildId: string; userId: string }): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { DrizzleBoosterRoleStore, type BoosterRoleRecord, type BoosterRoleUpdate } from "./drizzleBoosterRoleStore";
|
||||
|
||||
class FakeDb {
|
||||
rows: BoosterRoleRecord[] = [];
|
||||
lastUpdate: { changes: BoosterRoleUpdate; condition: unknown } | null = null;
|
||||
|
||||
select() {
|
||||
return {
|
||||
from: () => ({
|
||||
where: () => Object.assign(Promise.resolve(this.rows), {
|
||||
limit: (count: number) => Promise.resolve(this.rows.slice(0, count))
|
||||
})
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
insert() {
|
||||
return {
|
||||
values: (record: BoosterRoleRecord) => {
|
||||
this.rows.push(record);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
update() {
|
||||
return {
|
||||
set: (changes: BoosterRoleUpdate) => ({
|
||||
where: (condition: unknown) => {
|
||||
this.lastUpdate = { changes, condition };
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
delete() {
|
||||
return {
|
||||
where: () => {}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
describe("DrizzleBoosterRoleStore", () => {
|
||||
test("persists metadata updates for a stored booster role", async () => {
|
||||
const db = new FakeDb();
|
||||
const store = new DrizzleBoosterRoleStore(db);
|
||||
|
||||
await store.update("guild", "user", { name: "Renamed", color: "#AABBCC", updatedAt: 123 });
|
||||
|
||||
expect(db.lastUpdate?.changes).toEqual({ name: "Renamed", color: "#AABBCC", updatedAt: 123 });
|
||||
expect(db.lastUpdate?.condition).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -13,10 +13,13 @@ export type BoosterRoleRecord = {
|
||||
updatedAt: number;
|
||||
};
|
||||
|
||||
export type BoosterRoleUpdate = Partial<Pick<BoosterRoleRecord, "name" | "color" | "color2" | "icon" | "updatedAt">>;
|
||||
|
||||
export type BoosterRoleStore = {
|
||||
findByUser(guildId: string, userId: string): Promise<BoosterRoleRecord | null>;
|
||||
findByGuild(guildId: string): Promise<BoosterRoleRecord[]>;
|
||||
create(record: BoosterRoleRecord): Promise<void>;
|
||||
update(guildId: string, userId: string, changes: BoosterRoleUpdate): Promise<void>;
|
||||
delete(guildId: string, userId: string): Promise<void>;
|
||||
};
|
||||
|
||||
@@ -35,6 +38,11 @@ type DatabaseLike = {
|
||||
insert(table: typeof boosterRoles): {
|
||||
values(record: BoosterRoleRecord): Promise<unknown> | unknown;
|
||||
};
|
||||
update(table: typeof boosterRoles): {
|
||||
set(changes: BoosterRoleUpdate): {
|
||||
where(condition: unknown): Promise<unknown> | unknown;
|
||||
};
|
||||
};
|
||||
delete(table: typeof boosterRoles): {
|
||||
where(condition: unknown): Promise<unknown> | unknown;
|
||||
};
|
||||
@@ -64,6 +72,13 @@ export class DrizzleBoosterRoleStore implements BoosterRoleStore {
|
||||
await this.db.insert(boosterRoles).values(record);
|
||||
}
|
||||
|
||||
async update(guildId: string, userId: string, changes: BoosterRoleUpdate): Promise<void> {
|
||||
await this.db
|
||||
.update(boosterRoles)
|
||||
.set(changes)
|
||||
.where(and(eq(boosterRoles.guildId, guildId), eq(boosterRoles.userId, userId)));
|
||||
}
|
||||
|
||||
async delete(guildId: string, userId: string): Promise<void> {
|
||||
await this.db
|
||||
.delete(boosterRoles)
|
||||
|
||||
Reference in New Issue
Block a user