feat: getMe on launch

This commit is contained in:
Zamitto
2024-10-21 15:01:43 -03:00
parent d801bad49e
commit df5f82d47f
5 changed files with 89 additions and 72 deletions

View File

@@ -1,80 +1,43 @@
import { registerEvent } from "../register-event";
import * as Sentry from "@sentry/electron/main";
import { HydraApi, logger } from "@main/services";
import { logger } from "@main/services";
import type { ProfileVisibility, UserDetails } from "@types";
import {
userAuthRepository,
userSubscriptionRepository,
} from "@main/repository";
import { userAuthRepository } from "@main/repository";
import { UserNotLoggedInError } from "@shared";
import { getUserData } from "@main/services/user/get-user-data";
const getMe = async (
_event: Electron.IpcMainInvokeEvent
): Promise<UserDetails | null> => {
return HydraApi.get<UserDetails>(`/profile/me`)
.then((me) => {
userAuthRepository.upsert(
{
id: 1,
displayName: me.displayName,
profileImageUrl: me.profileImageUrl,
backgroundImageUrl: me.backgroundImageUrl,
userId: me.id,
},
["id"]
);
if (me.subscription) {
userSubscriptionRepository.upsert(
{
id: 1,
subscriptionId: me.subscription?.id || "",
status: me.subscription?.status || "",
planId: me.subscription?.plan.id || "",
planName: me.subscription?.plan.name || "",
expiresAt: me.subscription?.expiresAt || null,
user: { id: 1 },
},
["id"]
);
} else {
userSubscriptionRepository.delete({ id: 1 });
}
Sentry.setUser({ id: me.id, username: me.username });
return me;
})
.catch(async (err) => {
if (err instanceof UserNotLoggedInError) {
return null;
}
logger.error("Failed to get logged user", err);
const loggedUser = await userAuthRepository.findOne({ where: { id: 1 } });
if (loggedUser) {
return {
...loggedUser,
id: loggedUser.userId,
username: "",
bio: "",
profileVisibility: "PUBLIC" as ProfileVisibility,
subscription: loggedUser.subscription
? {
id: loggedUser.subscription.subscriptionId,
status: loggedUser.subscription.status,
plan: {
id: loggedUser.subscription.planId,
name: loggedUser.subscription.planName,
},
expiresAt: loggedUser.subscription.expiresAt,
}
: null,
};
}
return getUserData().catch(async (err) => {
if (err instanceof UserNotLoggedInError) {
return null;
});
}
logger.error("Failed to get logged user", err);
const loggedUser = await userAuthRepository.findOne({ where: { id: 1 } });
if (loggedUser) {
return {
...loggedUser,
id: loggedUser.userId,
username: "",
bio: "",
profileVisibility: "PUBLIC" as ProfileVisibility,
subscription: loggedUser.subscription
? {
id: loggedUser.subscription.subscriptionId,
status: loggedUser.subscription.status,
plan: {
id: loggedUser.subscription.planId,
name: loggedUser.subscription.planName,
},
expiresAt: loggedUser.subscription.expiresAt,
}
: null,
};
}
return null;
});
};
registerEvent("getMe", getMe);