-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.ts
More file actions
194 lines (173 loc) · 4.87 KB
/
database.ts
File metadata and controls
194 lines (173 loc) · 4.87 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
import { userToTeam, db, and, eq, log, team, teamJoinRequest } from "db";
import type { UserType, SiteRoleType } from "db/types";
import type { LoggingOptions, LoggingType } from "../types";
import { type Context } from "hono";
import { isInDevMode } from ".";
/**
* Fetches a database dump from a Turso database instance.
* @param databseName The name of the database.
* @param organizationSlug The organization slug associated with the database.
*/
export async function getDatabaseDumpTurso(
databseName: string,
organizationSlug: string,
) {
const res = await fetch(
`https://${databseName}-${organizationSlug}.turso.io/dump`,
{
method: "GET",
headers: new Headers({
// Authorization: `Bearer ${env.BACKUPS_DB_BEARER}`,
}),
},
);
if (!res.ok) {
throw new Error(
`Failed to get database dump: ${res.status} ${res.statusText}`,
);
}
return res.text();
}
/**
* Checks the database connection by pinging it and querying for it's table count.
* Function will take in an database information and the type to make the appropriate query.
*/
export async function pingDatabase() {}
export function isSiteAdminUser(
permissionEnum: NonNullable<UserType>["siteRole"],
): boolean {
return ["ADMIN", "SUPER_ADMIN"].some((role) => role === permissionEnum);
}
export async function findTeam(teamId: string) {
return db.query.team.findFirst({
where: eq(team.id, teamId),
});
}
export async function findTeamUserFacing(teamId: string) {
return db.query.team.findFirst({
columns: {
id: true,
name: true,
},
where: eq(team.id, teamId),
});
}
export async function leaveTeam(userId: string, teamId: string) {
return db
.delete(userToTeam)
.where(
and(eq(userToTeam.userId, userId), eq(userToTeam.teamId, teamId)),
)
.returning({ teamId: userToTeam.teamId });
}
export async function getAdminUserForTeam(userId: string, teamId: string) {
return db.query.userToTeam.findFirst({
where: and(
eq(userToTeam.userId, userId),
eq(userToTeam.teamId, teamId),
eq(userToTeam.role, "ADMIN"),
),
});
}
export async function getJoinTeamRequest(
requestId: string,
userId: string,
teamId: string,
) {
return db.query.teamJoinRequest.findFirst({
where: and(
eq(teamJoinRequest.id, requestId),
eq(teamJoinRequest.userId, userId),
eq(teamJoinRequest.teamId, teamId),
),
});
}
export async function getJoinTeamRequestAdmin(
requestId: string,
teamId: string,
) {
return db.query.teamJoinRequest.findFirst({
where: and(
eq(teamJoinRequest.id, requestId),
eq(teamJoinRequest.teamId, teamId),
),
});
}
// TODO: This function is lowkey pivotal so we should ensure it is WAI.
export async function isUserSiteAdminOrQueryHasPermissions<T = unknown>(
userSiteRole: SiteRoleType,
// Accept either a Promise (already invoked query) or a function that returns a Promise
query: Promise<T> | (() => Promise<T>),
): Promise<boolean> {
if (isSiteAdminUser(userSiteRole)) {
return true;
}
const result = typeof query === "function" ? await query() : await query;
return !!result;
}
export async function logError(message: string, c?: Context) {
const options = getAllContextValues(c);
await logToDb("ERROR", message, options);
}
export async function logInfo(message: string, c?: Context) {
const options = getAllContextValues(c);
await logToDb("INFO", message, options);
}
export async function logWarning(message: string, c?: Context) {
const options = getAllContextValues(c);
await logToDb("WARNING", message, options);
}
export async function logToDb(
loggingType: LoggingType,
message: string,
options?: LoggingOptions,
) {
if (isInDevMode()) {
console.log(`[${loggingType}] - ${message} - Options: `, options);
return;
}
try {
await db.insert(log).values({
...options,
logType: loggingType,
message,
});
} catch (e) {
// Silently fail if logging to the db fails.
console.error("Failed to log to database: ", e);
}
}
function getAllContextValues(c?: Context): LoggingOptions | undefined {
if (!c) {
return undefined;
}
const user = c.get("user") as UserType;
return {
route: c.req.path,
userId: user?.id || null,
teamId: c.get("teamId"),
requestId: c.get("requestId"),
};
}
/**
* Safely extract an error code string from an unknown thrown value from a db error.
* Returns the code as a string when present, otherwise null.
*
* This function can handle it being passed as either a number or string and will convert if need be
*/
export function maybeGetDbErrorCode(e: unknown): string | null {
if (e == null) return null;
if (typeof e === "object") {
const anyE = e as Record<string, unknown>;
const errorCauseKey = anyE["cause"];
if (errorCauseKey && typeof errorCauseKey === "object") {
const codeKey = (errorCauseKey as Record<string, unknown>)["code"];
if (typeof codeKey === "string") {
return codeKey;
} else if (typeof codeKey === "number") {
return codeKey.toString();
}
}
}
return null;
}