@3lineas/groovepack 0.1.4 → 1.2.0
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 +261 -138
- package/dist/action-response.type-XlzII9Lr.d.ts +11 -0
- package/dist/api-action/index.d.ts +44 -0
- package/dist/api-action/index.js +105 -0
- package/dist/api-action/index.js.map +1 -0
- package/dist/api-client/index.d.ts +52 -0
- package/dist/api-client/index.js +142 -0
- package/dist/api-client/index.js.map +1 -0
- package/dist/api-toast/index.d.ts +80 -0
- package/dist/api-toast/index.js +104 -0
- package/dist/api-toast/index.js.map +1 -0
- package/dist/batch-capable-db.type-Cyybxkjc.d.ts +8 -0
- package/dist/chunk-3FQ5C44Y.js +119 -0
- package/dist/chunk-3FQ5C44Y.js.map +1 -0
- package/dist/groovepack-locale.type-CaXo9vLj.d.ts +3 -0
- package/dist/i18n/index.d.ts +82 -0
- package/dist/i18n/index.js +17 -0
- package/dist/i18n/index.js.map +1 -0
- package/dist/logger/index.d.ts +19 -0
- package/dist/logger/index.js +89 -0
- package/dist/logger/index.js.map +1 -0
- package/dist/pipeline/pipeline.d.ts +41 -0
- package/dist/pipeline/pipeline.js +64 -0
- package/dist/pipeline/pipeline.js.map +1 -0
- package/dist/pipeline/with-d1-transaction.d.ts +16 -0
- package/dist/pipeline/with-d1-transaction.js +17 -0
- package/dist/pipeline/with-d1-transaction.js.map +1 -0
- package/package.json +55 -16
- package/dist/index.js +0 -468
- package/dist/index.js.map +0 -1
- package/registry/common/api-client/files/README.md.template +0 -64
- package/registry/common/api-client/files/index.ts.template +0 -296
- package/registry/common/logger/files/README.md.template +0 -55
- package/registry/common/logger/files/index.ts.template +0 -194
- package/registry/react/api-action/files/README.md.template +0 -61
- package/registry/react/api-action/files/index.ts.template +0 -291
- package/registry/react/api-toast/files/README.md.template +0 -51
- package/registry/react/api-toast/files/index.ts.template +0 -169
- package/registry/server/pipeline/files/README.md.template +0 -205
- package/registry/server/pipeline/files/pipeline.ts.template +0 -134
- package/registry/server/pipeline/files/types.ts.template +0 -35
- package/registry/server/pipeline/files/with-d1-transaction.ts.template +0 -50
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
# 🚀 Pipeline Pattern (`src/lib/pipeline`)
|
|
2
|
-
|
|
3
|
-
> **Laravel-style sequential pipeline with atomic batch transactions for Cloudflare D1 & SQLite.**
|
|
4
|
-
> 100% agnostic to **Drizzle ORM** and **Native Cloudflare D1 (`D1Database`)**.
|
|
5
|
-
> **Strict Direct Imports Rule**: No barrel files (`index.ts`). Import directly from each file.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## 📖 Direct Imports Guide
|
|
10
|
-
|
|
11
|
-
```typescript
|
|
12
|
-
// ✅ Correct (Direct imports)
|
|
13
|
-
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
14
|
-
import { withD1Transaction } from "@/lib/pipeline/with-d1-transaction";
|
|
15
|
-
import type { PipeAction, D1TransactionContext } from "@/lib/pipeline/types";
|
|
16
|
-
|
|
17
|
-
// ❌ Prohibited (No barrel files allowed)
|
|
18
|
-
// import { Pipeline } from "@/lib/pipeline";
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
## 📖 Table of Contents
|
|
24
|
-
1. [Core Concepts](#1-core-concepts)
|
|
25
|
-
2. [How to Use](#2-how-to-use)
|
|
26
|
-
- [A. Native Cloudflare D1 (`env.DB`)](#a-native-cloudflare-d1-envdb)
|
|
27
|
-
- [B. Drizzle ORM on D1 (`db`)](#b-drizzle-orm-on-d1-db)
|
|
28
|
-
- [C. Pure In-Memory Workflows (No Database)](#c-pure-in-memory-workflows-no-database)
|
|
29
|
-
3. [Inputs, Outputs & Type Contracts](#3-inputs-outputs--type-contracts)
|
|
30
|
-
4. [Possible Errors & Troubleshooting](#4-possible-errors--troubleshooting)
|
|
31
|
-
|
|
32
|
-
---
|
|
33
|
-
|
|
34
|
-
## 1. Core Concepts
|
|
35
|
-
|
|
36
|
-
The Pipeline pattern solves the complexity of multi-step business logic by:
|
|
37
|
-
- **Decoupling Actions**: Each action does one thing (`(context) => context`) without nested function calls.
|
|
38
|
-
- **Atomic Cloudflare D1 Batching**: Mutating statements are staged via `tx.stage(...)` and committed together in a single `db.batch()` call upon completion.
|
|
39
|
-
- **Preventive In-Memory Rollback**: If any action throws an error (e.g. domain exception), the pipeline stops immediately. Staged mutations are discarded in memory and zero queries hit D1.
|
|
40
|
-
|
|
41
|
-
---
|
|
42
|
-
|
|
43
|
-
## 2. How to Use
|
|
44
|
-
|
|
45
|
-
### A. Native Cloudflare D1 (`env.DB`)
|
|
46
|
-
|
|
47
|
-
```typescript
|
|
48
|
-
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
49
|
-
import type { D1TransactionContext } from "@/lib/pipeline/types";
|
|
50
|
-
|
|
51
|
-
interface CreateUserContext {
|
|
52
|
-
db: D1Database;
|
|
53
|
-
input: { email: string; name: string };
|
|
54
|
-
tx?: D1TransactionContext<D1Database, D1PreparedStatement>;
|
|
55
|
-
userId?: string;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// 1. Define isolated actions
|
|
59
|
-
async function ensureEmailAvailable(ctx: CreateUserContext): Promise<CreateUserContext> {
|
|
60
|
-
const existing = await ctx.tx!.db
|
|
61
|
-
.prepare("SELECT id FROM users WHERE email = ?")
|
|
62
|
-
.bind(ctx.input.email)
|
|
63
|
-
.first();
|
|
64
|
-
|
|
65
|
-
if (existing) {
|
|
66
|
-
throw new Error("Email already registered");
|
|
67
|
-
}
|
|
68
|
-
return ctx;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
async function stageInsertUser(ctx: CreateUserContext): Promise<CreateUserContext> {
|
|
72
|
-
const id = crypto.randomUUID();
|
|
73
|
-
|
|
74
|
-
// Stage statement for atomic batch execution
|
|
75
|
-
ctx.tx!.stage(
|
|
76
|
-
ctx.tx!.db
|
|
77
|
-
.prepare("INSERT INTO users (id, email, name) VALUES (?, ?, ?)")
|
|
78
|
-
.bind(id, ctx.input.email, ctx.input.name)
|
|
79
|
-
);
|
|
80
|
-
|
|
81
|
-
return { ...ctx, userId: id };
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// 2. Execute pipeline
|
|
85
|
-
const result = await Pipeline.send<CreateUserContext>({ db: env.DB, input })
|
|
86
|
-
.transactional(env.DB)
|
|
87
|
-
.through([ensureEmailAvailable, stageInsertUser])
|
|
88
|
-
.then((ctx) => ({ id: ctx.userId! }));
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
---
|
|
92
|
-
|
|
93
|
-
### B. Drizzle ORM on D1 (`db`)
|
|
94
|
-
|
|
95
|
-
```typescript
|
|
96
|
-
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
97
|
-
import type { D1TransactionContext } from "@/lib/pipeline/types";
|
|
98
|
-
import { users } from "@/db/schema";
|
|
99
|
-
import { eq } from "drizzle-orm";
|
|
100
|
-
import type { BatchItem } from "drizzle-orm/batch";
|
|
101
|
-
|
|
102
|
-
interface CreateUserContext {
|
|
103
|
-
db: typeof db;
|
|
104
|
-
input: { email: string; name: string };
|
|
105
|
-
tx?: D1TransactionContext<typeof db, BatchItem<"sqlite">>;
|
|
106
|
-
createdId?: string;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
async function validateUniqueEmail(ctx: CreateUserContext): Promise<CreateUserContext> {
|
|
110
|
-
const [existing] = await ctx.tx!.db
|
|
111
|
-
.select({ id: users.id })
|
|
112
|
-
.from(users)
|
|
113
|
-
.where(eq(users.email, ctx.input.email));
|
|
114
|
-
|
|
115
|
-
if (existing) {
|
|
116
|
-
throw new Error("Email already registered");
|
|
117
|
-
}
|
|
118
|
-
return ctx;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
async function stageCreateUser(ctx: CreateUserContext): Promise<CreateUserContext> {
|
|
122
|
-
const newId = crypto.randomUUID();
|
|
123
|
-
|
|
124
|
-
// Stage Drizzle mutation
|
|
125
|
-
ctx.tx!.stage(
|
|
126
|
-
ctx.tx!.db.insert(users).values({
|
|
127
|
-
id: newId,
|
|
128
|
-
email: ctx.input.email,
|
|
129
|
-
name: ctx.input.name,
|
|
130
|
-
})
|
|
131
|
-
);
|
|
132
|
-
|
|
133
|
-
return { ...ctx, createdId: newId };
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// Execute
|
|
137
|
-
const result = await Pipeline.send<CreateUserContext>({ db, input })
|
|
138
|
-
.transactional(db)
|
|
139
|
-
.through([validateUniqueEmail, stageCreateUser])
|
|
140
|
-
.thenReturn();
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
---
|
|
144
|
-
|
|
145
|
-
### C. Pure In-Memory Workflows (No Database)
|
|
146
|
-
|
|
147
|
-
```typescript
|
|
148
|
-
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
149
|
-
|
|
150
|
-
interface TransformOrderContext {
|
|
151
|
-
rawItems: Array<{ price: number; quantity: number }>;
|
|
152
|
-
discountRate: number;
|
|
153
|
-
subtotal?: number;
|
|
154
|
-
total?: number;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const finalOrder = await Pipeline.send<TransformOrderContext>({
|
|
158
|
-
rawItems: [{ price: 100, quantity: 2 }],
|
|
159
|
-
discountRate: 0.1,
|
|
160
|
-
})
|
|
161
|
-
.through([
|
|
162
|
-
(ctx) => ({ ...ctx, subtotal: ctx.rawItems.reduce((acc, i) => acc + i.price * i.quantity, 0) }),
|
|
163
|
-
(ctx) => ({ ...ctx, total: ctx.subtotal! * (1 - ctx.discountRate) }),
|
|
164
|
-
])
|
|
165
|
-
.thenReturn();
|
|
166
|
-
```
|
|
167
|
-
|
|
168
|
-
---
|
|
169
|
-
|
|
170
|
-
## 3. Inputs, Outputs & Type Contracts
|
|
171
|
-
|
|
172
|
-
### `Pipeline.send<TContext>(context: TContext)`
|
|
173
|
-
- **Input (`context`)**: Any state object representing the workflow input and accumulated outputs.
|
|
174
|
-
- **Output**: A new `Pipeline<TContext>` instance.
|
|
175
|
-
|
|
176
|
-
### `.transactional(db)`
|
|
177
|
-
- **Input (`db`)**: Any database client implementing `.batch(statements: any[])`.
|
|
178
|
-
- **Side Effect**: Injects `tx: D1TransactionContext<TDb, TStatement>` into `context.tx`.
|
|
179
|
-
- **Output**: Returns the same pipeline instance (`this`) for method chaining.
|
|
180
|
-
|
|
181
|
-
### `.through(pipes: PipeAction<TContext>[])`
|
|
182
|
-
- **Input (`pipes`)**: Array of standalone functions with signature:
|
|
183
|
-
```typescript
|
|
184
|
-
(context: TContext) => Promise<TContext> | TContext;
|
|
185
|
-
```
|
|
186
|
-
- **Rules**:
|
|
187
|
-
- Must return the updated context (or a new object spreading `...context`).
|
|
188
|
-
- To abort the flow, throw a standard error or domain exception.
|
|
189
|
-
|
|
190
|
-
### `.then(destination)` vs `.thenReturn()`
|
|
191
|
-
- **`.thenReturn()`**: Returns `Promise<TContext>` (the final accumulated state).
|
|
192
|
-
- **`.then(destination)`**: Executes `destination(finalContext)` and returns `Promise<TFinalResult>`.
|
|
193
|
-
|
|
194
|
-
---
|
|
195
|
-
|
|
196
|
-
## 4. Possible Errors & Troubleshooting
|
|
197
|
-
|
|
198
|
-
| Issue / Error | Cause | Solution |
|
|
199
|
-
| :--- | :--- | :--- |
|
|
200
|
-
| **`TypeError: Cannot read properties of undefined (reading 'stage')`** | Attempting to access `ctx.tx.stage(...)` without chaining `.transactional(db)`. | Make sure you call `.transactional(db)` right after `Pipeline.send(context)`. |
|
|
201
|
-
| **Data not written to D1** | Action called `ctx.tx.db.insert(...)` or `.prepare(...)` directly instead of staging via `ctx.tx.stage(...)`. | In transactional pipelines, all writes must be passed to `ctx.tx.stage(stmt)`. Immediate writes bypass atomic batching and won't be rolled back on error. |
|
|
202
|
-
| **Unhandled Promise / Floating Promise** | Forgetting to `await` the pipeline call (`const res = Pipeline.send(...)`). | Always use `await Pipeline.send(...)...` or return the promise. |
|
|
203
|
-
| **State mutations lost between actions** | An action forgot to return `context` or returned `undefined`. | Ensure every pipe function returns `context` or `{ ...context, newProp: value }`. |
|
|
204
|
-
| **Cloudflare D1 batch size exceeded (`D1_ERROR`)** | Staging more than 100 statements or exceeding D1 payload limits in a single batch. | Split massive migrations into chunks of 50-100 items before executing the pipeline. |
|
|
205
|
-
| **Preventive Rollback behavior** | If an action throws an error, the execution immediately bubbles up the exception without calling `db.batch()`. | This is intended behavior. Handle the exception in your route middleware or `try/catch` wrapper. |
|
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fileoverview Sequential multi-action Pipeline processor inspired by Laravel.
|
|
3
|
-
* Agnostic to Drizzle ORM and native Cloudflare D1.
|
|
4
|
-
* Strict Zero-Barrel implementation: imports types directly from ./types.
|
|
5
|
-
*/
|
|
6
|
-
import type { PipeAction, D1TransactionContext, BatchCapableDb } from "./types";
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Pipeline processor inspired by the Laravel pipeline pattern.
|
|
10
|
-
*
|
|
11
|
-
* Enables sequential execution of decoupled, atomic actions over a typed context.
|
|
12
|
-
* Actions are isolated and follow the single input / single output contract:
|
|
13
|
-
* `(context: TContext) => Promise<TContext> | TContext`.
|
|
14
|
-
*
|
|
15
|
-
* Supports atomic Cloudflare D1 batching via `.transactional(db)`:
|
|
16
|
-
* - Compatible with native Cloudflare D1 (`env.DB`) and Drizzle ORM (`db`).
|
|
17
|
-
* - Automatically injects a `tx: D1TransactionContext` into `context.tx`.
|
|
18
|
-
* - Staged statements via `context.tx.stage(...)` are committed in an atomic `db.batch()`
|
|
19
|
-
* when `.then()` or `.thenReturn()` resolves.
|
|
20
|
-
* - If any action throws an error (e.g. domain exception), staged statements are discarded
|
|
21
|
-
* in memory and zero mutations are sent to D1 (preventive in-memory rollback).
|
|
22
|
-
*
|
|
23
|
-
* @template TContext - The state object that flows through and gets enriched by the pipeline.
|
|
24
|
-
*
|
|
25
|
-
* @example
|
|
26
|
-
* ```typescript
|
|
27
|
-
* import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
28
|
-
*
|
|
29
|
-
* const result = await Pipeline.send<CreateUserContext>({ db, input })
|
|
30
|
-
* .transactional(db)
|
|
31
|
-
* .through([validateEmailAction, stageCreateUserAction])
|
|
32
|
-
* .thenReturn();
|
|
33
|
-
* ```
|
|
34
|
-
*/
|
|
35
|
-
export class Pipeline<TContext> {
|
|
36
|
-
private context: TContext;
|
|
37
|
-
private pipes: PipeAction<any, any>[] = [];
|
|
38
|
-
private dbClient?: BatchCapableDb<any, any>;
|
|
39
|
-
private stagedStatements: unknown[] = [];
|
|
40
|
-
|
|
41
|
-
private constructor(context: TContext) {
|
|
42
|
-
this.context = context;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Initializes a new pipeline instance with the provided initial context.
|
|
47
|
-
*
|
|
48
|
-
* @template T - The context type of the pipeline.
|
|
49
|
-
* @param context - The initial state to be processed through the pipeline steps.
|
|
50
|
-
* @returns A new `Pipeline` instance.
|
|
51
|
-
*/
|
|
52
|
-
static send<T>(context: T): Pipeline<T> {
|
|
53
|
-
return new Pipeline<T>(context);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Enables atomic Cloudflare D1 batch transaction mode for this pipeline run.
|
|
58
|
-
*
|
|
59
|
-
* Automatically initializes `tx: D1TransactionContext` into `context.tx` and
|
|
60
|
-
* commits all staged statements atomically using `db.batch()` upon resolution.
|
|
61
|
-
* Works with both native D1 (`D1Database`) and Drizzle D1.
|
|
62
|
-
*
|
|
63
|
-
* @param db - The database client instance used to execute the final atomic batch.
|
|
64
|
-
* @returns The current pipeline instance for fluent chaining.
|
|
65
|
-
*/
|
|
66
|
-
transactional<
|
|
67
|
-
TDb extends BatchCapableDb<TStatement, any>,
|
|
68
|
-
TStatement = unknown,
|
|
69
|
-
>(db: TDb): this {
|
|
70
|
-
this.dbClient = db;
|
|
71
|
-
|
|
72
|
-
const txContext: D1TransactionContext<TDb, TStatement> = {
|
|
73
|
-
db,
|
|
74
|
-
stage: (...statements: TStatement[]) => {
|
|
75
|
-
this.stagedStatements.push(...statements);
|
|
76
|
-
},
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
if (this.context && typeof this.context === "object") {
|
|
80
|
-
this.context = {
|
|
81
|
-
...this.context,
|
|
82
|
-
tx: txContext,
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
return this;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Defines the sequential list of atomic pipe actions to execute.
|
|
91
|
-
*
|
|
92
|
-
* @param pipes - An array of atomic action functions.
|
|
93
|
-
* @returns The current pipeline instance for fluent method chaining.
|
|
94
|
-
*/
|
|
95
|
-
through(pipes: PipeAction<TContext, any>[]): this {
|
|
96
|
-
this.pipes = pipes;
|
|
97
|
-
return this;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Executes the pipeline sequentially, commits staged mutations atomically if transactional,
|
|
102
|
-
* and passes the final enriched context to a destination closure, returning its resolved value.
|
|
103
|
-
*
|
|
104
|
-
* @template TFinalResult - The type of value returned by the destination closure.
|
|
105
|
-
* @param destination - Callback receiving the final context.
|
|
106
|
-
* @returns A promise resolving to the result of the destination callback.
|
|
107
|
-
*/
|
|
108
|
-
async then<TFinalResult>(
|
|
109
|
-
destination: (context: TContext) => Promise<TFinalResult> | TFinalResult,
|
|
110
|
-
): Promise<TFinalResult> {
|
|
111
|
-
const finalContext = await this.thenReturn();
|
|
112
|
-
return await destination(finalContext);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Executes all pipes sequentially, executes atomic db.batch() if transactional mode is active,
|
|
117
|
-
* and returns the final context state.
|
|
118
|
-
*
|
|
119
|
-
* @returns A promise resolving to the final accumulated context object.
|
|
120
|
-
*/
|
|
121
|
-
async thenReturn(): Promise<TContext> {
|
|
122
|
-
let currentContext = this.context;
|
|
123
|
-
|
|
124
|
-
for (const pipe of this.pipes) {
|
|
125
|
-
currentContext = await pipe(currentContext);
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
if (this.dbClient && this.stagedStatements.length > 0) {
|
|
129
|
-
await this.dbClient.batch(this.stagedStatements);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
return currentContext;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fileoverview Type definitions for Laravel-style Pipeline and atomic Cloudflare D1 batching.
|
|
3
|
-
* Agnostic to whether the consumer uses Drizzle ORM or native Cloudflare D1 (D1Database).
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Individual action contract in the pipeline.
|
|
8
|
-
* Follows the single input / single output rule:
|
|
9
|
-
* `(context: TContext) => Promise<TContext> | TContext`.
|
|
10
|
-
*/
|
|
11
|
-
export type PipeAction<TIn, TOut = TIn> = (
|
|
12
|
-
context: TIn,
|
|
13
|
-
) => Promise<TOut> | TOut;
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Generic minimal interface for database clients supporting atomic batching.
|
|
17
|
-
* Satisfied natively by Cloudflare D1 (`D1Database`) and Drizzle ORM (`DrizzleD1Database`).
|
|
18
|
-
*/
|
|
19
|
-
export interface BatchCapableDb<TStatement = unknown, TResult = unknown> {
|
|
20
|
-
batch(statements: TStatement[]): Promise<TResult[] | unknown>;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Transactional context supplied to the pipeline or withD1Transaction.
|
|
25
|
-
* Allows immediate read queries via `db` and stages mutations for atomic batch execution.
|
|
26
|
-
*
|
|
27
|
-
* @template TDb - The type of database client (e.g. `D1Database` or Drizzle client).
|
|
28
|
-
* @template TStatement - The type of statement staged for batching (e.g. `D1PreparedStatement` or Drizzle `BatchItem`).
|
|
29
|
-
*/
|
|
30
|
-
export interface D1TransactionContext<TDb = unknown, TStatement = unknown> {
|
|
31
|
-
/** Database client for immediate read queries */
|
|
32
|
-
readonly db: TDb;
|
|
33
|
-
/** Enqueues one or more statements to be committed atomically in db.batch() */
|
|
34
|
-
stage: (...statements: TStatement[]) => void;
|
|
35
|
-
}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fileoverview Transactional wrapper that emulates Laravel's DB::transaction() pattern for Cloudflare D1.
|
|
3
|
-
* Agnostic to Drizzle ORM and native Cloudflare D1.
|
|
4
|
-
* Strict Zero-Barrel implementation: imports types directly from ./types.
|
|
5
|
-
*/
|
|
6
|
-
import type { D1TransactionContext, BatchCapableDb } from "./types";
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Transactional wrapper that emulates Laravel's `DB::transaction()` pattern on Cloudflare D1.
|
|
10
|
-
*
|
|
11
|
-
* 1. Wraps the sequential execution of a Pipeline or asynchronous workflow.
|
|
12
|
-
* 2. If any Action throws an error (domain exception or unexpected error),
|
|
13
|
-
* the pipeline terminates immediately and staged mutations are discarded in memory.
|
|
14
|
-
* No queries are sent to Cloudflare D1 (Preventive in-memory rollback).
|
|
15
|
-
* 3. If the pipeline completes successfully and mutations were staged,
|
|
16
|
-
* they are dispatched together via `db.batch()`, guaranteeing ACID atomicity on SQLite/D1.
|
|
17
|
-
*
|
|
18
|
-
* Compatible with:
|
|
19
|
-
* - Native Cloudflare D1: `withD1Transaction(env.DB, async (tx) => { ... })`
|
|
20
|
-
* - Drizzle ORM: `withD1Transaction(db, async (tx) => { ... })`
|
|
21
|
-
*
|
|
22
|
-
* @param db - The database client instance (native D1 or Drizzle).
|
|
23
|
-
* @param pipelineExecution - Callback receiving the `D1TransactionContext`.
|
|
24
|
-
* @returns The resolved value of the pipeline execution callback.
|
|
25
|
-
*/
|
|
26
|
-
export async function withD1Transaction<
|
|
27
|
-
TResult,
|
|
28
|
-
TDb extends BatchCapableDb<TStatement, any> = BatchCapableDb,
|
|
29
|
-
TStatement = unknown,
|
|
30
|
-
>(
|
|
31
|
-
db: TDb,
|
|
32
|
-
pipelineExecution: (tx: D1TransactionContext<TDb, TStatement>) => Promise<TResult>,
|
|
33
|
-
): Promise<TResult> {
|
|
34
|
-
const stagedStatements: TStatement[] = [];
|
|
35
|
-
|
|
36
|
-
const tx: D1TransactionContext<TDb, TStatement> = {
|
|
37
|
-
db,
|
|
38
|
-
stage: (...statements: TStatement[]) => {
|
|
39
|
-
stagedStatements.push(...statements);
|
|
40
|
-
},
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
const result = await pipelineExecution(tx);
|
|
44
|
-
|
|
45
|
-
if (stagedStatements.length > 0) {
|
|
46
|
-
await db.batch(stagedStatements);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
return result;
|
|
50
|
-
}
|