: add example config and helper method of executing code with exception handling (todo: add exception handling)

This commit is contained in:
StarAppeal
2024-02-29 13:53:18 +01:00
parent 15160480c1
commit f96b658537
3 changed files with 32 additions and 15 deletions
+9
View File
@@ -5,5 +5,14 @@ export default class User {
public name: string,
public uuid: string,
public id: ObjectId,
public config : UserConfig
) {}
}
export class UserConfig {
constructor(
public isVisible: boolean ,
public canBeModified: boolean,
public isAdmin: boolean
) {}
}
+22 -14
View File
@@ -1,8 +1,8 @@
import "dotenv/config";
import * as mongoDB from "mongodb";
import User from "../models/user";
import { ObjectId, ReturnDocument } from "mongodb";
import User from "../models/user";
let mongoDb: mongoDB.Db;
@@ -33,26 +33,34 @@ export class UserService {
return this._instance;
}
public async updateUser(id: string, user: User): Promise<User> {
const result = await this.collection.findOneAndUpdate(
{ _id: new ObjectId(id) },
{ $set: user },
{ returnDocument: ReturnDocument.AFTER },
);
return result as unknown as User;
public async updateUser(id: string, user: User) {
return (await this.executeWithExceptionHandling(() => {
return this.collection.findOneAndUpdate(
{ _id: new ObjectId(id) },
{ $set: user },
{ returnDocument: ReturnDocument.AFTER },
);
})) as unknown as User;
}
public async getAllUsers(): Promise<User[]> {
return (await this.collection.find().toArray()) as unknown as User[];
public async getAllUsers() {
return (await this.executeWithExceptionHandling(() => {
return this.collection.find().toArray();
})) as unknown as User[];
}
async getUserById(id: string) {
try {
return (await this.collection.findOne({
return (await this.executeWithExceptionHandling(() => {
return this.collection.findOne({
_id: new ObjectId(id),
})) as unknown as User;
});
})) as unknown as User;
}
private async executeWithExceptionHandling<T>(operation: () => Promise<T>) {
try {
return await operation();
} catch (e) {
// TODO: implement proper logging
console.error(e);
return null;
}
+1 -1
View File
@@ -34,7 +34,7 @@ export class RestUser {
result
? res.status(200).send(result)
: res.status(304).send(`User with id: ${id} was not updated.`);
: res.status(304).send("Not Modified");
});
return router;