Complete Rewrite
This commit is contained in:
37
server/APIRoute.js
Normal file
37
server/APIRoute.js
Normal file
@@ -0,0 +1,37 @@
|
||||
import express from 'express';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import bodyParser from 'body-parser';
|
||||
|
||||
export default class APIRoute {
|
||||
constructor(path = '/') {
|
||||
this.path = "/api" + path;
|
||||
this.router = express.Router();
|
||||
this.router.use(cookieParser());
|
||||
this.router.use(bodyParser.json());
|
||||
this.router.use(bodyParser.urlencoded({ extended: true }));
|
||||
this.router.get("/", this.get);
|
||||
this.router.post("/", this.post);
|
||||
}
|
||||
|
||||
addSubRoute(name, method, callback) {
|
||||
this.router[method](name, callback);
|
||||
}
|
||||
|
||||
async get(req, res) {
|
||||
res.send('GET request');
|
||||
}
|
||||
|
||||
async post(req, res) {
|
||||
res.send('POST request');
|
||||
}
|
||||
|
||||
getPath() {
|
||||
return this.path;
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
|
||||
}
|
||||
44
server/APISession.js
Normal file
44
server/APISession.js
Normal file
@@ -0,0 +1,44 @@
|
||||
|
||||
export default class APISession {
|
||||
|
||||
constructor() {
|
||||
this.sessions = new Map();
|
||||
}
|
||||
|
||||
generateSessionID() {
|
||||
let id = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
||||
return id;
|
||||
}
|
||||
|
||||
createSession(id) {
|
||||
if(this.sessions.get(id)) return false;
|
||||
this.sessions.set(id, this.generateSessionID());
|
||||
return this.sessions.get(id);
|
||||
}
|
||||
|
||||
getSession(id) {
|
||||
for (let [key, value] in this.sessions) {
|
||||
if (key == id) return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
setSession(id, value) {
|
||||
if (!this.sessions.get(id)) return false;
|
||||
this.sessions.set(id, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
getSessionUser(sessionValue) {
|
||||
for (let [key, value] of this.sessions) {
|
||||
if (value == sessionValue) return key;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
deleteSessionValue(id, key) {
|
||||
if (!this.sessions.get(id)) return false;
|
||||
this.sessions.delete(key);
|
||||
return
|
||||
}
|
||||
}
|
||||
75
server/server.js
Normal file
75
server/server.js
Normal file
@@ -0,0 +1,75 @@
|
||||
// @ts-nocheck
|
||||
import { handler } from '../build/handler.js';
|
||||
import dotenv from 'dotenv';
|
||||
import http from 'http';
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import fs from 'fs';
|
||||
import ms from 'ms';
|
||||
import Mongo from './storage/Mongo.js';
|
||||
import APISession from './APISession.js';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const server = http.Server(app);
|
||||
const MongoServer = new Mongo(process.env.MONGO_URI);
|
||||
|
||||
app.use(cors());
|
||||
app.set("mongo", MongoServer);
|
||||
app.set("session", new APISession());
|
||||
|
||||
async function loadFolder(filePath) {
|
||||
let files = [];
|
||||
fs.readdirSync(filePath).forEach(file => {
|
||||
if (fs.lstatSync(`${filePath}/${file}`).isDirectory()) {
|
||||
loadFolder(`${filePath}/${file}`);
|
||||
} else {
|
||||
files.push(`${filePath}/${file}`);
|
||||
}
|
||||
});
|
||||
return files;
|
||||
}
|
||||
|
||||
async function loadFiles(filePath) {
|
||||
const file = await import(`../${filePath}`);
|
||||
if (file.default) {
|
||||
let route = new file.default();
|
||||
app.use(route.path, route.getRouter());
|
||||
console.log(`Loaded ${route.path}`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
fs.readdirSync('./server/api').forEach(async(file) => {
|
||||
if (fs.lstatSync(`./server/api/${file}`).isDirectory()) {
|
||||
let files = await loadFolder(`./server/api/${file}`);
|
||||
files.forEach(async(file) => {
|
||||
await loadFiles(file);
|
||||
});
|
||||
} else {
|
||||
await loadFiles(`./server/api/${file}`);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
} finally {
|
||||
setTimeout(() => {
|
||||
console.log('API loaded');
|
||||
app.use(handler);
|
||||
}, ms('1s'));
|
||||
}
|
||||
|
||||
server.listen(process.env.PORT, () => {
|
||||
console.log(`listening on port http://localhost:${process.env.PORT}`);
|
||||
});
|
||||
|
||||
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
console.log('Unhandled Rejection at:', reason.stack || reason);
|
||||
});
|
||||
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.log('Uncaught Exception thrown');
|
||||
console.error(error);
|
||||
});
|
||||
18
server/storage/Mongo.js
Normal file
18
server/storage/Mongo.js
Normal file
@@ -0,0 +1,18 @@
|
||||
import mongoose from "mongoose";
|
||||
import Users from "./collections/users.js";
|
||||
|
||||
export default class Mongo {
|
||||
constructor(uri) {
|
||||
this.connect(uri);
|
||||
this.users = new Users();
|
||||
}
|
||||
|
||||
async connect(uri) {
|
||||
mongoose.set('strictQuery', true);
|
||||
return mongoose.connect(uri).then(() => { console.log('MongoDB connected') });
|
||||
}
|
||||
|
||||
async disconnect() {
|
||||
return mongoose.disconnect();
|
||||
}
|
||||
}
|
||||
72
server/storage/collections/users.js
Normal file
72
server/storage/collections/users.js
Normal file
@@ -0,0 +1,72 @@
|
||||
import mongoose from "mongoose";
|
||||
|
||||
const reqString = {
|
||||
type: String,
|
||||
required: true
|
||||
}
|
||||
|
||||
const UserSchema = new mongoose.Schema({
|
||||
id: reqString,
|
||||
|
||||
}, { timestamps: true });
|
||||
|
||||
export default class Users {
|
||||
constructor() {
|
||||
this.model = mongoose.model('users', UserSchema);
|
||||
this.upsert = { upsert: true };
|
||||
}
|
||||
|
||||
makeId(length) {
|
||||
var result = [];
|
||||
var characters = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789';
|
||||
var charactersLength = characters.length;
|
||||
for ( var i = 0; i < length; i++ ) {
|
||||
result.push(characters.charAt(Math.floor(Math.random() * charactersLength)));
|
||||
}
|
||||
return result.join('');
|
||||
}
|
||||
|
||||
async create(user) {
|
||||
if(await this.model.findOne({ username: user.username }) || await this.model.findOne({ email: user.email })) return null;
|
||||
|
||||
let Id = this.makeId(5);
|
||||
|
||||
await this.model.findOneAndUpdate({ id: Id }, {
|
||||
id: Id,
|
||||
}, this.upsert);
|
||||
return await this.get(user.id);
|
||||
}
|
||||
|
||||
async get(Id) {
|
||||
let data = await this.model.findOne({ id: Id });
|
||||
if(data) data.password = undefined;
|
||||
return data;
|
||||
}
|
||||
|
||||
async getByUsername(username) {
|
||||
let data = await this.model.findOne({ username: username }) || await this.model.findOne({ email: username });
|
||||
if(data) data.password = undefined;
|
||||
return data;
|
||||
}
|
||||
|
||||
async getAll(query) {
|
||||
let data = await this.model.find(query);
|
||||
data.forEach(user => {
|
||||
user.password = undefined;
|
||||
});
|
||||
return data
|
||||
}
|
||||
|
||||
async update(Id, data) {
|
||||
if(!(await this.get(Id))) return null;
|
||||
await this.model.findOneAndUpdate({ id: Id }, data, this.upsert);
|
||||
return await this.get(Id);
|
||||
}
|
||||
|
||||
async delete(Id) {
|
||||
let result = await this.get(Id);
|
||||
if(!result) return false;
|
||||
await this.model.deleteOne({ id: Id })
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user