1
/**
2
 * Date & time utility functions to abstract the `aws-sdk` away from users.
3
 * (v2 => v3 modularization is a breaking change)
4
 *
5
 * @see https://github.com/aws/aws-sdk-js/blob/6edf586dcc1de7fe8fbfbbd9a0d2b1847921e6e1/lib/util.js#L262
6
 */
7

8 1
const FIVE_MINUTES_IN_MS = 1000 * 60 * 5;
9

10 1
export const DateUtils = {
11
	/**
12
	 * Milliseconds to offset the date to compensate for clock skew between device & services
13
	 */
14
	clockOffset: 0,
15

16
	getDateWithClockOffset() {
17 1
		if (DateUtils.clockOffset) {
18 0
			return new Date(new Date().getTime() + DateUtils.clockOffset);
19
		} else {
20 1
			return new Date();
21
		}
22
	},
23

24
	/**
25
	 * @returns {number} Clock offset in milliseconds
26
	 */
27
	getClockOffset() {
28 1
		return DateUtils.clockOffset;
29
	},
30

31 1
	getHeaderStringFromDate(date: Date = DateUtils.getDateWithClockOffset()) {
32 1
		return date.toISOString().replace(/[:\-]|\.\d{3}/g, '');
33
	},
34

35
	getDateFromHeaderString(header: string) {
36 1
		const [, year, month, day, hour, minute, second] = header.match(
37
			/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2}).+/
38
		);
39

40 1
		return new Date(
41
			Date.UTC(
42
				Number(year),
43
				Number(month) - 1,
44
				Number(day),
45
				Number(hour),
46
				Number(minute),
47
				Number(second)
48
			)
49
		);
50
	},
51

52
	isClockSkewed(serverDate: Date) {
53
		// API gateway permits client calls that are off by no more than ±5 minutes
54 1
		return (
55
			Math.abs(
56
				serverDate.getTime() - DateUtils.getDateWithClockOffset().getTime()
57
			) >= FIVE_MINUTES_IN_MS
58
		);
59
	},
60

61
	isClockSkewError(error: any) {
62 1
		if (!error.response || !error.response.headers) {
63 1
			return false;
64
		}
65

66 1
		const { headers } = error.response;
67

68 1
		return Boolean(
69 1
			headers['x-amzn-errortype'] === 'BadRequestException' &&
70
				(headers.date || headers.Date)
71
		);
72
	},
73

74
	/**
75
	 * @param {number} offset Clock offset in milliseconds
76
	 */
77
	setClockOffset(offset: number) {
78 0
		DateUtils.clockOffset = offset;
79
	},
80
};

Read our documentation on viewing source code .

Loading