-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathEnvironmentVariablesPresenter.server.ts
More file actions
215 lines (191 loc) · 7.1 KB
/
Copy pathEnvironmentVariablesPresenter.server.ts
File metadata and controls
215 lines (191 loc) · 7.1 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
import { $replica, PrismaClient, PrismaReplicaClient, prisma } from "~/db.server";
import { Project } from "~/models/project.server";
import { User } from "~/models/user.server";
import { EnvironmentVariablesRepository } from "~/v3/environmentVariables/environmentVariablesRepository.server";
import type { EnvironmentVariableUpdater } from "~/v3/environmentVariables/repository";
import {
SyncEnvVarsMapping,
EnvSlug,
} from "~/v3/vercel/vercelProjectIntegrationSchema";
import { VercelIntegrationService } from "~/services/vercelIntegration.server";
import { loadEnvironmentVariablesEnvironments } from "./environmentVariablesEnvironments.server";
type Result = Awaited<ReturnType<EnvironmentVariablesPresenter["call"]>>;
export type EnvironmentVariableWithSetValues = Result["environmentVariables"][number];
export class EnvironmentVariablesPresenter {
#prismaClient: PrismaClient;
#replicaClient: PrismaReplicaClient;
constructor(prismaClient: PrismaClient = prisma, replicaClient: PrismaReplicaClient = $replica) {
this.#prismaClient = prismaClient;
this.#replicaClient = replicaClient;
}
public async call({ userId, projectSlug }: { userId: User["id"]; projectSlug: Project["slug"] }) {
const project = await this.#replicaClient.project.findFirst({
select: {
id: true,
},
where: {
slug: projectSlug,
organization: {
members: {
some: {
userId,
},
},
},
},
});
if (!project) {
throw new Error("Project not found");
}
const { environments: sortedEnvironments, hasStaging } =
await loadEnvironmentVariablesEnvironments(
this.#replicaClient,
{ userId, projectId: project.id },
{ skipProjectAccessCheck: true }
);
// Only load values for the environments we display. Projects can accumulate
// values in archived branch environments, which would otherwise all be loaded here.
const environmentIds = sortedEnvironments.map((env) => env.id);
const environmentVariables = await this.#replicaClient.environmentVariable.findMany({
select: {
id: true,
key: true,
values: {
select: {
id: true,
environmentId: true,
version: true,
lastUpdatedBy: true,
updatedAt: true,
valueReference: {
select: {
key: true,
},
},
isSecret: true,
},
where: {
environmentId: {
in: environmentIds,
},
},
},
},
where: {
projectId: project.id,
},
});
const userIds = new Set(
environmentVariables
.flatMap((envVar) => envVar.values)
.map((value) => value.lastUpdatedBy)
.filter(
(lastUpdatedBy): lastUpdatedBy is { type: "user"; userId: string } =>
lastUpdatedBy !== null &&
typeof lastUpdatedBy === "object" &&
"type" in lastUpdatedBy &&
lastUpdatedBy.type === "user" &&
"userId" in lastUpdatedBy &&
typeof lastUpdatedBy.userId === "string"
)
.map((lastUpdatedBy) => lastUpdatedBy.userId)
);
const users =
userIds.size > 0
? await this.#replicaClient.user.findMany({
where: {
id: {
in: Array.from(userIds),
},
},
select: {
id: true,
name: true,
displayName: true,
avatarUrl: true,
},
})
: [];
const usersRecord: Record<string, { id: string; name: string | null; displayName: string | null; avatarUrl: string | null }> =
Object.fromEntries(users.map((u) => [u.id, u]));
const repository = new EnvironmentVariablesRepository(this.#prismaClient, this.#replicaClient);
const nonSecretItems: Array<{ environmentId: string; key: string }> = [];
for (const environmentVariable of environmentVariables) {
for (const env of sortedEnvironments) {
const valueRecord = environmentVariable.values.find((v) => v.environmentId === env.id);
if (valueRecord && !valueRecord.isSecret) {
nonSecretItems.push({ environmentId: env.id, key: environmentVariable.key });
}
}
}
const variableValuesByEnvAndKey = await repository.getVariableValuesForKeys(
project.id,
nonSecretItems
);
// Get Vercel integration data if it exists
const vercelService = new VercelIntegrationService(this.#prismaClient);
const vercelIntegration = await vercelService.getVercelProjectIntegration(project.id);
let vercelSyncEnvVarsMapping: SyncEnvVarsMapping = {};
let vercelPullEnvVarsBeforeBuild: EnvSlug[] | null = null;
if (vercelIntegration) {
vercelSyncEnvVarsMapping = vercelIntegration.parsedIntegrationData.syncEnvVarsMapping;
vercelPullEnvVarsBeforeBuild = vercelIntegration.parsedIntegrationData.config.pullEnvVarsBeforeBuild ?? null;
}
return {
environmentVariables: environmentVariables
.flatMap((environmentVariable) => {
return sortedEnvironments.flatMap((env) => {
const valueRecord = environmentVariable.values.find((v) => v.environmentId === env.id);
const isSecret = valueRecord?.isSecret ?? false;
if (!valueRecord) {
return [];
}
const val = isSecret
? undefined
: variableValuesByEnvAndKey.get(`${env.id}:${environmentVariable.key}`);
if (!isSecret && val === undefined) {
return [];
}
const lastUpdatedBy = valueRecord.lastUpdatedBy as EnvironmentVariableUpdater | null;
const updatedByUser =
lastUpdatedBy?.type === "user"
? (() => {
const user = usersRecord[lastUpdatedBy.userId];
return user
? {
id: user.id,
name: user.displayName || user.name || "Unknown",
avatarUrl: user.avatarUrl,
}
: null;
})()
: null;
return [
{
id: environmentVariable.id,
key: environmentVariable.key,
environment: { type: env.type, id: env.id, branchName: env.branchName },
value: isSecret ? "" : val!,
isSecret,
version: valueRecord.version,
lastUpdatedBy,
updatedByUser,
updatedAt: valueRecord.updatedAt,
},
];
});
})
.sort((a, b) => a.key.localeCompare(b.key)),
environments: sortedEnvironments,
hasStaging,
// Vercel integration data
vercelIntegration: vercelIntegration
? {
enabled: true,
pullEnvVarsBeforeBuild: vercelPullEnvVarsBeforeBuild,
syncEnvVarsMapping: vercelSyncEnvVarsMapping,
}
: null,
};
}
}