52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
import { db } from '$lib/server/dbService';
|
|
|
|
export const getUsers = (): { userId: string; userName: string }[] => {
|
|
const getUsersSQLStmt = `SELECT id, name
|
|
FROM users;`;
|
|
const statement = db.prepare(getUsersSQLStmt);
|
|
const result = statement.all() as { id: string; name: string }[];
|
|
const userList: { userId: string; userName: string }[] = [];
|
|
|
|
for (const resultItem of result) {
|
|
const user = { userId: resultItem.id, userName: resultItem.name };
|
|
userList.push(user);
|
|
}
|
|
|
|
return userList;
|
|
};
|
|
|
|
export const addUser = (userName: string, userPassword: string) => {
|
|
const addUserSQLStmt = `INSERT into users(name, pw)
|
|
values (?, ?)`;
|
|
const statement = db.prepare(addUserSQLStmt);
|
|
|
|
let rowInfo;
|
|
try {
|
|
rowInfo = statement.run(userName, userPassword);
|
|
return rowInfo;
|
|
} catch (error) {
|
|
console.error('ERROR: ', error);
|
|
}
|
|
};
|
|
|
|
export const deleteUser = (userId: string) => {
|
|
// make sure to not delete the last entry
|
|
const deleteUserSQLStmt = `DELETE
|
|
FROM users
|
|
WHERE id = ?
|
|
AND (SELECT COUNT(*) FROM users) > 1;`;
|
|
|
|
const statement = db.prepare(deleteUserSQLStmt);
|
|
|
|
let rowCount;
|
|
try {
|
|
const info = statement.run(userId);
|
|
rowCount = info.changes;
|
|
} catch (error) {
|
|
console.log(error);
|
|
rowCount = 0;
|
|
}
|
|
|
|
return rowCount;
|
|
};
|