MoonMiners/src/utils/helpers.ts
Joseph Ferano 9b753cf103 Porting database from SQLite to PostgreSQL
- New Postgres table schemas
- Using Stored Procedures with transactions that validate business logic
- User Ids now use UUID
- Updated and simplified all endpoints to call the stored procedures

Notes: There are still a few things missing that broke because of the migration,
in particular, because we moved a lot of the business logic into the database,
we now require that certain data that lived in the game-config.json to be
present in the database as well, to prevent cheating and truly have a single
source of truth.
2023-03-30 14:13:30 +07:00

79 lines
2.3 KiB
TypeScript

import { TimeDuration } from "typings";
import crypto from 'crypto';
export function getObjectFromArray<T>(array: T[], key: keyof T, value: any): T | undefined {
return array.find(obj => obj[key] === value);
}
export function pushElementToArray<T>(array: T[], element: T): T[] {
const newArray = [...array]; // create a new array
newArray.push(element); // add the new element to the array
return newArray; // return the new array
}
export function sumValues<T extends Record<K, number>, K extends keyof T>(array: T[], key: K): number {
return array.reduce((acc, obj) => acc + obj[key], 0);
}
interface IMapping {
[key: string]: any
}
export function resourceToBg(resourceName: string): string {
const mapping: IMapping = {
"Sollux": "from-teal-800 to-teal-900",
"Shadowstone": "from-cyan-800 to-cyan-900",
"Azurium": "from-purple-800 to-purple-900",
"Novafor": "from-rose-800 to-rose-900",
"Nebulance": "from-rose-800 to-rose-900"
}
return mapping[resourceName]
}
export function resourceToFc(resourceName: string): string {
const mapping: IMapping = {
"Sollux": "text-teal-400",
"Shadowstone": "text-cyan-400",
"Azurium": "text-purple-300",
"Novafor": "text-rose-300",
"Nebulance": "text-rose-300"
}
return mapping[resourceName]
}
export function checkIfValidUUID(uuid: string): bool {
const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
return regexExp.test(uuid);
}
export function notificationTypeToBg(type: string): string {
const mapping: IMapping = {
"Error": "bg-red-600",
"Success": "bg-green-600",
}
return mapping[type]
}
export const calculateRemainingTime = (startTime: string, durationInMins: number) => {
const start = new Date(startTime);
const end = new Date(start.getTime() + durationInMins * 60000);
const remaining = end.getTime() - Date.now();
return remaining;
};
export const generateRandomBase64String = (length: number) => {
// Create a random byte array of the desired length.
const byteArray = new Uint8Array(length);
crypto.getRandomValues(byteArray);
// Convert the byte array to a base64 string.
const base64String = btoa(String.fromCharCode(...byteArray));
return base64String;
}