chore(release): 0.2.5
[risinglegends.git] / src / server / items.ts
1 import { db } from './lib/db';
2 import {Item, PlayerItem, ShopItem} from '../shared/items';
3
4 export async function getShopItems(location_id: number): Promise<(ShopItem & Item)[]> {
5   const res = await db.raw(`select si.*, i.* from shop_items si
6     join items i on si.item_id = i.id where si.location_id = ?`, [location_id]);
7
8   return res.rows as (ShopItem & Item)[];
9 }
10
11 export async function getItemFromShop(item_id: number, location_id: number): Promise<ShopItem & Item> {
12   const res = await db.raw(`select si.*, i.* from shop_items si
13     join items i on si.item_id = i.id where si.location_id = ? and item_id = ?`, [location_id, item_id]);
14
15   if(res.rows.length === 1) {
16     return res.rows[0] as (ShopItem & Item);
17   }
18 }
19
20 export async function givePlayerItem(player_id: string, item_id: number, amount: number = 1) {
21   const res = await db.raw(`insert into player_items (item_id, player_id, amount) 
22       values (?, ?, ?) 
23       on conflict(item_id, player_id) 
24       do update set amount = player_items.amount + ? returning *`, [item_id, player_id, amount, amount]);
25
26   return res.rows[0] as {item_id: number, player_id: string, amount: number};
27 }
28
29 export async function getPlayersItems(player_id: string): Promise<PlayerItem[]> {
30   const res = await db.raw(`select pi.*, i.* from player_items pi 
31 join items i on pi.item_id = i.id where pi.player_id = ? and amount > 0`, [player_id]);
32   return res.rows as PlayerItem[];
33 }
34
35 export async function getItemFromPlayer(player_id: string, item_id: number): Promise<PlayerItem | undefined> {
36   const res = await db.raw(`select pi.*, i.* from player_items pi 
37 join items i on pi.item_id = i.id where pi.player_id = ? and pi.item_id = ?`, [player_id, item_id]);
38   if(res.rows.length === 1) {
39     return res.rows[0] as PlayerItem;
40   }
41 }
42
43 export async function updateItemCount(player_id: string, item_id: number, delta: number): Promise<number> {
44   const rows = await db('player_items').increment('amount', delta).where({
45     player_id,
46     item_id
47   }).returning('*');
48
49   return rows[0].amount;
50 }