86 lines
2.1 KiB
TypeScript
86 lines
2.1 KiB
TypeScript
import { mutation, query } from "./_generated/server";
|
|
import { v } from "convex/values";
|
|
import { getAuthUserId } from "@convex-dev/auth/server";
|
|
|
|
export const getCurrent = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx);
|
|
if (!userId) return null;
|
|
return await ctx.db.get(userId);
|
|
},
|
|
});
|
|
|
|
export const getCurrentProfile = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx);
|
|
if (!userId) return null;
|
|
const user = await ctx.db.get(userId);
|
|
if (!user) return null;
|
|
const accounts = await ctx.db
|
|
.query("authAccounts")
|
|
.withIndex("userIdAndProvider", (q) => q.eq("userId", userId))
|
|
.collect();
|
|
return { user, accounts };
|
|
},
|
|
});
|
|
|
|
export const touch = mutation({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx);
|
|
if (!userId) return null;
|
|
|
|
const today = new Date().toISOString().slice(0, 10);
|
|
const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000)
|
|
.toISOString()
|
|
.slice(0, 10);
|
|
|
|
const existing = await ctx.db
|
|
.query("userActivity")
|
|
.withIndex("by_user", (q) => q.eq("userId", userId))
|
|
.first();
|
|
|
|
if (!existing) {
|
|
await ctx.db.insert("userActivity", {
|
|
userId,
|
|
lastActiveDate: today,
|
|
streak: 1,
|
|
updatedAt: Date.now(),
|
|
});
|
|
return { lastActiveDate: today, streak: 1 };
|
|
}
|
|
|
|
if (existing.lastActiveDate === today) {
|
|
return { lastActiveDate: existing.lastActiveDate, streak: existing.streak };
|
|
}
|
|
|
|
const streak =
|
|
existing.lastActiveDate === yesterday ? existing.streak + 1 : 1;
|
|
|
|
await ctx.db.patch(existing._id, {
|
|
lastActiveDate: today,
|
|
streak,
|
|
updatedAt: Date.now(),
|
|
});
|
|
|
|
return { lastActiveDate: today, streak };
|
|
},
|
|
});
|
|
|
|
export const getActivity = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx);
|
|
if (!userId) return null;
|
|
|
|
const activity = await ctx.db
|
|
.query("userActivity")
|
|
.withIndex("by_user", (q) => q.eq("userId", userId))
|
|
.first();
|
|
|
|
return activity ?? null;
|
|
},
|
|
});
|