|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright CERN and copyright holders of ALICE O2. This software is |
| 4 | + * distributed under the terms of the GNU General Public License v3 (GPL |
| 5 | + * Version 3), copied verbatim in the file "COPYING". |
| 6 | + * |
| 7 | + * See http://alice-o2.web.cern.ch/license for full licensing information. |
| 8 | + * |
| 9 | + * In applying this license CERN does not waive the privileges and immunities |
| 10 | + * granted to it by virtue of its status as an Intergovernmental Organization |
| 11 | + * or submit itself to any jurisdiction. |
| 12 | + */ |
| 13 | +import Joi from 'joi'; |
| 14 | +import { NUMERICAL_COMPARISON_OPERATORS } from '../domain/dtos/filters/NumericalComparisonDto.js'; |
| 15 | + |
| 16 | +const joiTimeDurationErrorText = 'Invalid duration value'; |
| 17 | + |
| 18 | +/** |
| 19 | + * Transform digital time in string format |
| 20 | + * |
| 21 | + * @param {string} incomingValue The time to transform |
| 22 | + * @param {*} helpers The Joi helpers object |
| 23 | + * @returns {number|import("joi").ValidationError} The value if transformation passes, as seconds (Number) |
| 24 | + */ |
| 25 | +export const transformTime = (incomingValue, helpers) => { |
| 26 | + try { |
| 27 | + // Extract time to seconds... |
| 28 | + const [hoursStr, minutesStr, secondsStr] = incomingValue.split(':'); |
| 29 | + |
| 30 | + const hours = Number(hoursStr); |
| 31 | + const minutes = Number(minutesStr); |
| 32 | + const seconds = Number(secondsStr); |
| 33 | + |
| 34 | + return hours * 3600 + minutes * 60 + seconds; |
| 35 | + } catch (error) { |
| 36 | + return helpers.error('any.invalid', { message: `Validation error: ${error?.message ?? 'failed to transform time'}` }); |
| 37 | + } |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * Joi object that validates time duration filters. |
| 42 | + * This is for duration, not a point in time. 10000:59:59 is valid. |
| 43 | + * The operator is also validated. |
| 44 | + */ |
| 45 | +export const validateTimeDuration = Joi.object({ |
| 46 | + limit: Joi.string().trim().pattern(/^\d+:[0-5]?\d:[0-5]?\d$/).custom(transformTime).messages({ |
| 47 | + 'string.pattern.base': joiTimeDurationErrorText, |
| 48 | + 'string.base': joiTimeDurationErrorText, |
| 49 | + }), |
| 50 | + operator: Joi.string().valid(...NUMERICAL_COMPARISON_OPERATORS), |
| 51 | +}); |
0 commit comments