UNPKG

1.42 kBPlain TextView Raw
1// Copyright (c) .NET Foundation. All rights reserved.
2// Licensed under the MIT License.
3
4import { RpcDuration } from '@azure/functions-core';
5import { Duration } from '../../types';
6import { AzFuncSystemError } from '../errors';
7import { isDefined } from '../utils/nonNull';
8
9export function toRpcDuration(dateTime: Duration | number | undefined, propertyName: string): RpcDuration | undefined {
10 if (isDefined(dateTime)) {
11 try {
12 let timeInMilliseconds: number | undefined;
13 if (typeof dateTime === 'object') {
14 const minutes = (dateTime.minutes || 0) + (dateTime.hours || 0) * 60;
15 const seconds = (dateTime.seconds || 0) + minutes * 60;
16 timeInMilliseconds = (dateTime.milliseconds || 0) + seconds * 1000;
17 } else if (typeof dateTime === 'number') {
18 timeInMilliseconds = dateTime;
19 }
20
21 if (isDefined(timeInMilliseconds) && timeInMilliseconds >= 0) {
22 return {
23 seconds: Math.round(timeInMilliseconds / 1000),
24 };
25 }
26 } catch {
27 // fall through
28 }
29
30 throw new AzFuncSystemError(
31 `A 'number' or 'Duration' object was expected instead of a '${typeof dateTime}'. Cannot parse value of '${propertyName}'.`
32 );
33 }
34
35 return undefined;
36}