import { Connection } from 'mariadb'; import { getConnection } from './initDatabase'; import { defaultUserSettings } from '../config'; import { User } from '../user/types'; import redisClient from '../redis/init'; import MyRedisKeys from '../redis/keys'; interface StoreSettings { calendar_max_future_booking_days: number; calendar_min_earliest_booking_time: number; calendar_using_primary_calendar: boolean; } const storeSettingsKeys: (keyof StoreSettings)[] = ['calendar_max_future_booking_days', 'calendar_min_earliest_booking_time', 'calendar_using_primary_calendar']; type StoreID = string; interface Store { store_id: StoreID; owner_user_id: string; name: string; address: string; settings: StoreSettings; } async function getStore(store_id: string): Promise { try { //check if user is in redis let redisStore = await redisClient.get(MyRedisKeys.storeCache(store_id)); if (redisStore) { let store: Store = JSON.parse(redisStore); return store; } } catch (error) {} let conn: Connection | undefined; try { conn = await getConnection(); const rows = await conn.query('SELECT * FROM stores WHERE store_id = ?', [store_id]); if (rows.length != 1) throw new Error('invalid store_id, ' + store_id); const row = rows[0]; let _settings: any = {}; for (const key of storeSettingsKeys) { _settings[key] = row[key]; } let settings: StoreSettings = { ...defaultUserSettings }; for (const _key in settings) { const key = _key as keyof StoreSettings; if (_settings[key]) { (settings as any)[key] = _settings[key]; } } let store: Store = { store_id: row.store_id, owner_user_id: row.owner_user_id, name: row.name, address: row.address, settings, }; try { await redisClient.set(MyRedisKeys.storeCache(store_id), JSON.stringify(store), { EX: 1 * 60 }); } catch (error) { console.log(error); } return store; } catch (err) { console.log(err); throw err; } finally { if (conn) conn.end(); } } async function getStoreByUser(user: User): Promise { return await getStore(user.store_id); } async function getAllStoreIDs(): Promise { let conn: Connection | undefined; try { conn = await getConnection(); const rows = await conn.query('SELECT `store_id` FROM `stores`'); return rows.map((row: any) => row.store_id); } catch (err) { console.log(err); throw err; } finally { if (conn) conn.end(); } } export { getStore, Store, StoreSettings, getStoreByUser, getAllStoreIDs, storeSettingsKeys, StoreID }; /*CREATE TABLE `stores` ( `store_id` varchar(255) NOT NULL, `owner_user_id` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `calendar_max_future_booking_days` int(11) NOT NULL, `calendar_min_earliest_booking_time` int(11) NOT NULL, `calendar_primary_calendar_id` varchar(255) NOT NULL, `calendar_using_primary_calendar` tinyint(1) NOT NULL, `createdAt` datetime NOT NULL, `updatedAt` datetime NOT NULL )*/