personal_website/controllers/userController.ts
2024-07-31 15:53:27 +02:00

50 lines
1.5 KiB
TypeScript

import { type Request, type Response } from "express";
import UserModel, { values } from '../models/userModel';
export default {
render: async function (req: Request, res: Response) {
res.render('user', { keys: UserModel.namesOfValues });
},
create: async function (req: Request, res: Response) {
const reqPassword: string = req.body.reqPassword;
if (!reqPassword) return res.render('user', { keys: UserModel.namesOfValues });
const password = await UserModel.getValue(values.pass);
// if no password in db save reqPassword
if (!password) {
const affectedRows = await UserModel.updateValue("pass", reqPassword);
if (affectedRows > 0) {
return res.redirect('/list');
}
return res.render('user', { keys: UserModel.namesOfValues });
}
// check if passwords equal
if (password != reqPassword) {
return res.render('user', { keys: UserModel.namesOfValues });
}
// update
const name: string = req.body.name;
const value: string = req.body.value;
if (!name || !value) {
return res.render('user', { keys: UserModel.namesOfValues });
}
const affectedRows = await UserModel.updateValue(name, value);
if (affectedRows == 0) {
return res.render('user', { keys: UserModel.namesOfValues });
}
return res.redirect('/list');
},
get: async function (req: Request, res: Response) {
const usersFound = await UserModel.getAll();
return res.status(200).json(usersFound);
},
};