@aws-lambda-powertools/idempotency
Version:
The idempotency package for the Powertools for AWS Lambda (TypeScript) library. It provides options to make your Lambda functions idempotent and safe to retry.
76 lines (75 loc) • 2.52 kB
JavaScript
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 seconds UTC.
*/
expiryTimestamp;
/**
* The idempotency key of the record that is used to identify the record.
*/
idempotencyKey;
/**
* An optional sort key that can be used with the {@link DynamoDBPersistenceLayer | `DynamoDBPersistenceLayer`}.
*/
sortKey;
/**
* The expiry timestamp of the in progress record in milliseconds UTC.
*/
inProgressExpiryTimestamp;
/**
* The hash of the payload of the request, used for comparing requests.
*/
payloadHash;
/**
* The response data of the request, this will be returned if the payload hash matches.
*/
responseData;
/**
* 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 constants.IdempotencyRecordStatusValue | IdempotencyRecordStatusValue}
* @private
*/
status;
constructor(config) {
this.idempotencyKey = config.idempotencyKey;
this.expiryTimestamp = config.expiryTimestamp;
this.inProgressExpiryTimestamp = config.inProgressExpiryTimestamp;
this.responseData = config.responseData;
this.payloadHash = config.payloadHash;
this.status = config.status;
this.sortKey = config.sortKey;
}
/**
* Get the response data of the record.
*/
getResponse() {
return this.responseData;
}
/**
* Get the status of the record.
* @throws {IdempotencyInvalidStatusError} If the status is not a valid status.
*/
getStatus() {
if (this.isExpired()) {
return IdempotencyRecordStatus.EXPIRED;
}
if (Object.values(IdempotencyRecordStatus).includes(this.status)) {
return this.status;
}
throw new IdempotencyInvalidStatusError(this.status);
}
/**
* Returns true if the record is expired or undefined.
*/
isExpired() {
return (this.expiryTimestamp !== undefined &&
Date.now() / 1000 > this.expiryTimestamp);
}
}
export { IdempotencyRecord };