9 Commits

Author SHA1 Message Date
ca90835357 chore(deps): update dependency tsup to v8.0.2 2024-03-06 01:16:47 +00:00
6a058acd58 fix deps 2023-11-20 16:04:10 +00:00
78c16354d3 fix deps 2023-11-20 15:52:58 +00:00
415b9f8928 add route logging and a generic error handler for routes 2023-11-20 15:42:08 +00:00
35d78dc617 use environment when fetching infisical tokens 2023-11-20 15:15:07 +00:00
43bdcfe9e1 rename infisical token env var 2023-11-20 15:14:19 +00:00
fef36b8210 add player model 2023-11-20 15:14:01 +00:00
0430186f7e add mongo and infisical 2023-11-20 14:43:55 +00:00
3f7b723311 change startup log 2023-11-20 14:29:10 +00:00
11 changed files with 859 additions and 272 deletions

1
.env-example Normal file
View File

@ -0,0 +1 @@
INFISICAL_TOKEN=set me

View File

@ -5,19 +5,22 @@
"main": "dist/index.js", "main": "dist/index.js",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"build": "tsup src/index.ts --format cjs", "build": "tsup src/index.ts --format cjs --minify terser",
"start": "node dist/index.js", "start": "node dist/index.js",
"dev": "nodemon --exec ts-node src/index.ts" "dev": "nodemon --exec ts-node src/index.ts"
}, },
"dependencies": { "dependencies": {
"dotenv": "^16.3.1",
"express": "^4.18.2", "express": "^4.18.2",
"infisical-node": "^1.5.0",
"mongoose": "^8.0.1", "mongoose": "^8.0.1",
"tsup": "^8.0.0",
"typescript": "^5.2.2" "typescript": "^5.2.2"
}, },
"devDependencies": { "devDependencies": {
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"nodemon": "^3.0.1", "nodemon": "^3.0.1",
"ts-node": "^10.9.1" "terser": "^5.24.0",
"ts-node": "^10.9.1",
"tsup": "^8.0.0"
} }
} }

903
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
import mongoose, { Model } from "mongoose";
const { Schema } = mongoose;
const schema = new Schema({
/**
* The ID of the player
*/
_id: String,
scoresaber: {
name: String,
profilePicture: String,
country: String,
pp: Number,
rank: Number,
countryRank: Number,
role: String,
badges: [
{
image: String,
description: String,
},
],
histories: String,
scoreStats: {
totalScore: Number,
totalRankedScore: Number,
averageRankedAccuracy: Number,
totalPlayCount: Number,
rankedPlayCount: Number,
replaysWatched: Number,
},
permissions: Number,
banned: Boolean,
inactive: Boolean,
},
});
export const PlayerSchema =
(mongoose.models.Player as Model<typeof schema>) ||
mongoose.model("Player", schema);

11
src/database/mongo.ts Normal file
View File

@ -0,0 +1,11 @@
import mongoose from "mongoose";
import { Secrets } from "../secrets/secrets";
/**
* Connects to the mongo database
*
* @returns a promise that resolves when the connection is established
*/
export function connectMongo() {
return mongoose.connect(Secrets.MONGO_URI);
}

View File

@ -1,4 +1,33 @@
import dotenv from "dotenv";
import { connectMongo } from "./database/mongo";
import { initSecrets } from "./secrets/secrets";
import { SsrServer } from "./server/impl/ssrServer"; import { SsrServer } from "./server/impl/ssrServer";
import { checkEnvironmentVariables } from "./util/envVariables";
import { createInfisicalClient } from "./util/secrets";
// Init the SSR Server // Load the environment variables
const server = new SsrServer(); dotenv.config();
const isValid = checkEnvironmentVariables("INFISICAL_TOKEN");
if (!isValid) {
process.exit(1);
}
export const InfisicalClient = createInfisicalClient(
process.env.INFISICAL_TOKEN!
);
console.log("---");
console.log(
"NOTE: If the infisical secret is invalid, it will say secrets are missing."
);
console.log("If this happens please check the env variable and/or the secret");
console.log("---");
// Load the secrets first so we ensure they are valid before starting the server
initSecrets().then(async () => {
await connectMongo();
console.log("Connected to mongo");
// Init the SSR Server
new SsrServer();
});

48
src/route/messages.ts Normal file
View File

@ -0,0 +1,48 @@
/**
* Creates the base message for web responses
*
* @param message the message to send
* @returns the message
*/
function baseMessage(error: boolean, message: string) {
return {
error,
message,
};
}
/**
* Creates an error message for web responses
*
* @param message the message to send
* @returns the message
*/
function errorMessage(message: string) {
return baseMessage(true, message);
}
/**
* Creates a success message for web responses
*
* @param message the message to send
* @returns the message
*/
function successMessage(message: string) {
return baseMessage(false, message);
}
/**
* Creates a message for an internal server error
*
* @returns the message
*/
function internalServerError() {
return errorMessage("Internal Server Error");
}
export const ServerMessages = {
baseMessage,
errorMessage,
successMessage,
internalServerError,
};

34
src/secrets/secrets.ts Normal file
View File

@ -0,0 +1,34 @@
import { GetOptions } from "infisical-node/src/types/InfisicalClient";
import { InfisicalClient } from "..";
let MONGO_URI: string;
/**
* Initialize the secrets
*/
export async function initSecrets() {
const options: GetOptions = {
environment: process.env.NODE_ENV === "production" ? "main" : "dev",
path: "/",
type: "shared",
};
const mongoUri = (await InfisicalClient.getSecret("MONGO_URI", options))
.secretValue;
if (!mongoUri) {
console.log("MONGO_URI not set in secrets");
process.exit(1);
}
MONGO_URI = mongoUri;
}
/**
* All of the Infisical secrets
*/
export const Secrets = {
get MONGO_URI() {
return MONGO_URI;
},
};

View File

@ -1,4 +1,5 @@
import express, { Express } from "express"; import express, { Express } from "express";
import { ServerMessages } from "../route/messages";
import { Route } from "../route/route"; import { Route } from "../route/route";
type ServerConfig = { type ServerConfig = {
@ -32,15 +33,30 @@ export default class Server {
this.server = express(); this.server = express();
this.preInit(); this.preInit();
// Setup route logging
this.server.use((req, res, next) => {
// TODO: make this look better?
console.log(`[${req.method}] ${req.path}`);
next();
});
// Handle the routes // Handle the routes
for (const route of this.routes) { for (const route of this.routes) {
this.server.all(route.getPath(), (req, res, next) => { this.server.all(route.getPath(), (req, res, next) => {
if (req.method.toUpperCase() !== route.getMethod().toUpperCase()) { if (req.method.toUpperCase() !== route.getMethod().toUpperCase()) {
return next(); // Skip this method return next(); // Skip this method
} }
try {
route.handle(req, res, next); route.handle(req, res, next);
} catch (ex) {
console.error(ex);
// Inform the user that an internal server error occurred
res.status(500).json(ServerMessages.internalServerError());
}
}); });
} }
// Log the registered routes
console.log(`Registered ${this.routes.length} routes`); console.log(`Registered ${this.routes.length} routes`);
for (const route of this.routes) { for (const route of this.routes) {
console.log(` - ${route.getMethod().toUpperCase()} ${route.getPath()}`); console.log(` - ${route.getMethod().toUpperCase()} ${route.getPath()}`);
@ -53,7 +69,7 @@ export default class Server {
// Start listening on the specified port // Start listening on the specified port
this.server.listen(this.port, () => { this.server.listen(this.port, () => {
console.log(`Server listening on port ${this.port}`); console.log(`Server listening on http://localhost:${this.port}`);
this.postInit(); this.postInit();
}); });
} }

15
src/util/envVariables.ts Normal file
View File

@ -0,0 +1,15 @@
/**
* Checks if all environment variables are set
*
* @param variables the environment variables to check
* @returns true if all variables are set, false otherwise
*/
export function checkEnvironmentVariables(...variables: string[]): boolean {
let allVariablesSet = true;
variables.forEach((variable) => {
if (!process.env[variable]) {
throw new Error(`${variable} not set in environment variables`);
}
});
return allVariablesSet;
}

16
src/util/secrets.ts Normal file
View File

@ -0,0 +1,16 @@
import InfisicalClient from "infisical-node";
/**
* Create an infisical client
*
* @param token the infisical token
* @returns the infisical client
*/
function createInfisicalClient(token: string) {
return new InfisicalClient({
token,
siteURL: "https://secrets.fascinated.cc",
});
}
export { createInfisicalClient };