update to use new lambert-server

This commit is contained in:
Flam3rboy 2021-01-04 16:14:19 +01:00
parent 7bf89e1f43
commit a5c57b9363
11 changed files with 135 additions and 61 deletions

BIN
package-lock.json generated

Binary file not shown.

View File

@ -22,12 +22,15 @@
"@types/node-fetch": "^2.5.7", "@types/node-fetch": "^2.5.7",
"express": "^4.17.1", "express": "^4.17.1",
"express-cache-middleware": "^1.0.1", "express-cache-middleware": "^1.0.1",
"faker": "^5.1.0",
"lambert-db": "^1.0.3", "lambert-db": "^1.0.3",
"lambert-server": "^1.0.3",
"missing-native-js-functions": "^1.0.8", "missing-native-js-functions": "^1.0.8",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"rethinkdb-ts": "^2.4.5" "rethinkdb-ts": "^2.4.5"
}, },
"devDependencies": { "devDependencies": {
"@types/faker": "^5.1.5",
"@types/node": "^14.14.10", "@types/node": "^14.14.10",
"typescript": "^4.1.2" "typescript": "^4.1.2"
} }

View File

@ -2,27 +2,26 @@ import express, { Application, Router } from "express";
import { traverseDirectory } from "./Utils"; import { traverseDirectory } from "./Utils";
import { Server as HTTPServer } from "http"; import { Server as HTTPServer } from "http";
import fs from "fs/promises"; import fs from "fs/promises";
import { Server, ServerOptions } from "lambert-server";
export type ServerOptions = { export interface DiscordServerOptions extends ServerOptions {}
port: number;
};
export class Server { declare global {
private app: Application; namespace Express {
private http: HTTPServer; interface Request {
private options: ServerOptions; server: DiscordServer;
private routes: Router[]; }
private initalized: Promise<any>; }
}
constructor(opts: ServerOptions = { port: 8080 }) { export class DiscordServer extends Server {
this.options = opts; public options: DiscordServerOptions;
this.app = express(); constructor(opts?: DiscordServerOptions) {
super(opts);
this.initalized = this.init();
} }
async init() { async start() {
// recursively loads files in routes/ // recursively loads files in routes/
this.routes = await this.registerRoutes(__dirname + "/routes/"); this.routes = await this.registerRoutes(__dirname + "/routes/");
// const indexHTML = await (await fetch("https://discord.com/app")).buffer(); // const indexHTML = await (await fetch("https://discord.com/app")).buffer();
@ -33,39 +32,6 @@ export class Server {
res.set("content-type", "text/html"); res.set("content-type", "text/html");
res.send(indexHTML); res.send(indexHTML);
}); });
} return super.start();
async start() {
await this.initalized;
await new Promise<void>((res) => this.app.listen(this.options.port, () => res()));
console.log(`[Server] started on ${this.options.port}`);
}
async registerRoutes(root: string) {
return await traverseDirectory({ dirname: root, recursive: true }, this.registerRoute.bind(this, root));
}
registerRoute(root: string, file: string): any {
if (root.endsWith("/") || root.endsWith("\\")) root = root.slice(0, -1); // removes slash at the end of the root dir
let path = file.replace(root, ""); // remove root from path and
path = path.split(".").slice(0, -1).join("."); // trancate .js/.ts file extension of path
if (path.endsWith("/index")) path = path.slice(0, -6); // delete index from path
try {
var router = require(file);
if (router.router) router = router.router;
if (router.default) router = router.default;
if (!router || router?.prototype?.constructor?.name !== "router")
throw `File doesn't export any default router`;
this.app.use(path, <Router>router);
console.log(`[Server] Route ${path} registerd`);
return router;
} catch (error) {
console.error(new Error(`[Server] Failed to register route ${path}: ${error}`));
}
}
async stop() {
return new Promise<void>((res) => this.http.close(() => res()));
} }
} }

View File

@ -1,4 +1,4 @@
import { Server } from "./Server"; import { DiscordServer } from "./Server";
const server = new Server(); const server = new DiscordServer();
server.start().catch(console.error); server.start().catch(console.error);

View File

@ -0,0 +1,59 @@
import { Snowflake } from "./Snowflake";
export interface Guild {
afkChannel?: Snowflake;
afkTimeout: number;
onlineCount: number;
available: boolean;
banner: string | null;
channels: GuildChannelManager;
readonly createdTimestamp: number;
defaultMessageNotifications: DefaultMessageNotifications | number;
deleted: boolean;
description: string | null;
discoverySplash: string | null;
embedChannel: GuildChannel | null;
embedChannelID: Snowflake | null;
embedEnabled: boolean;
emojis: GuildEmojiManager;
explicitContentFilter: ExplicitContentFilterLevel;
features: GuildFeatures[];
icon: string | null;
id: Snowflake;
joinedTimestamp: number;
large: boolean;
maximumMembers: number | null;
maximumPresences: number | null;
memberCount: number;
members: GuildMemberManager;
mfaLevel: number;
name: string;
readonly nameAcronym: string;
readonly owner: Snowflake | null;
ownerID: Snowflake;
readonly partnered: boolean;
preferredLocale: string;
premiumSubscriptionCount: number | null;
premiumTier: PremiumTier;
presences: PresenceManager;
readonly publicUpdatesChannel: TextChannel | null;
publicUpdatesChannelID: Snowflake | null;
region: string;
roles: RoleManager;
readonly rulesChannel: TextChannel | null;
rulesChannelID: Snowflake | null;
readonly shard: WebSocketShard;
shardID: number;
splash: string | null;
readonly systemChannel: TextChannel | null;
systemChannelFlags: Readonly<SystemChannelFlags>;
systemChannelID: Snowflake | null;
vanityURLCode: string | null;
vanityURLUses: number | null;
verificationLevel: VerificationLevel;
readonly verified: boolean;
readonly voiceStates: VoiceStateManager;
readonly widgetChannel: TextChannel | null;
widgetChannelID: Snowflake | null;
widgetEnabled: boolean | null;
}

1
src/models/Snowflake.ts Normal file
View File

@ -0,0 +1 @@
export type Snowflake = string;

0
src/models/database.ts Normal file
View File

View File

View File

@ -1,10 +0,0 @@
import { r } from "rethinkdb-ts";
async function main() {
await r.connectPool();
const result = await r.db("test").tableCreate("authors").run();
console.log(result);
}
main();

55
src/test/db_benchmark.ts Normal file
View File

@ -0,0 +1,55 @@
// @ts-nocheck
import { r } from "rethinkdb-ts";
import faker from "faker";
import cluster from "cluster";
import { performance } from "perf_hooks";
console.log("starting");
if (cluster.isMaster) {
for (var i = 0; i < 1; i++) {
cluster.fork();
}
console.log("all nodes started");
}
if (cluster.isWorker) {
const inserts = [];
for (let i = 0; i < 100; i++) {
inserts.push({
color: faker.commerce.color(),
department: faker.commerce.department(),
price: faker.commerce.price(),
product: faker.commerce.product(),
productAdjective: faker.commerce.productAdjective(),
productName: faker.commerce.productName(),
productMaterial: faker.commerce.productMaterial(),
productDescription: faker.commerce.productDescription(),
});
}
async function main(connection) {
const start = performance.now();
await r
.db("test")
.table("test")
.nth(Math.floor(Math.random() * 300000))
.run(connection);
const end = performance.now();
// console.log(end - start);
// await main(connection);
setTimeout(main.bind(null, connection));
}
(async () => {
const threads = 30;
for (var i = 0; i < threads; i++) {
setTimeout(async () => {
main(await r.connect({ port: 28015, host: "192.168.178.122" }));
});
}
})();
}