-
-
Notifications
You must be signed in to change notification settings - Fork 736
/
export-import-controller.ts
226 lines (206 loc) · 8.45 KB
/
export-import-controller.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
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
import { Response } from 'express';
import Controller from '../../routes/controller';
import { Logger } from '../../logger';
import ExportImportService from './export-import-service';
import { OpenApiService } from '../../services';
import {
TransactionCreator,
UnleashTransaction,
WithTransactional,
} from '../../db/transaction';
import {
IUnleashConfig,
IUnleashServices,
NONE,
serializeDates,
} from '../../types';
import {
createRequestSchema,
createResponseSchema,
emptyResponse,
ExportQuerySchema,
exportResultSchema,
getStandardResponses,
ImportTogglesSchema,
importTogglesValidateSchema,
} from '../../openapi';
import { IAuthRequest } from '../../routes/unleash-types';
import { extractUsername } from '../../util';
import { BadDataError, InvalidOperationError } from '../../error';
import ApiUser from '../../types/api-user';
class ExportImportController extends Controller {
private logger: Logger;
/** @deprecated gradually rolling out exportImportV2 */
private exportImportService: ExportImportService;
/** @deprecated gradually rolling out exportImportV2 */
private transactionalExportImportService: (
db: UnleashTransaction,
) => ExportImportService;
private exportImportServiceV2: WithTransactional<ExportImportService>;
private openApiService: OpenApiService;
/** @deprecated gradually rolling out exportImportV2 */
private readonly startTransaction: TransactionCreator<UnleashTransaction>;
constructor(
config: IUnleashConfig,
{
exportImportService,
transactionalExportImportService,
exportImportServiceV2,
openApiService,
}: Pick<
IUnleashServices,
| 'exportImportService'
| 'exportImportServiceV2'
| 'openApiService'
| 'transactionalExportImportService'
>,
startTransaction: TransactionCreator<UnleashTransaction>,
) {
super(config);
this.logger = config.getLogger('/admin-api/export-import.ts');
this.exportImportService = exportImportService;
this.transactionalExportImportService =
transactionalExportImportService;
this.exportImportServiceV2 = exportImportServiceV2;
this.startTransaction = startTransaction;
this.openApiService = openApiService;
this.route({
method: 'post',
path: '/export',
permission: NONE,
handler: this.export,
middleware: [
this.openApiService.validPath({
tags: ['Import/Export'],
operationId: 'exportFeatures',
requestBody: createRequestSchema('exportQuerySchema'),
responses: {
200: createResponseSchema('exportResultSchema'),
...getStandardResponses(404),
},
description:
"Exports all features listed in the `features` property from the environment specified in the request body. If set to `true`, the `downloadFile` property will let you download a file with the exported data. Otherwise, the export data is returned directly as JSON. Refer to the documentation for more information about [Unleash's export functionality](https://docs.getunleash.io/reference/deploy/environment-import-export#export).",
summary: 'Export feature toggles from an environment',
}),
],
});
this.route({
method: 'post',
path: '/validate',
permission: NONE,
handler: this.validateImport,
middleware: [
openApiService.validPath({
tags: ['Import/Export'],
operationId: 'validateImport',
requestBody: createRequestSchema('importTogglesSchema'),
responses: {
200: createResponseSchema(
'importTogglesValidateSchema',
),
...getStandardResponses(404),
},
summary: 'Validate feature import data',
description: `Validates a feature toggle data set. Checks whether the data can be imported into the specified project and environment. The returned value is an object that contains errors, warnings, and permissions required to perform the import, as described in the [import documentation](https://docs.getunleash.io/reference/deploy/environment-import-export#import).`,
}),
],
});
this.route({
method: 'post',
path: '/import',
permission: NONE,
handler: this.importData,
middleware: [
openApiService.validPath({
tags: ['Import/Export'],
operationId: 'importToggles',
requestBody: createRequestSchema('importTogglesSchema'),
responses: {
200: emptyResponse,
...getStandardResponses(404),
},
summary: 'Import feature toggles',
description: `[Import feature toggles](https://docs.getunleash.io/reference/deploy/environment-import-export#import) into a specific project and environment.`,
}),
],
});
}
async export(
req: IAuthRequest<unknown, unknown, ExportQuerySchema, unknown>,
res: Response,
): Promise<void> {
this.verifyExportImportEnabled();
const query = req.body;
const userName = extractUsername(req);
const useTransactionalDecorator = this.config.flagResolver.isEnabled(
'transactionalDecorator',
);
const data = useTransactionalDecorator
? await this.exportImportServiceV2.export(query, userName)
: await this.exportImportService.export(query, userName);
this.openApiService.respondWithValidation(
200,
res,
exportResultSchema.$id,
serializeDates(data),
);
}
async validateImport(
req: IAuthRequest<unknown, unknown, ImportTogglesSchema, unknown>,
res: Response,
): Promise<void> {
this.verifyExportImportEnabled();
const dto = req.body;
const { user } = req;
const useTransactionalDecorator = this.config.flagResolver.isEnabled(
'transactionalDecorator',
);
const validation = useTransactionalDecorator
? await this.exportImportServiceV2.transactional((service) =>
service.validate(dto, user),
)
: await this.startTransaction(async (tx) =>
this.transactionalExportImportService(tx).validate(dto, user),
);
this.openApiService.respondWithValidation(
200,
res,
importTogglesValidateSchema.$id,
validation,
);
}
async importData(
req: IAuthRequest<unknown, unknown, ImportTogglesSchema, unknown>,
res: Response,
): Promise<void> {
this.verifyExportImportEnabled();
const { user } = req;
if (user instanceof ApiUser && user.type === 'admin') {
throw new BadDataError(
`You can't use an admin token to import features. Please use either a personal access token (https://docs.getunleash.io/reference/api-tokens-and-client-keys#personal-access-tokens) or a service account (https://docs.getunleash.io/reference/service-accounts).`,
);
}
const dto = req.body;
const useTransactionalDecorator = this.config.flagResolver.isEnabled(
'transactionalDecorator',
);
if (useTransactionalDecorator) {
await this.exportImportServiceV2.transactional((service) =>
service.import(dto, user),
);
} else {
await this.startTransaction(async (tx) =>
this.transactionalExportImportService(tx).import(dto, user),
);
}
res.status(200).end();
}
private verifyExportImportEnabled() {
if (!this.config.flagResolver.isEnabled('featuresExportImport')) {
throw new InvalidOperationError(
'Feature export/import is not enabled',
);
}
}
}
export default ExportImportController;