Skip to content

Commit

Permalink
Merge pull request #3 from ledouxm/feat/change-orm
Browse files Browse the repository at this point in the history
Feat/change orm
  • Loading branch information
ledouxm authored Jan 31, 2022
2 parents de3add1 + 28df060 commit 8aa0db8
Show file tree
Hide file tree
Showing 55 changed files with 1,669 additions and 661 deletions.
13 changes: 13 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1,2 +1,15 @@
PORT = 3002
HTTPS = TRUE

TYPEORM_CONNECTION = sqlite
TYPEORM_HOST = localhost
TYPEORM_USERNAME = root
TYPEORM_PASSWORD = admin
TYPEORM_DATABASE = database/lol-stalker.db
TYPEORM_PORT = 3000
TYPEORM_SYNCHRONIZE = false
TYPEORM_ENTITIES = **/entities/*.js
TYPEORM_MIGRATIONS_DIR = migration
TYPEORM_MIGRATIONS = migration/*.js

TYPEORM_LOGGING = true
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ yarn-error.log*
*.tgz

*.db-journal
lol-stalker.db.dev
*/prismaClient
database/**

selectedFriends.json
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
Clone this repo and install all dependencies
`yarn` or `npm install`

## First start

`yarn init:db`

## Development

`yarn dev` or `npm run dev`
Expand Down
Binary file added base.db
Binary file not shown.
Binary file added database/lol-stalker.db
Binary file not shown.
34 changes: 27 additions & 7 deletions electron/LCU/lcu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { pick } from "@pastable/core";
import axios, { AxiosInstance } from "axios";
import https from "https";
import LCUConnector from "lcu-connector";
import { Prisma } from "../prismaClient";
import { Friend } from "../entities/Friend";
import { sendInvalidate } from "../routes";
import { addOrUpdateFriends } from "../routes/friends";
import { sendToClient } from "../utils";
import { sendToClient, Tier } from "../utils";
import { CurrentSummoner, FriendDto, MatchDto, Queue, RankedStats } from "./types";

const httpsAgent = new https.Agent({ rejectUnauthorized: false });
Expand Down Expand Up @@ -45,6 +45,7 @@ const theoPuuid = "4ab5d4e7-0e24-54ac-b8e7-2a72c8483712";
const getTheoSoloQRank = () => getSoloQRankedStats(theoPuuid);
export interface FriendChange extends FriendStats {
oldFriend: FriendStats;
toNotify: boolean;
}
export const compareFriends = (oldFriends: FriendStats[], newFriends: FriendStats[]) => {
const changes: FriendChange[] = [];
Expand All @@ -56,15 +57,15 @@ export const compareFriends = (oldFriends: FriendStats[], newFriends: FriendStat
newFriend.tier !== oldFriend.tier ||
newFriend.leaguePoints !== oldFriend.leaguePoints
) {
changes.push({ ...newFriend, oldFriend });
changes.push({ ...newFriend, oldFriend, toNotify: !!oldFriend.division });
}
});

return changes;
};

type FriendStats = Pick<Prisma.FriendCreateInput, "name" | "puuid"> &
Pick<Queue, "division" | "tier" | "leaguePoints" | "wins" | "losses">;
type FriendStats = Pick<Friend, "name" | "puuid"> &
Pick<Queue, "division" | "tier" | "leaguePoints" | "wins" | "losses" | "miniSeriesProgress">;

export const checkFriendList = async () => {
const friends = await getFriends();
Expand All @@ -73,6 +74,18 @@ export const checkFriendList = async () => {
return stats;
};

export const getAllApexLeague = async () => {
const tiers: Tier[] = ["MASTER", "GRANDMASTER", "CHALLENGER"];
const payload: Partial<Record<Tier, number>> = {};
for (const tier of tiers) {
payload[tier] = (await getApexLeague(tier)).divisions[0].standings[0].leaguePoints;
}

return payload;
};
export const getApexLeague = (tier: RankedStats["queues"][0]["tier"]) =>
request<any>(`/lol-ranked/v1/apex-leagues/RANKED_SOLO_5x5/${tier}`);

///lol-ranked-stats/v1/stats/{summonerId}
export const getHelp = () => request("/help?format=Console");
export const getBuild = () => request("/system/v1/builds");
Expand All @@ -92,7 +105,7 @@ export const getSoloQRankedStats = async (puuid: string) =>
export const getMatchHistoryBySummonerPuuid = (puuid: string) =>
request<MatchDto>(`/lol-match-history/v1/products/lol/${puuid}/matches`);
export const getMultipleSummonerSoloQStats = async (
summoners: Pick<Prisma.FriendCreateInput, "puuid" | "name">[]
summoners: Pick<Friend, "puuid" | "name">[]
) => {
const summonersRanks = [];
for (const summoner of summoners) {
Expand All @@ -102,7 +115,14 @@ export const getMultipleSummonerSoloQStats = async (
throw "no rank";
}
summonersRanks.push({
...pick(rank, ["division", "tier", "leaguePoints", "wins", "losses"]),
...pick(rank, [
"division",
"tier",
"leaguePoints",
"wins",
"losses",
"miniSeriesProgress",
]),
...pick(summoner, ["name", "puuid"]),
});
} catch (e) {
Expand Down
5 changes: 3 additions & 2 deletions electron/LCU/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Prisma } from "../prismaClient";
export interface FriendDto extends Prisma.FriendCreateInput {
import { Friend } from "../entities/Friend";

export interface FriendDto extends Friend {
availability: string;
displayGroupId: number;
displayGroupName: string;
Expand Down
22 changes: 11 additions & 11 deletions electron/db.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import isDev from "electron-is-dev";
import path from "path";
import sqlite3 from "sqlite3";
import { PrismaClient } from "./prismaClient";
const dbUrl = isDev ? "lol-stalker.db.dev" : "lol-stalker.db";

export const db = new sqlite3.Database(dbUrl);
import { createConnection } from "typeorm";
const dbUrl = path.join(__dirname, "database", "lol-stalker.db");
// export const db = new sqlite3.Database(dbUrl);

export const prisma = isDev
? new PrismaClient({
datasources: {
db: { url: `file://${path.join(__dirname, "../" + dbUrl).replace("C:\\", "")}` },
},
// log: ["query", "info", "warn", "error"],
})
: new PrismaClient();
export const makeDb = () =>
isDev
? createConnection()
: createConnection({
type: "sqlite",
database: dbUrl,
entities: [path.join(__dirname, "entities/*")],
});
49 changes: 49 additions & 0 deletions electron/entities/Friend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Column, Entity, OneToMany } from "typeorm";
import { Ranking } from "./Ranking";
import { FriendName } from "./FriendName";
import { Notification } from "./Notification";

@Entity("Friend")
export class Friend {
@Column("text", { primary: true, name: "puuid", unique: true })
puuid: string;

@Column("text", { name: "id", nullable: true })
id: string | null;

@Column("text", { name: "gameName" })
gameName: string;

@Column("text", { name: "gameTag", nullable: true })
gameTag: string | null;

@Column("integer", { name: "groupId", default: () => "0" })
groupId: number;

@Column("text", { name: "groupName", default: () => "'NONE'" })
groupName: string;

@Column("text", { name: "name" })
name: string;

@Column("integer", { name: "summonerId" })
summonerId: number;

@Column("integer", { name: "icon" })
icon: number;

@Column("datetime", { name: "createdAt", default: () => "CURRENT_TIMESTAMP" })
createdAt: Date;

@Column("boolean", { name: "isCurrentSummoner", default: () => "false" })
isCurrentSummoner: boolean;

@OneToMany(() => Ranking, (ranking) => ranking.friend)
rankings: Ranking[];

@OneToMany(() => FriendName, (friendName) => friendName.friend)
friendNames: FriendName[];

@OneToMany(() => Notification, (notification) => notification.friend)
notifications: Notification[];
}
21 changes: 21 additions & 0 deletions electron/entities/FriendName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Friend } from "./Friend";

@Entity("FriendName")
export class FriendName {
@PrimaryGeneratedColumn({ type: "integer", name: "id" })
id: number;

@Column("text", { name: "name", default: () => "''" })
name: string;

@Column("datetime", { name: "createdAt", default: () => "CURRENT_TIMESTAMP" })
createdAt: Date;

@ManyToOne(() => Friend, (friend) => friend.friendNames, {
onDelete: "RESTRICT",
onUpdate: "CASCADE",
})
@JoinColumn([{ name: "puuid", referencedColumnName: "puuid" }])
friend: Friend;
}
33 changes: 33 additions & 0 deletions electron/entities/Notification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Friend } from "./Friend";

@Entity("Notification")
export class Notification {
@PrimaryGeneratedColumn({ type: "integer", name: "id" })
id: number;

@Column("text", { name: "type", default: () => "''" })
type: string;

@Column("text", { name: "from" })
from: string;

@Column("text", { name: "to" })
to: string;

@Column("text", { name: "content" })
content: string;

@Column("datetime", { name: "createdAt", default: () => "CURRENT_TIMESTAMP" })
createdAt: Date;

@Column("boolean", { name: "isNew", default: () => "true" })
isNew: boolean;

@ManyToOne(() => Friend, (friend) => friend.notifications, {
onDelete: "RESTRICT",
onUpdate: "CASCADE",
})
@JoinColumn([{ name: "puuid", referencedColumnName: "puuid" }])
friend: Friend;
}
36 changes: 36 additions & 0 deletions electron/entities/Ranking.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Friend } from "./Friend";

@Entity("Ranking")
export class Ranking {
@PrimaryGeneratedColumn({ type: "integer", name: "id" })
id: number;

@Column("text", { name: "division" })
division: string;

@Column("text", { name: "tier" })
tier: string;

@Column("integer", { name: "leaguePoints" })
leaguePoints: number;

@Column("integer", { name: "wins" })
wins: number;

@Column("integer", { name: "losses" })
losses: number;

@Column("text", { name: "miniSeriesProgress", default: () => "''" })
miniSeriesProgress: string;

@Column("datetime", { name: "createdAt", default: () => "CURRENT_TIMESTAMP" })
createdAt: Date;

@ManyToOne(() => Friend, (friend) => friend.rankings, {
onDelete: "RESTRICT",
onUpdate: "CASCADE",
})
@JoinColumn([{ name: "puuid", referencedColumnName: "puuid" }])
friend: Friend;
}
11 changes: 6 additions & 5 deletions electron/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ dotenv.config();
import { app, BrowserWindow, ipcMain, shell } from "electron";
import isDev from "electron-is-dev";
import path, { join } from "path";
import { prisma } from "./db";
import { makeDb } from "./db";
import { startCheckCurrentSummonerRank } from "./jobs/currentSummonerRank";
import { startCheckFriendListJob } from "./jobs/friendListJob";
import { connector, sendConnectorStatus } from "./LCU/lcu";
import {
receiveToggleSelectFriends,
sendApex,
sendCursoredNotifications,
sendFriendList,
sendFriendListWithRankings,
sendFriendNotifications,
sendFriendRank,
sendMatches,
sendNbNewNotifications,
Expand Down Expand Up @@ -52,6 +52,7 @@ export function makeWindow() {
return window;
}
app.whenReady().then(async () => {
const db = await makeDb();
connector.start();
await loadSelectedFriends();
makeWindow();
Expand All @@ -63,7 +64,6 @@ app.whenReady().then(async () => {
if (BrowserWindow.getAllWindows().length === 0) makeWindow();
});
app.on("window-all-closed", () => {
prisma.$disconnect();
app.quit();
process.exit(0);
});
Expand All @@ -78,13 +78,14 @@ ipcMain.on("friendList/ranks", sendFriendListWithRankings);
ipcMain.on("friendList/select", receiveToggleSelectFriends);
ipcMain.on("friendList/select-all", sendSelectAllFriends);
ipcMain.on("friendList/selected", () => sendSelected());
ipcMain.on("notifications/friend", sendFriendNotifications);
ipcMain.on("notifications/all", sendCursoredNotifications);
ipcMain.on("notifications/nb-new", sendNbNewNotifications);
ipcMain.on("friend/matches", sendMatches);

ipcMain.on("config/apex", sendApex);

ipcMain.on("config/dl-db", () => {
const url = path.join(__dirname, isDev ? "../lol-stalker.db" : "lol-stalker.db");
const url = path.join(__dirname, isDev ? "../database/lol-stalker.db" : "lol-stalker.db");
shell.showItemInFolder(url);
sendToClient("config/dl-db", "ok");
});
Expand Down
Loading

0 comments on commit 8aa0db8

Please sign in to comment.