@hexafy/core 1.0.0-rc.0 → 1.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -304
- package/package.json +3 -2
- package/dist/application.d.mts +0 -170
- package/dist/application.d.mts.map +0 -1
- package/dist/application.mjs +0 -146
- package/dist/application.mjs.map +0 -1
- package/dist/domain.d.mts +0 -500
- package/dist/domain.d.mts.map +0 -1
- package/dist/domain.mjs +0 -350
- package/dist/domain.mjs.map +0 -1
- package/dist/infrastructure.d.mts +0 -38
- package/dist/infrastructure.d.mts.map +0 -1
- package/dist/infrastructure.mjs +0 -98
- package/dist/infrastructure.mjs.map +0 -1
- package/dist/metrics.port-CfI8yKMA.d.mts +0 -114
- package/dist/metrics.port-CfI8yKMA.d.mts.map +0 -1
- package/dist/noop.metrics.adapter-MgMrk-sq.mjs +0 -53
- package/dist/noop.metrics.adapter-MgMrk-sq.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -1,370 +1,129 @@
|
|
|
1
1
|
# @hexafy/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small, opinionated toolkit for building hexagonal architecture applications in TypeScript.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-

|
|
5
|
+
This package gives you the core building blocks for domain logic, application use cases, repositories, and error handling without bringing in a framework.
|
|
7
6
|
|
|
8
|
-
##
|
|
7
|
+
## What it includes
|
|
9
8
|
|
|
10
|
-
|
|
9
|
+
- `Usecase` base class for application logic
|
|
10
|
+
- `UsecaseResult` helpers: `success`, `failure`, `unwrap`, `isSuccess`, `isFailure`
|
|
11
|
+
- domain error types such as `ValidationError`, `NotFoundError`, `ConflictError`, and `ApplicationError`
|
|
12
|
+
- repository and unit-of-work base abstractions
|
|
13
|
+
- logging, clock, identifier, and metrics ports with adapters
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
- **Result Types** — Explicit error handling without exceptions for domain errors
|
|
14
|
-
- **Repositories** — Clean data access abstraction
|
|
15
|
-
- **Unit of Work** — Transactional boundary management
|
|
16
|
-
- **Logger Ports** — Optional structured logging with no-op fallback
|
|
17
|
-
|
|
18
|
-
## ✨ Why Use It?
|
|
19
|
-
|
|
20
|
-
### Problems Solved
|
|
21
|
-
|
|
22
|
-
| Problem | Solution |
|
|
23
|
-
| ------------------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
24
|
-
| Mixed exception/return error patterns | **Explicit `Result` type** — all domain errors handled consistently |
|
|
25
|
-
| Logging setup complexity | **Built-in NOOP logger** — works immediately, opt-in to structured logging |
|
|
26
|
-
| Use case boilerplate | **`Usecase` base class** — handles logging, metrics, and error wrapping automatically |
|
|
27
|
-
| Unclear error boundaries | **Domain vs Infrastructure separation** — domain errors returned, infrastructure errors thrown |
|
|
28
|
-
|
|
29
|
-
### Key Benefits
|
|
30
|
-
|
|
31
|
-
- ✅ **Type-safe error handling** — No more `any` exceptions for expected failures
|
|
32
|
-
- ✅ **Zero-config logging** — Works out of the box, switches to NOOP when disabled
|
|
33
|
-
- ✅ **Consistent patterns** — Same approach across your entire codebase
|
|
34
|
-
- ✅ **Testing friendly** — Dependencies are optional and injectable
|
|
35
|
-
- ✅ **Production ready** — Automatic execution metrics and structured logging
|
|
36
|
-
|
|
37
|
-
## 📦 Installation
|
|
15
|
+
## Installation
|
|
38
16
|
|
|
39
17
|
```bash
|
|
40
|
-
bun add @hexafy/core
|
|
41
|
-
# or
|
|
42
18
|
npm install @hexafy/core
|
|
43
19
|
# or
|
|
20
|
+
bun add @hexafy/core
|
|
21
|
+
# or
|
|
44
22
|
yarn add @hexafy/core
|
|
45
23
|
```
|
|
46
24
|
|
|
47
|
-
|
|
25
|
+
## Quick start
|
|
48
26
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
### Your First Use Case
|
|
52
|
-
|
|
53
|
-
```typescript
|
|
27
|
+
```ts
|
|
54
28
|
import {
|
|
55
|
-
failure,
|
|
56
|
-
Result,
|
|
57
|
-
success,
|
|
58
29
|
Usecase,
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
} from '@hexafy/core';
|
|
30
|
+
type UsecaseExecutionConfiguration
|
|
31
|
+
} from '@hexafy/core/application';
|
|
32
|
+
import { type LoggerPort, ValidationError } from '@hexafy/core/domain';
|
|
62
33
|
|
|
63
34
|
interface CreateUserInput {
|
|
64
35
|
email: string;
|
|
65
36
|
name: string;
|
|
66
37
|
}
|
|
67
38
|
|
|
68
|
-
interface
|
|
69
|
-
|
|
39
|
+
interface User {
|
|
40
|
+
id: string;
|
|
70
41
|
email: string;
|
|
42
|
+
name: string;
|
|
71
43
|
}
|
|
72
44
|
|
|
73
|
-
class CreateUserUseCase extends Usecase<CreateUserInput,
|
|
74
|
-
constructor(
|
|
75
|
-
super(
|
|
45
|
+
class CreateUserUseCase extends Usecase<CreateUserInput, User> {
|
|
46
|
+
constructor(config?: UsecaseExecutionConfiguration) {
|
|
47
|
+
super(config);
|
|
76
48
|
}
|
|
77
49
|
|
|
78
50
|
protected async executeInternal(
|
|
79
51
|
input: CreateUserInput,
|
|
80
52
|
logger: LoggerPort
|
|
81
|
-
): Promise<
|
|
82
|
-
// Domain validation — return failures, don't throw
|
|
53
|
+
): Promise<User> {
|
|
83
54
|
if (!input.email.includes('@')) {
|
|
84
|
-
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
if (input.name.length < 2) {
|
|
88
|
-
return failure(new ValidationError('Name too short'));
|
|
55
|
+
throw new ValidationError('Invalid email');
|
|
89
56
|
}
|
|
90
57
|
|
|
91
|
-
|
|
92
|
-
const userId = this.dependencies.generateId?.() ?? `user_${Date.now()}`;
|
|
93
|
-
|
|
94
|
-
logger.info('User created', { userId, email: input.email });
|
|
58
|
+
logger.info('User created', { email: input.email });
|
|
95
59
|
|
|
96
|
-
return
|
|
60
|
+
return {
|
|
61
|
+
id: 'user_123',
|
|
62
|
+
email: input.email,
|
|
63
|
+
name: input.name
|
|
64
|
+
};
|
|
97
65
|
}
|
|
98
66
|
}
|
|
99
67
|
|
|
100
|
-
|
|
101
|
-
const useCase = new CreateUserUseCase({});
|
|
68
|
+
const useCase = new CreateUserUseCase();
|
|
102
69
|
const result = await useCase.execute({
|
|
103
70
|
email: 'john@example.com',
|
|
104
71
|
name: 'John'
|
|
105
72
|
});
|
|
106
73
|
|
|
107
74
|
if (result.success) {
|
|
108
|
-
console.log(
|
|
75
|
+
console.log(result.value);
|
|
109
76
|
} else {
|
|
110
|
-
console.error(result.error.message);
|
|
111
|
-
}
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
## 📚 Core Concepts
|
|
115
|
-
|
|
116
|
-
### Result Type
|
|
117
|
-
|
|
118
|
-
Explicit success/failure handling for domain errors:
|
|
119
|
-
|
|
120
|
-
```typescript
|
|
121
|
-
import { failure, Result, success } from '@hexafy/core';
|
|
122
|
-
|
|
123
|
-
// Success path
|
|
124
|
-
const result = success({ data: 'value' });
|
|
125
|
-
if (result.success) {
|
|
126
|
-
console.log(result.value.data);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
// Failure path
|
|
130
|
-
const errorResult = failure(new Error('Something went wrong'));
|
|
131
|
-
if (!errorResult.success) {
|
|
132
|
-
console.error(errorResult.error.message);
|
|
77
|
+
console.error(result.error.message);
|
|
133
78
|
}
|
|
134
79
|
```
|
|
135
80
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
#### `isDomainError(value: unknown): value is DomainErrorLike`
|
|
139
|
-
|
|
140
|
-
Checks if a value is a domain error (has compatible shape). Works with both `@hexafy/core` errors and custom error classes.
|
|
141
|
-
|
|
142
|
-
```typescript
|
|
143
|
-
import { ApplicationError, isDomainError, ValidationError } from '@hexafy/core';
|
|
144
|
-
|
|
145
|
-
// Built-in errors
|
|
146
|
-
isDomainError(new ValidationError('Invalid input')); // true
|
|
147
|
-
|
|
148
|
-
// Custom errors with code/context
|
|
149
|
-
isDomainError({
|
|
150
|
-
code: 'MY_ERROR',
|
|
151
|
-
message: 'Something went wrong',
|
|
152
|
-
context: { userId: 123 }
|
|
153
|
-
}); // true
|
|
154
|
-
|
|
155
|
-
// Regular Error (no code/context)
|
|
156
|
-
isDomainError(new Error('Generic error')); // false
|
|
157
|
-
```
|
|
158
|
-
|
|
159
|
-
#### `getDomainErrorCode(error: Error): string | undefined`
|
|
160
|
-
|
|
161
|
-
Extracts the error code from any error. Useful for routing errors to appropriate handlers.
|
|
162
|
-
|
|
163
|
-
```typescript
|
|
164
|
-
import { getDomainErrorCode, ValidationError } from '@hexafy/core';
|
|
165
|
-
|
|
166
|
-
getDomainErrorCode(new ValidationError());
|
|
167
|
-
// Returns: 'VALIDATION_ERROR'
|
|
81
|
+
## Core pattern
|
|
168
82
|
|
|
169
|
-
|
|
170
|
-
// Returns: 'CUSTOM'
|
|
83
|
+
The package is built around a simple application flow:
|
|
171
84
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
85
|
+
- business logic lives in a `Usecase`
|
|
86
|
+
- the use case returns a value on success
|
|
87
|
+
- thrown errors are converted into a failed `UsecaseResult`
|
|
88
|
+
- infrastructure concerns stay outside the domain layer
|
|
175
89
|
|
|
176
|
-
|
|
90
|
+
Example:
|
|
177
91
|
|
|
178
|
-
|
|
92
|
+
```ts
|
|
93
|
+
import { failure, success } from '@hexafy/core/application';
|
|
179
94
|
|
|
180
|
-
|
|
181
|
-
|
|
95
|
+
const ok = success({ id: '1' });
|
|
96
|
+
const bad = failure(new Error('Something went wrong'));
|
|
182
97
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
input: Input,
|
|
186
|
-
logger: LoggerPort
|
|
187
|
-
): Promise<Result<Output>> {
|
|
188
|
-
logger.debug('Starting execution', { input });
|
|
189
|
-
logger.info('Success', { result: output });
|
|
190
|
-
return success(output);
|
|
191
|
-
}
|
|
98
|
+
if (ok.success) {
|
|
99
|
+
console.log(ok.value.id);
|
|
192
100
|
}
|
|
193
|
-
|
|
194
|
-
// Configure with your logger
|
|
195
|
-
const useCase = new MyUseCase({
|
|
196
|
-
loggerFactory: (name) => consoleLogger
|
|
197
|
-
});
|
|
198
101
|
```
|
|
199
102
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
Built-in error classes for domain errors. All errors support `code`, `message`, `context`, and `cause`:
|
|
103
|
+
## Package layout
|
|
203
104
|
|
|
204
|
-
|
|
205
|
-
| --------------------- | -------------------------------------- | ------------------------------------ |
|
|
206
|
-
| **ValidationError** | Input validation fails | Email format invalid, required field |
|
|
207
|
-
| **NotFoundError** | Resource lookup returns null/undefined | User by ID not found |
|
|
208
|
-
| **ConflictError** | Unique constraint violation | Email already registered |
|
|
209
|
-
| **UnauthorizedError** | Authentication required | Missing JWT token |
|
|
210
|
-
| **ForbiddenError** | Insufficient permissions | User can't edit another's order |
|
|
211
|
-
| **InvariantError** | Business rule violated | Cannot cancel order after shipment |
|
|
212
|
-
| **ApplicationError** | Generic domain error | Custom business logic error |
|
|
105
|
+
This package exposes focused subpaths:
|
|
213
106
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
#### Creating Custom Errors
|
|
217
|
-
|
|
218
|
-
```typescript
|
|
219
|
-
import { ApplicationError, type ApplicationErrorDetails } from '@hexafy/core';
|
|
220
|
-
|
|
221
|
-
class PaymentProcessingError extends ApplicationError {
|
|
222
|
-
constructor(
|
|
223
|
-
message = 'Payment processing failed',
|
|
224
|
-
details?: ApplicationErrorDetails
|
|
225
|
-
) {
|
|
226
|
-
super(message, { ...details, code: 'PAYMENT_PROCESSING_ERROR' });
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
```
|
|
230
|
-
|
|
231
|
-
## 🔧 Configuration
|
|
232
|
-
|
|
233
|
-
### Logger Setup
|
|
234
|
-
|
|
235
|
-
```typescript
|
|
236
|
-
import Pino from 'pino';
|
|
237
|
-
|
|
238
|
-
const useCase = new CreateUserUseCase({
|
|
239
|
-
loggerFactory: (name) => pinoLogger
|
|
240
|
-
});
|
|
241
|
-
```
|
|
242
|
-
|
|
243
|
-
### Dependencies
|
|
244
|
-
|
|
245
|
-
Optional dependencies injected into use cases:
|
|
246
|
-
|
|
247
|
-
```typescript
|
|
248
|
-
const useCase = new CreateUserUseCase({
|
|
249
|
-
generateId: () => crypto.randomUUID()
|
|
250
|
-
});
|
|
251
|
-
```
|
|
252
|
-
|
|
253
|
-
## 🏗️ Quick Example
|
|
254
|
-
|
|
255
|
-
```typescript
|
|
107
|
+
```ts
|
|
108
|
+
import { failure, success, Usecase } from '@hexafy/core/application';
|
|
256
109
|
import {
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
Usecase,
|
|
110
|
+
ApplicationError,
|
|
111
|
+
type LoggerPort,
|
|
112
|
+
RepositoryBase,
|
|
113
|
+
type RepositoryPort,
|
|
262
114
|
ValidationError
|
|
263
|
-
} from '@hexafy/core';
|
|
264
|
-
|
|
265
|
-
class GetProductUseCase extends Usecase<string, Product> {
|
|
266
|
-
constructor(private repository: ProductRepository) {
|
|
267
|
-
super({});
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
protected async executeInternal(
|
|
271
|
-
productId: string,
|
|
272
|
-
logger: LoggerPort
|
|
273
|
-
): Promise<Result<Product>> {
|
|
274
|
-
const product = await this.repository.findById(productId);
|
|
275
|
-
|
|
276
|
-
if (!product) {
|
|
277
|
-
return failure(new NotFoundError(`Product ${productId} not found`));
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
return success(product);
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
// Usage
|
|
285
|
-
const useCase = new GetProductUseCase(repository);
|
|
286
|
-
const result = await useCase.execute('prod_123');
|
|
287
|
-
|
|
288
|
-
if (result.success) {
|
|
289
|
-
console.log(result.value.name);
|
|
290
|
-
} else {
|
|
291
|
-
console.error(result.error.message);
|
|
292
|
-
}
|
|
293
|
-
```
|
|
294
|
-
|
|
295
|
-
## 📖 API Reference
|
|
296
|
-
|
|
297
|
-
### Exports from `@hexafy/core`
|
|
298
|
-
|
|
299
|
-
| Export | Description |
|
|
300
|
-
| ------------------------------------- | --------------------------------------- |
|
|
301
|
-
| `Result<T>`, `success()`, `failure()` | Result type for explicit error handling |
|
|
302
|
-
| `Usecase<Input, Output>` | Base class for use cases |
|
|
303
|
-
| `UsecaseExecutionDependencies` | Injection dependencies interface |
|
|
304
|
-
| `LoggerPort` | Logger interface (NOOP by default) |
|
|
305
|
-
| `consoleLogger`, `NOOP_LOGGER` | Logger implementations |
|
|
306
|
-
| `Entity<T>` | Base entity class |
|
|
307
|
-
| `Repository<T, K>` | Base repository interface |
|
|
308
|
-
| `UnitOfWorkBase` | Transactional boundary helper |
|
|
309
|
-
|
|
310
|
-
### Error Classes
|
|
311
|
-
|
|
312
|
-
| Error Type | Description |
|
|
313
|
-
| ------------------- | --------------------------- |
|
|
314
|
-
| `ValidationError` | Invalid input data |
|
|
315
|
-
| `NotFoundError` | Resource not found |
|
|
316
|
-
| `ConflictError` | Resource conflict |
|
|
317
|
-
| `UnauthorizedError` | Authentication required |
|
|
318
|
-
| `ForbiddenError` | Authorization denied |
|
|
319
|
-
| `InvariantError` | Business invariant violated |
|
|
320
|
-
| `ApplicationError` | Generic domain error |
|
|
321
|
-
|
|
322
|
-
### Utilities
|
|
323
|
-
|
|
324
|
-
| Function | Description |
|
|
325
|
-
| ---------------------- | --------------------------------- |
|
|
326
|
-
| `isDomainError()` | Type guard for domain errors |
|
|
327
|
-
| `getDomainErrorCode()` | Extract error code from any error |
|
|
328
|
-
|
|
329
|
-
## 🎓 Best Practices
|
|
330
|
-
|
|
331
|
-
### Return Domain Errors, Don't Throw
|
|
332
|
-
|
|
333
|
-
Use `failure()` for expected domain errors. Throw infrastructure errors (database, external services):
|
|
334
|
-
|
|
335
|
-
```typescript
|
|
336
|
-
// ✅ Domain errors
|
|
337
|
-
if (!email.includes('@')) {
|
|
338
|
-
return failure(new ValidationError('Invalid email'));
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
// ✅ Infrastructure errors
|
|
342
|
-
try {
|
|
343
|
-
await db.save(data);
|
|
344
|
-
} catch (e) {
|
|
345
|
-
throw new InfrastructureError('Save failed', e);
|
|
346
|
-
}
|
|
347
|
-
```
|
|
348
|
-
|
|
349
|
-
### Choose the Right Error Type
|
|
350
|
-
|
|
351
|
-
```typescript
|
|
352
|
-
// ✅ Use NotFoundError for missing resources
|
|
353
|
-
if (!user) {
|
|
354
|
-
return failure(new NotFoundError('User not found'));
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
// ✅ Use ConflictError for duplicate violations
|
|
358
|
-
if (await this.exists(email)) {
|
|
359
|
-
return failure(new ConflictError('Email already registered'));
|
|
360
|
-
}
|
|
115
|
+
} from '@hexafy/core/domain';
|
|
116
|
+
import { ConsoleLoggingAdapter } from '@hexafy/core/infrastructure';
|
|
361
117
|
```
|
|
362
118
|
|
|
363
|
-
##
|
|
119
|
+
## Recommended usage
|
|
364
120
|
|
|
365
|
-
-
|
|
366
|
-
-
|
|
121
|
+
- keep domain rules and validation in `Usecase` or domain types
|
|
122
|
+
- let infrastructure code throw unexpected exceptions
|
|
123
|
+
- use domain errors for expected business failures
|
|
124
|
+
- keep adapters on the edges of the system
|
|
125
|
+
- prefer small, explicit ports over framework-specific abstractions
|
|
367
126
|
|
|
368
|
-
##
|
|
127
|
+
## License
|
|
369
128
|
|
|
370
129
|
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hexafy/core",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.2",
|
|
4
4
|
"description": "Core hexagonal architecture constructs for TypeScript",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"clean-architecture",
|
|
@@ -10,9 +10,10 @@
|
|
|
10
10
|
"use-case"
|
|
11
11
|
],
|
|
12
12
|
"license": "MIT",
|
|
13
|
+
"author": "Philipp Teßner-Müller",
|
|
13
14
|
"repository": {
|
|
14
15
|
"type": "git",
|
|
15
|
-
"url": "https://github.com/phips-git/hexafy"
|
|
16
|
+
"url": "git+https://github.com/phips-git/hexafy.git"
|
|
16
17
|
},
|
|
17
18
|
"files": [
|
|
18
19
|
"dist"
|
package/dist/application.d.mts
DELETED
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
import { a as ClockPort, n as LoggingPort, r as IdentifierPort, t as MetricsPort } from "./metrics.port-CfI8yKMA.mjs";
|
|
2
|
-
/**
|
|
3
|
-
* Token for requesting use case cancellation.
|
|
4
|
-
*
|
|
5
|
-
* Provides a way to signal that a use case execution should be aborted. Useful
|
|
6
|
-
* for implementing timeouts, user-initiated cancellation, or long-running
|
|
7
|
-
* operations that can be interrupted.
|
|
8
|
-
*
|
|
9
|
-
* @example
|
|
10
|
-
* ```typescript
|
|
11
|
-
* // Create a cancellation token
|
|
12
|
-
* const controller = new AbortController();
|
|
13
|
-
* const token: CancellationToken = {
|
|
14
|
-
* isCancelled: controller.signal.aborted,
|
|
15
|
-
* reason: 'Operation timed out'
|
|
16
|
-
* };
|
|
17
|
-
*
|
|
18
|
-
* // Execute use case with cancellation
|
|
19
|
-
* await useCase.execute(data, context, token);
|
|
20
|
-
* ```
|
|
21
|
-
*
|
|
22
|
-
* @param isCancelled - Whether cancellation has been requested
|
|
23
|
-
* @param reason - Optional reason for cancellation
|
|
24
|
-
*/
|
|
25
|
-
interface CancellationToken {
|
|
26
|
-
readonly isCancelled: boolean;
|
|
27
|
-
readonly reason?: string;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Result type for use case execution.
|
|
31
|
-
*
|
|
32
|
-
* Represents the outcome of a use case, either success with a value or failure
|
|
33
|
-
* with an error. This discriminated union enables pattern matching for result
|
|
34
|
-
* handling without requiring try/catch.
|
|
35
|
-
*
|
|
36
|
-
* @example
|
|
37
|
-
* ```typescript
|
|
38
|
-
* const result = await createUser({ email: 'user@example.com' });
|
|
39
|
-
*
|
|
40
|
-
* if (result.success) {
|
|
41
|
-
* console.log('User created:', result.value.userId);
|
|
42
|
-
* } else {
|
|
43
|
-
* console.error('Failed:', result.error.message);
|
|
44
|
-
* }
|
|
45
|
-
* ```
|
|
46
|
-
*
|
|
47
|
-
* @template TSuccess - The type of the success value
|
|
48
|
-
* @template TFailure - The type of the failure (default: Error)
|
|
49
|
-
*/
|
|
50
|
-
type UsecaseResult<TSuccess, TFailure = Error> = {
|
|
51
|
-
success: true;
|
|
52
|
-
value: TSuccess;
|
|
53
|
-
} | {
|
|
54
|
-
success: false;
|
|
55
|
-
error: TFailure;
|
|
56
|
-
};
|
|
57
|
-
/** Configuration for use case execution. */
|
|
58
|
-
interface UsecaseExecutionConfiguration {
|
|
59
|
-
clock?: ClockPort;
|
|
60
|
-
/**
|
|
61
|
-
* Optional logging instance. If not provided, consoleLogger is used by
|
|
62
|
-
* default for developer convenience. Set to NOOP_LOGGER to explicitly disable
|
|
63
|
-
* logging.
|
|
64
|
-
*/
|
|
65
|
-
logging?: LoggingPort;
|
|
66
|
-
/**
|
|
67
|
-
* Optional metrics port for observability. If not provided, NOOP_METRICS is
|
|
68
|
-
* used (no metrics recorded). Pass a custom implementation to enable metrics
|
|
69
|
-
* collection.
|
|
70
|
-
*/
|
|
71
|
-
metrics?: MetricsPort;
|
|
72
|
-
identifier?: IdentifierPort;
|
|
73
|
-
}
|
|
74
|
-
/** Alias for UsecaseExecutionConfiguration for backwards compatibility. */
|
|
75
|
-
type UsecaseExecutionDependencies = UsecaseExecutionConfiguration;
|
|
76
|
-
/**
|
|
77
|
-
* Abstract base class for all use cases.
|
|
78
|
-
*
|
|
79
|
-
* Provides structured logging, execution IDs, and duration tracking.
|
|
80
|
-
*
|
|
81
|
-
* Simple semantics:
|
|
82
|
-
*
|
|
83
|
-
* - Return a value → success (wrapped automatically)
|
|
84
|
-
* - Throw an error → failure (wrapped automatically)
|
|
85
|
-
*
|
|
86
|
-
* Logging is enabled by default (uses console logger) for developer
|
|
87
|
-
* convenience. To disable logging, explicitly pass NOOP_LOGGER.
|
|
88
|
-
*
|
|
89
|
-
* The framework logs the fact of failure, not the error details. Consumers
|
|
90
|
-
* handle error logging at the call site by inspecting the Result type.
|
|
91
|
-
*
|
|
92
|
-
* @example
|
|
93
|
-
* ```typescript
|
|
94
|
-
* // Default: uses consoleLogger (logs to console)
|
|
95
|
-
* const useCase = new CreateUserUseCase({});
|
|
96
|
-
* await useCase.execute({ email: 'user@example.com' });
|
|
97
|
-
* // → Logs to console
|
|
98
|
-
*
|
|
99
|
-
* // Disable logging (for tests or silent mode)
|
|
100
|
-
* const silentUseCase = new CreateUserUseCase({
|
|
101
|
-
* logger: NOOP_LOGGER
|
|
102
|
-
* });
|
|
103
|
-
* await silentUseCase.execute({ email: 'user@example.com' });
|
|
104
|
-
* // → No output
|
|
105
|
-
*
|
|
106
|
-
* // Custom logger
|
|
107
|
-
* const useCase = new CreateUserUseCase({
|
|
108
|
-
* logger: myCustomLogger
|
|
109
|
-
* });
|
|
110
|
-
* ```;
|
|
111
|
-
*
|
|
112
|
-
* @template TInput - The input type for the use case
|
|
113
|
-
* @template TOutput - The output type for the use case
|
|
114
|
-
*/
|
|
115
|
-
export declare abstract class Usecase<TInput = void, TOutput = void> {
|
|
116
|
-
protected readonly dependencies: UsecaseExecutionConfiguration;
|
|
117
|
-
constructor(dependencies?: UsecaseExecutionConfiguration);
|
|
118
|
-
/**
|
|
119
|
-
* Abstract method to implement.
|
|
120
|
-
*
|
|
121
|
-
* Simple semantics:
|
|
122
|
-
*
|
|
123
|
-
* - Return a value → success (wrapped automatically)
|
|
124
|
-
* - Throw an error → failure (wrapped automatically)
|
|
125
|
-
*
|
|
126
|
-
* Use the logger to log business logic and errors as needed.
|
|
127
|
-
*/
|
|
128
|
-
protected abstract executeInternal(input: TInput, logger: LoggingPort, cancellationToken?: CancellationToken): Promise<TOutput>;
|
|
129
|
-
/**
|
|
130
|
-
* Execute the use case.
|
|
131
|
-
*
|
|
132
|
-
* @param input - The input data for the use case
|
|
133
|
-
* @param executionContext - Additional context to include in logs
|
|
134
|
-
* @param cancellationToken - Optional token for requesting cancellation
|
|
135
|
-
* @returns Promise resolving to a Result (success or failure)
|
|
136
|
-
*/
|
|
137
|
-
execute(input: TInput, executionContext?: Record<string, unknown>, cancellationToken?: CancellationToken): Promise<UsecaseResult<TOutput, Error>>;
|
|
138
|
-
private getNow;
|
|
139
|
-
private getExecutionId;
|
|
140
|
-
private getNowAdapter;
|
|
141
|
-
private getOrCreateLoggingAdapter;
|
|
142
|
-
private getOrCreateMetricsAdapter;
|
|
143
|
-
private normalizeError;
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* Result type indicating a successful use case execution.
|
|
147
|
-
*
|
|
148
|
-
* @template T - The type of the success value
|
|
149
|
-
* @param value - The successfully computed value
|
|
150
|
-
*/
|
|
151
|
-
export declare function success<T>(value: T): UsecaseResult<T, never>;
|
|
152
|
-
/**
|
|
153
|
-
* Result type indicating a failed use case execution.
|
|
154
|
-
*
|
|
155
|
-
* @template TError - The type of the error
|
|
156
|
-
* @param error - The error that occurred
|
|
157
|
-
*/
|
|
158
|
-
export declare function failure<TError extends Error>(error: TError): UsecaseResult<never, TError>;
|
|
159
|
-
/**
|
|
160
|
-
* Extracts the value from a successful UsecaseResult.
|
|
161
|
-
*
|
|
162
|
-
* @template TSuccess - The type of the success value
|
|
163
|
-
* @template TError - The type of the error
|
|
164
|
-
* @param result - The result to unwrap
|
|
165
|
-
* @returns The success value
|
|
166
|
-
* @throws {Error} If the result represents a failure
|
|
167
|
-
*/
|
|
168
|
-
export declare function unwrap<TSuccess, TError>(result: UsecaseResult<TSuccess, TError>): TSuccess;
|
|
169
|
-
export type { CancellationToken, UsecaseExecutionConfiguration, UsecaseExecutionDependencies, UsecaseResult };
|
|
170
|
-
//# sourceMappingURL=application.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"application.d.mts","names":[],"sources":["../src/application/types/cancellation-token.type.ts","../src/application/types/usecase-result.ts","../src/application/usecase.ts","../src/application/utils/usecase-result.utils.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;UAuBiB;WACN;WACA;;;;;;;;;;;;;;;;;;;;;;;KCJC,cAAc,UAAU,WAAW;EAC3C;EAAe,OAAO;;EAAe;EAAgB,OAAO;;;UCL/C;EACf,QAAQ;;;;;;EAMR,UAAU;;;;;;EAMV,UAAU;EACV,aAAa;;;KAIH,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8BAyCrB,QAAQ,eAAe;qBAEtB,cAAc;EADnC,YACqB,eAAc;;;;;;;;;;;qBAahB,gBACjB,OAAO,QACP,QAAQ,aACR,oBAAoB,oBACnB,QAAQ;;;;;;;;;EAUL,QACJ,OAAO,QACP,mBAAmB,yBACnB,oBAAoB,oBACnB,QAAQ,cAAc,SAAS;UAqC1B;UAIA;UAOA;UAIA;UAIA;UAIA;;;;;;;;wBCrIM,QAAQ,GAAG,OAAO,IAAI,cAAc;;;;;;;wBAUpC,QAAQ,eAAe,OACrC,OAAO,SACN,qBAAqB;;;;;;;;;;wBAaR,OAAO,UAAU,QAC/B,QAAQ,cAAc,UAAU,UAC/B"}
|