-
Notifications
You must be signed in to change notification settings - Fork 0
/
usermanager.ts
106 lines (99 loc) · 2.61 KB
/
usermanager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// 获取命令行参数,增加或删除用户
import { PrismaClient } from "@prisma/client";
import { argv } from "process";
const usage = "Usage: bun usermanager.ts add|delete|change";
const action = argv[2];
const prisma = new PrismaClient();
async function addUser() {
const usage = "Usage: bun usermanager.ts add username useremail role";
const username = argv[3];
const useremail = argv[4];
const role = argv[5];
if (role !== "ADMIN" && role !== "USER") {
console.error(usage);
console.error("Invalid role type (ADMIN|USER)");
process.exit(1);
}
if (!username || !useremail) {
console.error(usage);
process.exit(1);
}
try {
await prisma.user.create({
data: {
name: username,
email: useremail,
role: role
}
});
} catch (e) {
console.error(`User ${username} already exists`)
process.exit(1);
}
console.log("User added");
}
async function delUser() {
const usage = "Usage: bun usermanager.ts delete username";
const username = argv[3];
if (!username) {
console.error(usage);
process.exit(1);
}
try {
await prisma.user.delete({
where: {
name: username
}
});
} catch (e) {
console.error(`User ${username} not found`)
process.exit(1);
}
console.log("User deleted");
}
async function changeUser() {
const usage = "Usage: bun usermanager.ts change username role";
const username = argv[3];
const role = argv[4];
if (role !== "ADMIN" && role !== "USER") {
console.error("Invalid role type (ADMIN|USER)");
process.exit(1);
}
if (!username || !role) {
console.error(usage);
process.exit(1);
}
if (role === "ADMIN" || role === "USER") {
try {
await prisma.user.update({
where: {
name: username
},
data: {
role: role
}
});
} catch (e) {
console.error(`User ${username} not found`)
process.exit(1);
}
} else {
console.error("Invalid role");
process.exit(1);
}
console.log(`User ${username} role changed to ${role}`);
}
switch (action) {
case "add":
await addUser();
break;
case "del" || "delete":
await delUser();
break;
case "change":
await changeUser();
break;
default:
console.error(usage);
process.exit(1);
}