Create effects concept #402
2 changed files with 58 additions and 0 deletions
|
@ -1,5 +1,6 @@
|
|||
import {Column, Entity} from "typeorm";
|
||||
import AppBaseEntity from "../../../contracts/AppBaseEntity";
|
||||
import AppDataSource from "../../dataSources/appDataSource";
|
||||
|
||||
@Entity()
|
||||
export default class UserEffect extends AppBaseEntity {
|
||||
|
@ -48,4 +49,12 @@ export default class UserEffect extends AppBaseEntity {
|
|||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
49
src/helpers/EffectHelper.ts
Normal file
49
src/helpers/EffectHelper.ts
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue