Skip to content

Commit

Permalink
⚡️ perf: improve getUserState api performance (lobehub#5076)
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx authored Dec 19, 2024
1 parent ee88732 commit f16a233
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
10 changes: 10 additions & 0 deletions src/database/server/models/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,16 @@ export class MessageModel {
return result[0].count;
};

hasMoreThanN = async (n: number): Promise<boolean> => {
const result = await this.db
.select({ id: messages.id })
.from(messages)
.where(eq(messages.userId, this.userId))
.limit(n + 1);

return result.length > n;
};

// **************** Create *************** //

create = async (
Expand Down
10 changes: 10 additions & 0 deletions src/database/server/models/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ export class SessionModel {
return result[0].count;
};

hasMoreThanN = async (n: number): Promise<boolean> => {
const result = await this.db
.select({ id: sessions.id })
.from(sessions)
.where(eq(sessions.userId, this.userId))
.limit(n + 1);

return result.length > n;
};

// **************** Create *************** //

create = async ({
Expand Down
11 changes: 6 additions & 5 deletions src/server/routers/lambda/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,17 @@ export const userRouter = router({
}

const messageModel = new MessageModel(serverDB, ctx.userId);
const messageCount = await messageModel.count();
const hasMoreThan4Messages = await messageModel.hasMoreThanN(4);

const sessionModel = new SessionModel(serverDB, ctx.userId);
const sessionCount = await sessionModel.count();
const hasAnyMessages = await messageModel.hasMoreThanN(0);
const hasExtraSession = await sessionModel.hasMoreThanN(1);

return {
canEnablePWAGuide: messageCount >= 4,
canEnableTrace: messageCount >= 4,
canEnablePWAGuide: hasMoreThan4Messages,
canEnableTrace: hasMoreThan4Messages,
// 有消息,或者创建过助手,则认为有 conversation
hasConversation: messageCount > 0 || sessionCount > 1,
hasConversation: hasAnyMessages || hasExtraSession,

// always return true for community version
isOnboard: state.isOnboarded || true,
Expand Down

0 comments on commit f16a233

Please sign in to comment.