-
Notifications
You must be signed in to change notification settings - Fork 128
/
IdempotencyRecord.ts
83 lines (77 loc) · 2.52 KB
/
IdempotencyRecord.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
import type { JSONValue } from '@aws-lambda-powertools/commons/types';
import type {
IdempotencyRecordOptions,
IdempotencyRecordStatusValue,
} from '../types/IdempotencyRecord.js';
import { IdempotencyRecordStatus } from '../constants.js';
import { IdempotencyInvalidStatusError } from '../errors.js';
/**
* Class representing an idempotency record.
* The properties of this class will be reflected in the persistence layer.
*/
class IdempotencyRecord {
/**
* The expiry timestamp of the record in milliseconds UTC.
*/
public expiryTimestamp?: number;
/**
* The idempotency key of the record that is used to identify the record.
*/
public idempotencyKey: string;
/**
* The expiry timestamp of the in progress record in milliseconds UTC.
*/
public inProgressExpiryTimestamp?: number;
/**
* The hash of the payload of the request, used for comparing requests.
*/
public payloadHash?: string;
/**
* The response data of the request, this will be returned if the payload hash matches.
*/
public responseData?: JSONValue;
/**
* The idempotency record status can be COMPLETED, IN_PROGRESS or EXPIRED.
* We check the status during idempotency processing to make sure we don't process an expired record and handle concurrent requests.
* @link {IdempotencyRecordStatusValue}
* @private
*/
private status: IdempotencyRecordStatusValue;
public constructor(config: IdempotencyRecordOptions) {
this.idempotencyKey = config.idempotencyKey;
this.expiryTimestamp = config.expiryTimestamp;
this.inProgressExpiryTimestamp = config.inProgressExpiryTimestamp;
this.responseData = config.responseData;
this.payloadHash = config.payloadHash;
this.status = config.status;
}
/**
* Get the response data of the record.
*/
public getResponse(): JSONValue {
return this.responseData;
}
/**
* Get the status of the record.
* @throws {IdempotencyInvalidStatusError} If the status is not a valid status.
*/
public getStatus(): IdempotencyRecordStatusValue {
if (this.isExpired()) {
return IdempotencyRecordStatus.EXPIRED;
} else if (Object.values(IdempotencyRecordStatus).includes(this.status)) {
return this.status;
} else {
throw new IdempotencyInvalidStatusError(this.status);
}
}
/**
* Returns true if the record is expired or undefined.
*/
public isExpired(): boolean {
return (
this.expiryTimestamp !== undefined &&
Date.now() / 1000 > this.expiryTimestamp
);
}
}
export { IdempotencyRecord };