forked from Mintplex-Labs/anything-llm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiKeys.js
96 lines (83 loc) · 2.29 KB
/
apiKeys.js
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
const prisma = require("../utils/prisma");
const ApiKey = {
tablename: "api_keys",
writable: [],
makeSecret: () => {
const uuidAPIKey = require("uuid-apikey");
return uuidAPIKey.create().apiKey;
},
create: async function (createdByUserId = null) {
try {
const apiKey = await prisma.api_keys.create({
data: {
secret: this.makeSecret(),
createdBy: createdByUserId,
},
});
return { apiKey, error: null };
} catch (error) {
console.error("FAILED TO CREATE API KEY.", error.message);
return { apiKey: null, error: error.message };
}
},
get: async function (clause = {}) {
try {
const apiKey = await prisma.api_keys.findFirst({ where: clause });
return apiKey;
} catch (error) {
console.error("FAILED TO GET API KEY.", error.message);
return null;
}
},
count: async function (clause = {}) {
try {
const count = await prisma.api_keys.count({ where: clause });
return count;
} catch (error) {
console.error("FAILED TO COUNT API KEYS.", error.message);
return 0;
}
},
delete: async function (clause = {}) {
try {
await prisma.api_keys.deleteMany({ where: clause });
return true;
} catch (error) {
console.error("FAILED TO DELETE API KEY.", error.message);
return false;
}
},
where: async function (clause = {}, limit) {
try {
const apiKeys = await prisma.api_keys.findMany({
where: clause,
take: limit,
});
return apiKeys;
} catch (error) {
console.error("FAILED TO GET API KEYS.", error.message);
return [];
}
},
whereWithUser: async function (clause = {}, limit) {
try {
const { User } = require("./user");
const apiKeys = await this.where(clause, limit);
for (const apiKey of apiKeys) {
if (!apiKey.createdBy) continue;
const user = await User.get({ id: apiKey.createdBy });
if (!user) continue;
apiKey.createdBy = {
id: user.id,
username: user.username,
role: user.role,
};
}
return apiKeys;
} catch (error) {
console.error("FAILED TO GET API KEYS WITH USER.", error.message);
return [];
}
},
};
module.exports = { ApiKey };