chore(release): 0.1.1
[risinglegends.git] / src / server / monster.ts
1 import { db } from './lib/db';
2 import { Fight, Monster, MonsterWithFaction } from '../shared/monsters';
3 import { TimePeriod, TimeManager } from '../shared/time';
4
5 const time = new TimeManager();
6
7 /**
8  * return a list of monsters that
9  * - are at the current location
10  * - in the current time period
11  * - in any time period
12  */
13 export async function getMonsterList(location_id: number, timePeriod: TimePeriod[] = []): Promise<Monster[]> {
14   if(timePeriod.length === 0) {
15     timePeriod.push('any');
16     timePeriod.push(time.getTimePeriod());
17   }
18
19   const res: Monster[] = await db.select('*')
20                       .where({ location_id })
21                       .whereIn('time_period', timePeriod)
22                       .from<Monster>('monsters')
23                       .orderBy('level');
24
25   return res;
26 }
27
28 export async function loadMonster(id: number): Promise<Monster> {
29   return db.select('*').from<Monster>('monsters').where({
30     id
31   }).first();
32 }
33
34 export async function loadMonsterFromFight(authToken: string): Promise<Fight> {
35   return await db.first().select('*').from<Fight>('fight').where({
36     player_id: authToken,
37   });
38 }
39
40 export async function loadMonsterWithFaction(authToken: string): Promise<MonsterWithFaction> {
41   const res = await db.raw(`
42                       select 
43                         f.*, fa.id as faction_id, fa.name as faction_name
44                       from fight f
45                       join monsters m on f.ref_id = m.id
46                       left outer join factions fa on m.faction_id = fa.id
47                       where f.player_id = ?
48                         limit 1
49                       `, [authToken]);
50
51   return res.rows[0];
52 }
53
54 export async function saveFightState(authToken: string, monster: Fight) {
55   return db('fight').where({
56     player_id: authToken,
57     id: monster.id
58   }).update<Fight>({
59     hp: monster.hp
60   });
61 }
62
63 export async function createFight(playerId: string, monster: Monster): Promise<Fight> {
64   const res = await db('fight').insert({
65     player_id: playerId,
66     name: monster.name,
67     strength: monster.strength,
68     constitution: monster.constitution,
69     dexterity: monster.dexterity,
70     intelligence: monster.intelligence,
71     exp: monster.exp,
72     level: monster.level,
73     gold: monster.gold,
74     hp: monster.hp,
75     helmAp: monster.helmAp,
76     chestAp: monster.chestAp,
77     legsAp: monster.legsAp,
78     armsAp: monster.armsAp,
79     maxHp: monster.maxHp,
80     ref_id: monster.id
81   }).returning<Fight[]>('*');
82
83   return res.pop();
84 }
85
86 export async function clearFight(authToken: string) {
87   return db('fight').where({
88     player_id: authToken
89   }).delete();
90 }