Create EffectHelper class

This commit is contained in:
Ethan Lane 2024-10-26 21:38:23 +01:00
parent 3d8745dc0f
commit 17d89d4a44
2 changed files with 58 additions and 0 deletions

View file

@ -1,5 +1,6 @@
import {Column, Entity} from "typeorm"; import {Column, Entity} from "typeorm";
import AppBaseEntity from "../../../contracts/AppBaseEntity"; import AppBaseEntity from "../../../contracts/AppBaseEntity";
import AppDataSource from "../../dataSources/appDataSource";
@Entity() @Entity()
export default class UserEffect extends AppBaseEntity { export default class UserEffect extends AppBaseEntity {
@ -48,4 +49,12 @@ export default class UserEffect extends AppBaseEntity {
return false; return false;
} }
public static async FetchOneByUserIdAndName(userId: string, name: string): Promise<UserEffect | null> {
const repository = AppDataSource.getRepository(UserEffect);
const single = await repository.findOne({ where: { UserId: userId, Name: name } });
return single;
}
} }

View file

@ -0,0 +1,49 @@
import UserEffect from "../database/entities/app/UserEffect";
export default class EffectHelper {
public static async AddEffectToUserInventory(userId: string, name: string, quantity: number = 1) {
let effect = await UserEffect.FetchOneByUserIdAndName(userId, name);
if (!effect) {
effect = new UserEffect(name, userId, quantity);
} else {
effect.AddUnused(quantity);
}
await effect.Save(UserEffect, effect);
}
public static async UseEffect(userId: string, name: string, whenExpires: Date): Promise<boolean> {
const effect = await UserEffect.FetchOneByUserIdAndName(userId, name);
const now = new Date();
if (!effect || effect.Unused == 0) {
return false;
}
if (effect.WhenExpires && now < effect.WhenExpires) {
return false;
}
effect.UseEffect(whenExpires);
await effect.Save(UserEffect, effect);
return true;
}
public static async HasEffect(userId: string, name: string): Promise<boolean> {
const effect = await UserEffect.FetchOneByUserIdAndName(userId, name);
const now = new Date();
if (!effect || !effect.WhenExpires) {
return false;
}
if (now > effect.WhenExpires) {
return false;
}
return true;
}
}