-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathLayoutController.js
More file actions
301 lines (281 loc) · 10.8 KB
/
LayoutController.js
File metadata and controls
301 lines (281 loc) · 10.8 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/**
* @license
* Copyright 2019-2020 CERN and copyright holders of ALICE O2.
* See http://alice-o2.web.cern.ch/copyright for details of the copyright holders.
* All rights not expressly granted are reserved.
*
* This software is distributed under the terms of the GNU General Public
* License v3 (GPL Version 3), copied verbatim in the file "COPYING".
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
'use strict';
import assert from 'assert';
import { LayoutDto, LayoutsGetDto } from './../dtos/LayoutDto.js';
import { LayoutPatchDto } from './../dtos/LayoutPatchDto.js';
import {
InvalidInputError,
LogManager,
NotFoundError,
updateAndSendExpressResponseFromNativeError,
}
from '@aliceo2/web-ui';
import { parseRequestToConfig, parseRequestToLayout } from '../utils/download/configurator.js';
import { MapStorage } from '../utils/download/classes/domain/MapStorage.js';
import { download, saveDownloadData } from '../utils/download/downloadEngine.js';
/**
* @typedef {import('../repositories/LayoutRepository.js').LayoutRepository} LayoutRepository
*/
const logger = LogManager.getLogger(`${process.env.npm_config_log_label ?? 'qcg'}/layout-ctrl`);
const mapStorage = new MapStorage();
/**
* Gateway for all HTTP requests with regards to QCG Layouts
*/
export class LayoutController {
/**
* Setup Layout Controller:
* @param {LayoutRepository} layoutRepository - The repository for layout data
*/
constructor(layoutRepository) {
assert(layoutRepository, 'Missing layout repository');
/**
* @type {LayoutRepository}
*/
this._layoutRepository = layoutRepository;
}
/**
* HTTP GET endpoint for retrieving a list of layouts
* * Can be filtered by "owner_id" or "objectPath" using filter.objectPath
* * if no owner_id is provided, all layouts will be fetched;
* @param {Request} req - HTTP request object with information on owner_id
* @param {Response} res - HTTP response object to provide layouts information
* @returns {undefined}
*/
async getLayoutsHandler(req, res) {
let fields = undefined;
let owner_id = undefined;
let filter = undefined;
try {
const validated = await LayoutsGetDto.validateAsync(req.query);
({ fields, owner_id, filter } = validated);
} catch (error) {
const responseError = error.isJoi ?
new InvalidInputError(`Invalid query parameters: ${error.details[0].message}`) :
new Error('Unable to process request');
logger.errorMessage(`Error validating query parameters: ${error}`);
return updateAndSendExpressResponseFromNativeError(res, responseError);
}
try {
const layouts = await this._layoutRepository.listLayouts({ fields, filter: { ...filter, owner_id } });
return res.status(200).json(layouts);
} catch (error) {
logger.errorMessage(`Error retrieving layouts: ${error}`);
return updateAndSendExpressResponseFromNativeError(res, new Error('Unable to retrieve layouts'));
}
}
/**
* HTTP GET endpoint for retrieving a single layout specified by layout "id";
* @param {Request} req - HTTP request object with "params" information on layout ID
* @param {Response} res - HTTP response object to provide layout information
* @returns {undefined}
*/
async getLayoutHandler(req, res) {
const { id } = req.params;
if (!id.trim()) {
updateAndSendExpressResponseFromNativeError(res, new InvalidInputError('Missing parameter "id" of layout'));
} else {
try {
const layout = await this._layoutRepository.readLayoutById(id);
res.status(200).json(layout);
} catch (error) {
updateAndSendExpressResponseFromNativeError(res, error);
}
}
}
/**
* HTTP GET endpoint for retrieving a single layout via query parameters. Either by:
* * name (e.g. CALIBRATIONS)
* * runDefinition + pdpBeamMode
* @param {Request} req - HTTP request object with "params" information on layout ID
* @param {Response} res - HTTP response object to provide layout information
* @returns {undefined}
*/
async getLayoutByNameHandler(req, res) {
const { name, runDefinition, pdpBeamType } = req.query;
let layoutName = '';
if (name) {
layoutName = name;
} else if (runDefinition && pdpBeamType) {
layoutName = `${runDefinition}_${pdpBeamType}`;
} else if (runDefinition) {
layoutName = runDefinition;
} else {
updateAndSendExpressResponseFromNativeError(res, new InvalidInputError('Missing query parameters'));
return;
}
try {
const layout = await this._layoutRepository.readLayoutByName(layoutName);
res.status(200).json(layout);
} catch (error) {
updateAndSendExpressResponseFromNativeError(res, error);
}
}
/**
* HTTP PUT endpoint for updating a single layout specified by:
* * query.id for identification
* * body - for layout data to be updated
* @param {Request} req - HTTP request object with "query" and "body" information on layout
* @param {Response} res - HTTP response object to provide information on the update
* @returns {undefined}
*/
async putLayoutHandler(req, res) {
const { id } = req.params;
let layoutProposed = {};
try {
layoutProposed = await LayoutDto.validateAsync(req.body);
} catch (error) {
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError(`Failed to update layout: ${error?.details?.[0]?.message || ''}`),
);
return;
}
try {
const layouts = await this._layoutRepository.listLayouts({ name: layoutProposed.name });
const layoutExistsWithName = layouts.every((layout) => layout.id !== layoutProposed.id);
if (layouts.length > 0 && layoutExistsWithName) {
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError(`Proposed layout name: ${layoutProposed.name} already exists`),
);
return;
}
const layout = await this._layoutRepository.updateLayout(id, layoutProposed);
res.status(201).json({ id: layout });
} catch (error) {
updateAndSendExpressResponseFromNativeError(res, error);
}
}
/**
* HTTP DELETE endpoint to allow removal a single layout specified by its id
* @param {Request} req - HTTP request object with "params" information on layout ID
* @param {Response} res - HTTP response object to inform client if deletion was successful
* @returns {undefined}
*/
async deleteLayoutHandler(req, res) {
const { id } = req.params;
try {
const result = await this._layoutRepository.deleteLayout(id);
res.status(200).json(result);
} catch {
updateAndSendExpressResponseFromNativeError(res, new Error(`Unable to delete layout with id: ${id}`));
}
}
/**
* HTTP POST endpoint that validates received payload follows a layout format and if successful, stores it
* @param {Request} req - HTTP request object with "body" information on layout to be created
* @param {Response} res - HTTP request object with result of the action
* @returns {undefined}
*/
async postLayoutHandler(req, res) {
let layoutProposed = {};
try {
layoutProposed = await LayoutDto.validateAsync(req.body);
} catch (error) {
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError(`Failed to validate layout: ${error?.details[0]?.message || ''}`),
);
return;
}
try {
const layouts = await this._layoutRepository.listLayouts({ name: layoutProposed.name });
if (layouts.length > 0) {
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError(`Proposed layout name: ${layoutProposed.name} already exists`),
);
return;
}
const result = await this._layoutRepository.createLayout(layoutProposed);
res.status(201).json(result);
} catch {
updateAndSendExpressResponseFromNativeError(res, new Error('Unable to create new layout'));
}
}
/**
* Store layout data for later download request.
* @param {Request<import('../utils/download/configurator.js').Query>}req - request
* @param {Response} res - response
*/
async postDownloadHandler(req, res) {
try {
const downloadConfigDomain = parseRequestToConfig(req);
const downloadLayoutDomain = parseRequestToLayout(req);
// Note: if userId becomes 0 it will throw when creating the storagelayout.
const userId = Number(req.query.user_id ?? 0);
const key = saveDownloadData(mapStorage, downloadLayoutDomain, downloadConfigDomain, userId);
logger.infoMessage(`Saved layout key: ${key}`);
res.status(201).send(key);
} catch {
res.status(400).send('Could not save download data');
}
};
/**
* Download objects using key from post download request.
* @param {Request<import('../utils/download/configurator.js').Query>}req - request
* @param {Response} res - response
*/
async getDownloadHandler(req, res) {
const { key } = req.query;
if (key == '') {
res.status(400).send('Key not defined correctly');
}
try {
const downloadLayoutDomain = mapStorage.readRequest(key)?.[0].toSuper();
const downloadConfigDomain = mapStorage.readRequest(key)?.[1];
if (downloadLayoutDomain == undefined || downloadConfigDomain == undefined) {
throw new Error('Layout could not be found with key');
}
// start the download engine
await download(downloadLayoutDomain, downloadConfigDomain, 1234567, res);
} catch (error) {
logger.errorMessage(error?.message ?? error);
res.status(400).send('Could not download objects');
}
}
/**
* Patch a layout entity with information as per LayoutPatchDto.js
* @param {Request} req - HTTP request object with "params" and "body" information on layout
* @param {Response} res - HTTP response object to provide information on the update
* @returns {undefined}
*/
async patchLayoutHandler(req, res) {
const { id } = req.params;
let layout = {};
try {
layout = await LayoutPatchDto.validateAsync(req.body);
} catch (error) {
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError(`Failed to validate layout: ${error?.details[0]?.message || ''}`),
);
return;
}
try {
this._layoutRepository.readLayoutById(id);
} catch {
updateAndSendExpressResponseFromNativeError(res, new NotFoundError(`Unable to find layout with id: ${id}`));
return;
}
try {
const updatedLayoutId = await this._layoutRepository.updateLayout(id, layout);
res.status(201).json({ id: updatedLayoutId });
} catch {
updateAndSendExpressResponseFromNativeError(res, new Error(`Unable to update layout with id: ${id}`));
return;
}
}
}