-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-service.ts
More file actions
239 lines (203 loc) · 5.78 KB
/
user-service.ts
File metadata and controls
239 lines (203 loc) · 5.78 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Context: This is a UserService from an internal API. It handles user CRUD
// operations, caching, and data export.
//
// Assume standard library types (Request, Response, etc.) are available.
interface User {
id: string;
name: string;
email: string;
role: "admin" | "editor" | "viewer";
createdAt: Date;
lastLogin: Date | null;
}
interface Database {
query<T>(sql: string, params?: unknown[]): Promise<T[]>;
execute(sql: string, params?: unknown[]): Promise<{ rowCount: number }>;
}
// In-memory cache
const userCache: Record<string, User> = {};
export class UserService {
private db: Database;
constructor(db: Database) {
this.db = db;
}
// Fetch a single user by ID, with caching
async getUser(id: string): Promise<User | null> {
if (userCache[id]) {
return userCache[id];
}
const rows = await this.db.query<User>(
"SELECT * FROM users WHERE id = $1",
[id]
);
if (rows.length > 0) {
userCache[id] = rows[0];
return rows[0];
}
return null;
}
// Create a new user
async createUser(data: {
name: string;
email: string;
role: string;
}): Promise<User | { error: string }> {
if (!data.email.includes("@")) {
return { error: "Invalid email" };
}
if (data.name.length < 1 || data.name.length > 200) {
return { error: "Name must be between 1 and 200 characters" };
}
if (
data.role !== "admin" &&
data.role !== "editor" &&
data.role !== "viewer"
) {
return { error: "Invalid role" };
}
const existing = await this.db.query<User>(
"SELECT * FROM users WHERE email = $1",
[data.email]
);
if (existing.length > 0) {
return { error: "Email already in use" };
}
const id = crypto.randomUUID();
await this.db.execute(
"INSERT INTO users (id, name, email, role, createdAt) VALUES ($1, $2, $3, $4, $5)",
[id, data.name, data.email, data.role, new Date()]
);
try {
fetch("https://email-service.internal.company.com/api/v1/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
to: data.email,
template: "welcome",
data: { name: data.name },
}),
});
} catch (e) {
console.log("Failed to send welcome email");
}
// Log to audit service
try {
fetch("https://audit-service.internal.company.com/api/v1/events", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "user.created",
actor: "system",
target: id,
timestamp: new Date().toISOString(),
}),
});
} catch (e) {
console.log("Failed to log audit event");
}
const user: User = {
id,
name: data.name,
email: data.email,
role: data.role as User["role"],
createdAt: new Date(),
lastLogin: null,
};
userCache[id] = user;
return user;
}
// Update a user's role
async updateUserRole(
userId: string,
newRole: string,
updatedBy: string
): Promise<void> {
const user = this.getUser(userId);
if (!user) {
throw new Error("User not found");
}
await this.db.execute("UPDATE users SET role = $1 WHERE id = $2", [
newRole,
userId,
]);
if (userCache[userId]) {
userCache[userId].role = newRole as User["role"];
}
}
// Deactivate a user
async deactivateUser(userId: string): Promise<boolean> {
const result = await this.db.execute(
"UPDATE users SET active = false WHERE id = $1",
[userId]
);
delete userCache[userId];
if (result.rowCount === 0) {
return false;
}
return true;
}
// Get all users with a specific role, with details from external profile service
async getUsersByRoleWithProfiles(role: string): Promise<any[]> {
const users = await this.db.query<User>(
"SELECT * FROM users WHERE role = $1",
[role]
);
const results = [];
for (const user of users) {
const response = await fetch(
`https://profile-service.internal.company.com/api/v1/profiles/${user.id}`
);
const profile = await response.json();
results.push({ ...user, profile });
}
return results;
}
// Export users in different formats
async exportUsers(format: string): Promise<string> {
const users = await this.db.query<User>("SELECT * FROM users", []);
if (format === "csv") {
let csv = "id,name,email,role,createdAt\n";
for (const user of users) {
csv += `${user.id},${user.name},${user.email},${user.role},${user.createdAt}\n`;
}
return csv;
} else if (format === "json") {
return JSON.stringify(users, null, 2);
} else if (format === "yaml") {
let yaml = "users:\n";
for (const user of users) {
yaml += ` - id: ${user.id}\n`;
yaml += ` name: ${user.name}\n`;
yaml += ` email: ${user.email}\n`;
yaml += ` role: ${user.role}\n`;
}
return yaml;
} else {
// Default to JSON
return JSON.stringify(users);
}
}
// Bulk delete inactive users older than 90 days
async cleanupInactiveUsers(): Promise<number> {
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() - 90);
const inactive = await this.db.query<User>(
"SELECT * FROM users WHERE lastLogin < $1 OR lastLogin IS NULL",
[cutoff]
);
let deleted = 0;
for (const user of inactive) {
if (user.role === "admin") {
continue;
}
try {
await this.db.execute("DELETE FROM users WHERE id = $1", [user.id]);
delete userCache[user.id];
deleted++;
} catch (e) {
// continue with next user
}
}
return deleted;
}
}