-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
86 lines (71 loc) · 2.61 KB
/
index.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
84
85
86
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBPersistence } from './src/DynamoDBPersistence';
import { Config, Idempotency, md5 } from './src/Idempotency';
import { IdempotencyError, UseCaseAlreadyInProgressError } from './src/Errors';
type Input = {
name: string;
age: number;
createdAt: Date;
}
type Result = {
id: number;
name: string;
age: number;
};
const config: Config = {
ttl: 10,
customHashCalculator: (input: Input) => {
const hash = md5(JSON.stringify({
name: input.name,
age: input.age,
}));
return hash;
}
}
const idempotency = new Idempotency(new DynamoDBPersistence(new DynamoDBClient({ region: 'us-east-1', endpoint: 'http://localhost:8000'}), { ttl: config.ttl, tableName: 'idempotency' }), config);
// The use case we would execute
const myUseCase = (input: Input): Result => {
console.log('Executing use case: ', input);
return {
id: 1,
name: input.name,
age: input.age
};
}
(async () => {
console.log('Now: ', new Date().toISOString());
const useCase = 'my-use-case';
let input: Input = {
name: 'John Doe Dorian',
age: 19,
createdAt: new Date()
};
let result: Result | undefined;
try {
// Start the idempotency process
result = await idempotency.add<Result>(useCase, input);
if (result === undefined) {
// execute the use case
result = myUseCase(input);
// Complete the idempotency process - we pass the result so it can be stored in the persistence layer
await idempotency.complete(useCase, input, result);
}
// Do your application normal flow and return the result
console.log('Result => ', result);
} catch(e) {
// Either the use case is still in progress or it failed altogether
if (e.code != 'UseCaseAlreadyInProgress') {
// Since it is not in progress, the use case failed.
// We remove the idempotency record so we can try again
await idempotency.remove(useCase, input);
// Do your application normal error handling
console.log('Error: ', e);
// Return an error indicating the use case failed
console.log({ code: 500, message: `Internal server error: ${e.message}` });
return;
}
// Return an error indicating the use case is still being executed
console.log('Use case is still being executed');
console.log({ code: 409, message: 'Use case is still being executed' });
}
})();