1
0
mirror of https://github.com/spacebarchat/server.git synced 2024-11-22 10:22:39 +01:00

update to use new Lambert-server

This commit is contained in:
Flam3rboy 2021-01-04 16:10:12 +01:00
parent 9955183fa1
commit 35655773d7
5 changed files with 3385 additions and 1584 deletions

4873
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -24,6 +24,7 @@
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"lambert-db": "^1.0.5",
"lambert-server": "^1.0.3",
"missing-native-js-functions": "^1.0.8",
"multer": "^1.4.2",
"node-fetch": "^2.6.1",

View File

@ -1,93 +1,42 @@
import express, { Application, Router, Request, Response, NextFunction } from "express";
import { MongoDatabase, Database } from "lambert-db";
import { Server as HTTPServer } from "http";
import { traverseDirectory } from "./Util";
import bodyParser from "body-parser";
import "express-async-errors";
import { Server, ServerOptions } from "lambert-server";
const log = console.log;
console.log = (content) => {
log(`[${new Date().toTimeString().split(" ")[0]}]`, content);
};
export type ServerOptions = {
db: string;
port: number;
host: string;
};
declare global {
namespace Express {
interface Request {
server: Server;
cdn: CDNServer;
}
}
}
export class Server {
app: Application;
http: HTTPServer;
export interface CDNServerOptions extends ServerOptions {
db: string;
}
export class CDNServer extends Server {
db: Database;
routes: Router[];
options: ServerOptions;
public options: CDNServerOptions;
constructor(options: CDNServerOptions) {
super(options);
constructor(options: Partial<ServerOptions> = { port: 3000, host: "0.0.0.0" }) {
this.app = express();
this.db = new MongoDatabase(options?.db);
this.options = options as ServerOptions;
}
async init() {
async start() {
console.log("[Database] connecting ...");
await this.db.init();
console.log("[Database] connected...");
await new Promise((res, rej) => {
this.http = this.app.listen(this.options.port, this.options.host, () => res(null));
});
this.routes = await this.registerRoutes(__dirname + "/routes/");
console.log("[Database] connected");
return super.start();
}
async registerRoutes(root: string) {
this.app.use((req, res, next) => {
req.server = this;
next();
});
const routes = await traverseDirectory({ dirname: root, recursive: true }, this.registerRoute.bind(this, root));
this.app.use((err: string | Error, req: Request, res: Response, next: NextFunction) => {
res.status(400).send(err);
next(err);
});
return routes;
}
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(`[Routes] ${path} registerd`);
return router;
} catch (error) {
console.error(new Error(`[Server] ¯\\_(ツ)_/¯ Failed to register route ${path}: ${error}`));
}
}
async destroy() {
async stop() {
await this.db.destroy();
await new Promise((res, rej) => {
this.http.close((err) => {
if (err) return rej(err);
return res("");
});
});
return super.stop();
}
}

View File

@ -15,7 +15,7 @@ type Attachment = {
router.post("/:filename", multer_.single("attachment"), async (req, res) => {
const { buffer, mimetype } = req.file;
const { filename } = req.params;
const { db } = req.server;
const { db } = req.cdn;
const File: Attachment = {
filename,
@ -30,7 +30,7 @@ router.post("/:filename", multer_.single("attachment"), async (req, res) => {
});
router.get("/:hash/:filename", async (req, res) => {
const { db } = req.server;
const { db } = req.cdn;
const { hash, filename } = req.params;
const File: Attachment = await db.data.attachments({ id: hash, filename: filename }).get();
@ -41,7 +41,7 @@ router.get("/:hash/:filename", async (req, res) => {
router.delete("/:hash/:filename", async (req, res) => {
const { hash, filename } = req.params;
const { db } = req.server;
const { db } = req.cdn;
await db.data.attachments({ id: hash, filename: filename }).delete();
return res.send({ success: true, message: "attachment deleted" });

View File

@ -30,7 +30,7 @@ const DEFAULT_FETCH_OPTIONS: any = {
router.post("/", bodyParser.json(), async (req, res) => {
if (!req.body) throw new Error("Invalid Body (url missing) \nExample: url:https://discord.com");
const { db } = req.server;
const { db } = req.cdn;
const { url } = req.body;
const ID = btoa(url);
@ -72,7 +72,7 @@ router.post("/", bodyParser.json(), async (req, res) => {
});
router.get("/:id/:filename", async (req, res) => {
const { db } = req.server;
const { db } = req.cdn;
const { id, filename } = req.params;
const { image, type } = await db.data.externals({ id: id }).get();
const imageBuffer = Buffer.from(image, "base64");