@effect/sql-sqlite-react-native 4.0.0-beta.99 → 4.0.0-rc.109
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/AGENTS.md +395 -0
- package/CLAUDE.md +395 -0
- package/README.md +10 -3
- package/ai-docs/README.md +44 -0
- package/ai-docs/package.json +36 -0
- package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
- package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +39 -0
- package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
- package/ai-docs/src/01_effect/01_basics/index.md +5 -0
- package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
- package/ai-docs/src/01_effect/02_schema/index.md +7 -0
- package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
- package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
- package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
- package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
- package/ai-docs/src/01_effect/03_services/index.md +5 -0
- package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
- package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
- package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
- package/ai-docs/src/01_effect/04_errors/index.md +1 -0
- package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
- package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
- package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
- package/ai-docs/src/01_effect/05_resources/index.md +3 -0
- package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
- package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
- package/ai-docs/src/01_effect/06_running/index.md +1 -0
- package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
- package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
- package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
- package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
- package/ai-docs/src/03_stream/30_encoding.ts +165 -0
- package/ai-docs/src/03_stream/index.md +4 -0
- package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
- package/ai-docs/src/04_integration/index.md +5 -0
- package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
- package/ai-docs/src/05_batching/index.md +3 -0
- package/ai-docs/src/06_schedule/10_schedules.ts +110 -0
- package/ai-docs/src/06_schedule/index.md +3 -0
- package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
- package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
- package/ai-docs/src/07_datetime/index.md +5 -0
- package/ai-docs/src/08_observability/10_logging.ts +66 -0
- package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
- package/ai-docs/src/08_observability/index.md +7 -0
- package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
- package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
- package/ai-docs/src/09_testing/index.md +1 -0
- package/ai-docs/src/10_predicate/01_basics.ts +14 -0
- package/ai-docs/src/10_predicate/index.md +9 -0
- package/ai-docs/src/40_sql/10_basics.ts +175 -0
- package/ai-docs/src/40_sql/index.md +6 -0
- package/ai-docs/src/50_http-client/10_basics.ts +102 -0
- package/ai-docs/src/50_http-client/index.md +3 -0
- package/ai-docs/src/51_http-server/10_basics.ts +118 -0
- package/ai-docs/src/51_http-server/20_testing.ts +100 -0
- package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
- package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
- package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
- package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
- package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
- package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
- package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
- package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
- package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
- package/ai-docs/src/51_http-server/index.md +3 -0
- package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
- package/ai-docs/src/60_child-process/index.md +3 -0
- package/ai-docs/src/70_cli/10_basics.ts +160 -0
- package/ai-docs/src/70_cli/index.md +5 -0
- package/ai-docs/src/71_ai/10_language-model.ts +156 -0
- package/ai-docs/src/71_ai/20_tools.ts +226 -0
- package/ai-docs/src/71_ai/30_chat.ts +158 -0
- package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
- package/ai-docs/src/71_ai/index.md +5 -0
- package/ai-docs/src/80_cluster/10_entities.ts +97 -0
- package/ai-docs/src/80_cluster/index.md +4 -0
- package/ai-docs/src/index.md +10 -0
- package/ai-docs/tsconfig.json +24 -0
- package/dist/SqliteClient.d.ts +3 -3
- package/dist/SqliteClient.d.ts.map +1 -1
- package/dist/SqliteClient.js +23 -10
- package/dist/SqliteClient.js.map +1 -1
- package/dist/SqliteMigrator.d.ts +2 -2
- package/dist/SqliteMigrator.js +2 -2
- package/dist/SqliteMigrator.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +11 -9
- package/src/SqliteClient.ts +26 -12
- package/src/SqliteMigrator.ts +2 -2
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @title Getting started with SQL
|
|
3
|
+
*
|
|
4
|
+
* Define a schema-backed domain model, run migrations against a SQLite
|
|
5
|
+
* database, and expose a derived repository through a service.
|
|
6
|
+
*/
|
|
7
|
+
import { NodeRuntime } from "@effect/platform-node"
|
|
8
|
+
import { SqliteClient, SqliteMigrator } from "@effect/sql-sqlite-node"
|
|
9
|
+
import { Context, Effect, Layer, Schema } from "effect"
|
|
10
|
+
import { Model } from "effect/unstable/schema"
|
|
11
|
+
import { SqlClient, SqlModel, SqlSchema } from "effect/unstable/sql"
|
|
12
|
+
|
|
13
|
+
// Use a branded string for the group id, so it cannot be mixed up with other
|
|
14
|
+
// string ids in the application.
|
|
15
|
+
export const GroupId = Schema.String.pipe(Schema.brand("GroupId"))
|
|
16
|
+
export type GroupId = typeof GroupId.Type
|
|
17
|
+
|
|
18
|
+
// `Model.Class` defines a domain model with variants for the database and JSON
|
|
19
|
+
// boundaries. The single field declaration is the source of truth, and each
|
|
20
|
+
// variant only contains the fields that make sense for that operation:
|
|
21
|
+
//
|
|
22
|
+
// - `Group` / `Group.insert` / `Group.update` for the database
|
|
23
|
+
// - `Group.json` / `Group.jsonCreate` / `Group.jsonUpdate` for JSON APIs
|
|
24
|
+
export class Group extends Model.Class<Group>("Group")({
|
|
25
|
+
// A UUID v4 primary key that is generated by the application on insert
|
|
26
|
+
id: Model.UuidV4Insert(GroupId),
|
|
27
|
+
name: Schema.NonEmptyString,
|
|
28
|
+
// `Model.FieldExcept` removes a field from the given variants. The slug is
|
|
29
|
+
// chosen when the group is created and is immutable afterwards, so it is
|
|
30
|
+
// removed from the update variants.
|
|
31
|
+
slug: Schema.NonEmptyString.pipe(Model.FieldExcept(["update", "jsonUpdate"])),
|
|
32
|
+
// `Model.FieldOnly` keeps a field in only the given variants. Internal notes
|
|
33
|
+
// live in the database and are never exposed through the JSON variants.
|
|
34
|
+
notes: Schema.NullOr(Schema.String).pipe(Model.FieldOnly(["select", "insert"])),
|
|
35
|
+
// `Model.Field` gives full control over the individual variants. The member
|
|
36
|
+
// count is maintained by the database, so the application can read it but
|
|
37
|
+
// never writes it.
|
|
38
|
+
memberCount: Model.Field({
|
|
39
|
+
select: Schema.Int,
|
|
40
|
+
json: Schema.Int
|
|
41
|
+
}),
|
|
42
|
+
// `createdAt` is set to the current time on insert, and `updatedAt` is
|
|
43
|
+
// refreshed on every update. Both are stored as strings, which suits SQLite.
|
|
44
|
+
createdAt: Model.DateTimeInsert,
|
|
45
|
+
updatedAt: Model.DateTimeUpdate
|
|
46
|
+
}) {}
|
|
47
|
+
|
|
48
|
+
export class GroupNotFound extends Schema.TaggedError<GroupNotFound>()("GroupNotFound", {
|
|
49
|
+
id: GroupId
|
|
50
|
+
}) {}
|
|
51
|
+
|
|
52
|
+
// The SqlClient layer determines which database you are talking to. Swap this
|
|
53
|
+
// layer for `@effect/sql-pg`, `@effect/sql-mysql2` etc. to target another
|
|
54
|
+
// database without changing the rest of the code.
|
|
55
|
+
const SqlLayer = SqliteClient.layer({ filename: ":memory:" })
|
|
56
|
+
|
|
57
|
+
// Migrations are effects keyed by `<id>_<name>` that run once, in id order. A
|
|
58
|
+
// real application would keep each migration in its own file and load them
|
|
59
|
+
// with `SqliteMigrator.fromFileSystem` instead of an inline record.
|
|
60
|
+
const MigratorLayer = SqliteMigrator.layer({
|
|
61
|
+
loader: SqliteMigrator.fromRecord({
|
|
62
|
+
"0001_create_groups": Effect.gen(function*() {
|
|
63
|
+
const sql = yield* SqlClient.SqlClient
|
|
64
|
+
yield* sql`
|
|
65
|
+
CREATE TABLE groups (
|
|
66
|
+
id TEXT PRIMARY KEY,
|
|
67
|
+
name TEXT NOT NULL,
|
|
68
|
+
slug TEXT NOT NULL,
|
|
69
|
+
notes TEXT,
|
|
70
|
+
memberCount INTEGER NOT NULL DEFAULT 0,
|
|
71
|
+
createdAt TEXT NOT NULL,
|
|
72
|
+
updatedAt TEXT NOT NULL
|
|
73
|
+
)
|
|
74
|
+
`
|
|
75
|
+
})
|
|
76
|
+
})
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
// Combine the database client with the migrations, so anything built on top of
|
|
80
|
+
// `SqlLive` sees a fully migrated database.
|
|
81
|
+
const SqlLive = MigratorLayer.pipe(Layer.provideMerge(SqlLayer))
|
|
82
|
+
|
|
83
|
+
// Wrap data access in a service, so the rest of the application depends on
|
|
84
|
+
// `Groups` instead of the database directly.
|
|
85
|
+
export class Groups extends Context.Service<Groups, {
|
|
86
|
+
create(name: string, slug: string): Effect.Effect<Group>
|
|
87
|
+
rename(id: GroupId, name: string): Effect.Effect<Group, GroupNotFound>
|
|
88
|
+
findById(id: GroupId): Effect.Effect<Group, GroupNotFound>
|
|
89
|
+
readonly list: Effect.Effect<Array<Group>>
|
|
90
|
+
}>()("app/Groups") {
|
|
91
|
+
static readonly layer = Layer.effect(
|
|
92
|
+
Groups,
|
|
93
|
+
Effect.gen(function*() {
|
|
94
|
+
const sql = yield* SqlClient.SqlClient
|
|
95
|
+
|
|
96
|
+
// `SqlModel.makeRepository` derives insert / update / findById / delete
|
|
97
|
+
// operations from the model, using the matching variant schema for each
|
|
98
|
+
// operation.
|
|
99
|
+
const repo = yield* SqlModel.makeRepository(Group, {
|
|
100
|
+
tableName: "groups",
|
|
101
|
+
spanPrefix: "Groups",
|
|
102
|
+
idColumn: "id"
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
// For queries the repository does not cover, combine the `sql` tag with
|
|
106
|
+
// `SqlSchema` to decode the rows using the model schema.
|
|
107
|
+
const listAll = SqlSchema.findAll({
|
|
108
|
+
Request: Schema.Void,
|
|
109
|
+
Result: Group,
|
|
110
|
+
execute: () => sql`SELECT * FROM groups ORDER BY createdAt`
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
// Use `Effect.fn` to give each method a named span for observability.
|
|
114
|
+
const create = Effect.fn("Groups.create")((name: string, slug: string) =>
|
|
115
|
+
// `Group.insert.makeEffect` fills in the generated id and timestamps
|
|
116
|
+
// using the Effect clock, so tests can control them with `TestClock`.
|
|
117
|
+
Group.insert.makeEffect({ name, slug, notes: null }).pipe(
|
|
118
|
+
Effect.flatMap(repo.insert),
|
|
119
|
+
// Database and encoding failures are unexpected here, so treat
|
|
120
|
+
// them as defects to keep the service interface focused on domain
|
|
121
|
+
// errors.
|
|
122
|
+
Effect.orDie
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
const rename = Effect.fn("Groups.rename")((id: GroupId, name: string) =>
|
|
127
|
+
Group.update.makeEffect({ id, name }).pipe(
|
|
128
|
+
Effect.flatMap(repo.update),
|
|
129
|
+
Effect.orDie
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
const findById = Effect.fn("Groups.findById")((id: GroupId) =>
|
|
134
|
+
repo.findById(id).pipe(
|
|
135
|
+
Effect.catchTags({
|
|
136
|
+
NoSuchElementError: () => new GroupNotFound({ id }),
|
|
137
|
+
SchemaError: Effect.die,
|
|
138
|
+
SqlError: Effect.die
|
|
139
|
+
})
|
|
140
|
+
)
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
const list = listAll().pipe(
|
|
144
|
+
Effect.orDie,
|
|
145
|
+
Effect.withSpan("Groups.list")
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
return Groups.of({ create, rename, findById, list })
|
|
149
|
+
})
|
|
150
|
+
).pipe(
|
|
151
|
+
// Provide the layers locally, so lots of messy wiring doesn't need to
|
|
152
|
+
// happen in the "main" entrypoint of the application.
|
|
153
|
+
Layer.provide(SqlLive)
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const program = Effect.gen(function*() {
|
|
158
|
+
const groups = yield* Groups
|
|
159
|
+
|
|
160
|
+
const engineering = yield* groups.create("Engineering", "engineering")
|
|
161
|
+
const design = yield* groups.create("Design", "design")
|
|
162
|
+
|
|
163
|
+
yield* groups.rename(design.id, "Product Design")
|
|
164
|
+
|
|
165
|
+
const found = yield* groups.findById(engineering.id)
|
|
166
|
+
yield* Effect.log("found group", found)
|
|
167
|
+
|
|
168
|
+
const all = yield* groups.list
|
|
169
|
+
yield* Effect.log(`total groups: ${all.length}`)
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
program.pipe(
|
|
173
|
+
Effect.provide(Groups.layer),
|
|
174
|
+
NodeRuntime.runMain
|
|
175
|
+
)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
## Working with SQL databases
|
|
2
|
+
|
|
3
|
+
Use the `effect/unstable/sql` modules together with a driver package such as
|
|
4
|
+
`@effect/sql-sqlite-node` to access SQL databases. Define domain models with
|
|
5
|
+
`Model.Class` to derive schemas for the database and JSON boundaries, run
|
|
6
|
+
migrations, and write type-safe queries.
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @title Getting started with HttpClient
|
|
3
|
+
*
|
|
4
|
+
* Define a service that uses the HttpClient module to fetch data from an external API
|
|
5
|
+
*/
|
|
6
|
+
import { Context, Effect, flow, Layer, Schedule, Schema } from "effect"
|
|
7
|
+
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
|
|
8
|
+
|
|
9
|
+
class Todo extends Schema.Class<Todo>("Todo")({
|
|
10
|
+
userId: Schema.Int,
|
|
11
|
+
id: Schema.Int,
|
|
12
|
+
title: Schema.String,
|
|
13
|
+
completed: Schema.Boolean
|
|
14
|
+
}) {}
|
|
15
|
+
|
|
16
|
+
export class JsonPlaceholder extends Context.Service<JsonPlaceholder, {
|
|
17
|
+
readonly allTodos: Effect.Effect<ReadonlyArray<Todo>, JsonPlaceholderError>
|
|
18
|
+
getTodo(id: number): Effect.Effect<Todo, JsonPlaceholderError>
|
|
19
|
+
createTodo(todo: Omit<Todo, "id">): Effect.Effect<Todo, JsonPlaceholderError>
|
|
20
|
+
}>()("app/JsonPlaceholder") {
|
|
21
|
+
static readonly layer = Layer.effect(
|
|
22
|
+
JsonPlaceholder,
|
|
23
|
+
Effect.gen(function*() {
|
|
24
|
+
// Access the HttpClient service, and apply some common middleware to all
|
|
25
|
+
// requests:
|
|
26
|
+
const client = (yield* HttpClient.HttpClient).pipe(
|
|
27
|
+
// Add a base URL to all requests made with this client, and set the
|
|
28
|
+
// Accept header to expect JSON responses
|
|
29
|
+
HttpClient.mapRequest(flow(
|
|
30
|
+
HttpClientRequest.prependUrl("https://jsonplaceholder.typicode.com"),
|
|
31
|
+
HttpClientRequest.acceptJson
|
|
32
|
+
)),
|
|
33
|
+
// Fail if the response status is not 2xx
|
|
34
|
+
HttpClient.filterStatusOk,
|
|
35
|
+
// Retry transient errors (network issues, 5xx responses) with an
|
|
36
|
+
// exponential backoff.
|
|
37
|
+
//
|
|
38
|
+
// See the schedule documentation for more complex retry strategies.
|
|
39
|
+
HttpClient.retryTransient({
|
|
40
|
+
schedule: Schedule.exponential(100),
|
|
41
|
+
times: 3
|
|
42
|
+
})
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
const allTodos = client.get("/todos").pipe(
|
|
46
|
+
Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Array(Todo))),
|
|
47
|
+
Effect.mapError((cause) => new JsonPlaceholderError({ cause })),
|
|
48
|
+
Effect.withSpan("JsonPlaceholder.allTodos")
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
// Use the HttpClient to fetch a todo item by id, and decode the response
|
|
52
|
+
// using the Todo schema.
|
|
53
|
+
const getTodo = Effect.fn("JsonPlaceholder.getTodo")(function*(id: number) {
|
|
54
|
+
// Annotate the current span with the id of the todo being fetched, so
|
|
55
|
+
// that it shows up in telemetry for this request.
|
|
56
|
+
yield* Effect.annotateCurrentSpan({ id })
|
|
57
|
+
|
|
58
|
+
const todo = yield* client.get(`/todos/${id}`, {
|
|
59
|
+
// You can pass additional options to individual requests.
|
|
60
|
+
// There are options for query parameters, request body, headers, and
|
|
61
|
+
// more.
|
|
62
|
+
urlParams: { format: "json" }
|
|
63
|
+
}).pipe(
|
|
64
|
+
Effect.flatMap(HttpClientResponse.schemaBodyJson(Todo)),
|
|
65
|
+
Effect.mapError((cause) => new JsonPlaceholderError({ cause }))
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
return todo
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
// You can use the HttpClientRequest module to build up more complex
|
|
72
|
+
// requests:
|
|
73
|
+
const createTodo = Effect.fn("JsonPlaceholder.createTodo")(function*(todo: Omit<Todo, "id">) {
|
|
74
|
+
yield* Effect.annotateCurrentSpan({ title: todo.title })
|
|
75
|
+
|
|
76
|
+
const createdTodo = yield* HttpClientRequest.post("/todos").pipe(
|
|
77
|
+
// The HttpClientRequest module has many helper functions for building requests.
|
|
78
|
+
HttpClientRequest.setUrlParams({ format: "json" }),
|
|
79
|
+
HttpClientRequest.bodyJsonUnsafe(todo),
|
|
80
|
+
client.execute,
|
|
81
|
+
Effect.flatMap(HttpClientResponse.schemaBodyJson(Todo)),
|
|
82
|
+
Effect.mapError((cause) => new JsonPlaceholderError({ cause }))
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
return createdTodo
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
return JsonPlaceholder.of({
|
|
89
|
+
allTodos,
|
|
90
|
+
getTodo,
|
|
91
|
+
createTodo
|
|
92
|
+
})
|
|
93
|
+
})
|
|
94
|
+
).pipe(
|
|
95
|
+
// Provide the fetch-based HttpClient implementation
|
|
96
|
+
Layer.provide(FetchHttpClient.layer)
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export class JsonPlaceholderError extends Schema.TaggedError<JsonPlaceholderError>()("JsonPlaceholderError", {
|
|
101
|
+
cause: Schema.Defect()
|
|
102
|
+
}) {}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @title Getting started with HttpApi
|
|
3
|
+
*
|
|
4
|
+
* Define a schema-first API, implement handlers, secure endpoints with
|
|
5
|
+
* middleware, serve it over HTTP, and call it using a generated typed client.
|
|
6
|
+
*/
|
|
7
|
+
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"
|
|
8
|
+
import { Context, Effect, flow, Layer, Schedule } from "effect"
|
|
9
|
+
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/unstable/http"
|
|
10
|
+
import { HttpApiBuilder, HttpApiClient, HttpApiMiddleware, HttpApiScalar } from "effect/unstable/httpapi"
|
|
11
|
+
import { createServer } from "node:http"
|
|
12
|
+
// Api definitions should **always** be seperate from the server implementation,
|
|
13
|
+
// so that they can be shared between the server and client without leaking
|
|
14
|
+
// server code into clients.
|
|
15
|
+
// Ideally, the would use a seperate package in a monorepo.
|
|
16
|
+
import { Api } from "./fixtures/api/Api.ts"
|
|
17
|
+
import { Authorization } from "./fixtures/api/Authorization.ts"
|
|
18
|
+
import { UsersApiHandlers } from "./fixtures/server/Users/http.ts"
|
|
19
|
+
|
|
20
|
+
// This walkthrough focuses on runtime wiring and typed client usage.
|
|
21
|
+
// See the fixture files for the API schemas, endpoint definitions and handlers:
|
|
22
|
+
|
|
23
|
+
const SystemApiHandlers = HttpApiBuilder.group(
|
|
24
|
+
Api,
|
|
25
|
+
"system",
|
|
26
|
+
Effect.fn(function*(handlers) {
|
|
27
|
+
return handlers.handleAll({
|
|
28
|
+
health: () => Effect.void
|
|
29
|
+
})
|
|
30
|
+
})
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
const ApiRoutes = HttpApiBuilder.layer(Api, {
|
|
34
|
+
openapiPath: "/openapi.json"
|
|
35
|
+
}).pipe(
|
|
36
|
+
// Provide all the handler Layers for the API.
|
|
37
|
+
Layer.provide([UsersApiHandlers, SystemApiHandlers])
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
// Define a /docs route that serves scalar documentation
|
|
41
|
+
const DocsRoute = HttpApiScalar.layer(Api, {
|
|
42
|
+
path: "/docs"
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
// Merge all the http routes together
|
|
46
|
+
const AllRoutes = Layer.mergeAll(ApiRoutes, DocsRoute)
|
|
47
|
+
|
|
48
|
+
// Create an HTTP server Layer that serves the API routes.
|
|
49
|
+
//
|
|
50
|
+
// Here we are using the NodeHttpServer, but you could also use the
|
|
51
|
+
// BunHttpServer
|
|
52
|
+
export const HttpServerLayer = HttpRouter.serve(AllRoutes).pipe(
|
|
53
|
+
Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
// Then run the server using Layer.launch
|
|
57
|
+
Layer.launch(HttpServerLayer).pipe(
|
|
58
|
+
NodeRuntime.runMain
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
// Or create a web handler, which can be used in serverless environments
|
|
62
|
+
export const { handler, dispose } = HttpRouter.toWebHandler(AllRoutes.pipe(
|
|
63
|
+
Layer.provide(HttpServer.layerServices)
|
|
64
|
+
))
|
|
65
|
+
|
|
66
|
+
// -----------------
|
|
67
|
+
// Client side setup
|
|
68
|
+
// -----------------
|
|
69
|
+
|
|
70
|
+
export const AuthorizationClient = HttpApiMiddleware.layerClient(
|
|
71
|
+
Authorization,
|
|
72
|
+
Effect.fn(function*({ next, request }) {
|
|
73
|
+
// Here you can modify the request and pass it down the middleware chain.
|
|
74
|
+
// This is where you would add authentication tokens, custom headers, etc.
|
|
75
|
+
// For this example, we just add a hardcoded bearer token to all requests.
|
|
76
|
+
return yield* next(HttpClientRequest.bearerToken(request, "dev-token"))
|
|
77
|
+
})
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
// Define the HttpApiClient service, which will be used to make requests to the
|
|
81
|
+
// API.
|
|
82
|
+
export class ApiClient extends Context.Service<ApiClient, HttpApiClient.ForApi<typeof Api>>()("acme/ApiClient") {
|
|
83
|
+
static readonly layer = Layer.effect(
|
|
84
|
+
ApiClient,
|
|
85
|
+
HttpApiClient.make(Api, {
|
|
86
|
+
// Use transformClient to apply middleware to the generated client. This
|
|
87
|
+
// is useful for settings the base url and applying retry policies.
|
|
88
|
+
transformClient: (client) =>
|
|
89
|
+
client.pipe(
|
|
90
|
+
HttpClient.mapRequest(flow(
|
|
91
|
+
HttpClientRequest.prependUrl("http://localhost:3000")
|
|
92
|
+
)),
|
|
93
|
+
HttpClient.retryTransient({
|
|
94
|
+
schedule: Schedule.exponential(100),
|
|
95
|
+
times: 3
|
|
96
|
+
})
|
|
97
|
+
)
|
|
98
|
+
})
|
|
99
|
+
).pipe(
|
|
100
|
+
// Provide the client implementation of the Authorization middleware, which
|
|
101
|
+
// is required.
|
|
102
|
+
Layer.provide(AuthorizationClient),
|
|
103
|
+
// Supply a HttpClient implementation to use for making requests. Here we
|
|
104
|
+
// use the FetchHttpClient, but you could also use the NodeHttpClient or
|
|
105
|
+
// BunHttpClient.
|
|
106
|
+
Layer.provide(FetchHttpClient.layer)
|
|
107
|
+
)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// The generated client mirrors your API definition, so renames and schema
|
|
111
|
+
// changes are checked end-to-end at compile time.
|
|
112
|
+
export const callApi = Effect.gen(function*() {
|
|
113
|
+
const client = yield* ApiClient
|
|
114
|
+
|
|
115
|
+
yield* client.health()
|
|
116
|
+
}).pipe(
|
|
117
|
+
Effect.provide(ApiClient.layer)
|
|
118
|
+
)
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @title Testing HttpApi implementations
|
|
3
|
+
*
|
|
4
|
+
* Test handlers through an in-memory typed client with `HttpApiTest`, without
|
|
5
|
+
* starting an HTTP server or touching a real database.
|
|
6
|
+
*/
|
|
7
|
+
import { assert, layer } from "@effect/vitest"
|
|
8
|
+
import { Effect, Layer } from "effect"
|
|
9
|
+
import { HttpClientRequest, HttpServer } from "effect/unstable/http"
|
|
10
|
+
import { HttpApiMiddleware, HttpApiTest } from "effect/unstable/httpapi"
|
|
11
|
+
import { Api } from "./fixtures/api/Api.ts"
|
|
12
|
+
import { Authorization } from "./fixtures/api/Authorization.ts"
|
|
13
|
+
import { UserId } from "./fixtures/domain/User.ts"
|
|
14
|
+
import { AuthorizationLayer } from "./fixtures/server/Authorization.ts"
|
|
15
|
+
import { Users } from "./fixtures/server/Users.ts"
|
|
16
|
+
import { UsersApiHandlersNoDeps } from "./fixtures/server/Users/http.ts"
|
|
17
|
+
|
|
18
|
+
// Provide the handlers with the in-memory `Users` implementation, so the full
|
|
19
|
+
// HTTP pipeline is exercised without any SQL. The Authorization middleware is
|
|
20
|
+
// provided with `Layer.provideMerge`, because the HTTP pipeline also resolves
|
|
21
|
+
// it when the routes are built.
|
|
22
|
+
const HandlersLayer = UsersApiHandlersNoDeps.pipe(
|
|
23
|
+
Layer.provide(Users.layerMemory),
|
|
24
|
+
Layer.provideMerge(AuthorizationLayer)
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
// The client-side Authorization middleware supplies the bearer token.
|
|
28
|
+
// Providing different middleware implementations lets the tests cover both
|
|
29
|
+
// authorized and unauthorized requests.
|
|
30
|
+
const AuthorizationMiddlewareGood = HttpApiMiddleware.layerClient(
|
|
31
|
+
Authorization,
|
|
32
|
+
({ next, request }) => next(HttpClientRequest.bearerToken(request, "dev-token"))
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
const AuthorizationMiddlewareBad = HttpApiMiddleware.layerClient(
|
|
36
|
+
Authorization,
|
|
37
|
+
// Forward the request without attaching a token
|
|
38
|
+
({ next, request }) => next(request)
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
// `HttpApiTest.groups` builds a typed client wired directly to the handlers of
|
|
42
|
+
// the selected groups, using the same request encoding, routing, and response
|
|
43
|
+
// decoding as a real server.
|
|
44
|
+
const makeClient = HttpApiTest.groups(Api, ["users"])
|
|
45
|
+
|
|
46
|
+
// `HttpServer.layerServices` provides the platform services the HTTP pipeline
|
|
47
|
+
// needs in tests.
|
|
48
|
+
layer(Layer.mergeAll(HandlersLayer, HttpServer.layerServices))("UsersApi", (it) => {
|
|
49
|
+
it.effect("lists, fetches, and creates users", () =>
|
|
50
|
+
Effect.gen(function*() {
|
|
51
|
+
const client = yield* makeClient
|
|
52
|
+
|
|
53
|
+
const created = yield* client.users.create({
|
|
54
|
+
payload: { name: "Alice", email: "alice@acme.dev" }
|
|
55
|
+
})
|
|
56
|
+
assert.strictEqual(created.name, "Alice")
|
|
57
|
+
|
|
58
|
+
const fetched = yield* client.users.getById({
|
|
59
|
+
params: { id: created.id }
|
|
60
|
+
})
|
|
61
|
+
assert.deepStrictEqual(fetched, created)
|
|
62
|
+
|
|
63
|
+
const all = yield* client.users.list({ query: {} })
|
|
64
|
+
assert.isTrue(all.some((user) => user.id === created.id))
|
|
65
|
+
}).pipe(Effect.provide(AuthorizationMiddlewareGood)))
|
|
66
|
+
|
|
67
|
+
it.effect("returns a 404 for a missing user", () =>
|
|
68
|
+
Effect.gen(function*() {
|
|
69
|
+
const client = yield* makeClient
|
|
70
|
+
|
|
71
|
+
// Use Effect.flip to assert on the error channel
|
|
72
|
+
const error = yield* client.users.getById({
|
|
73
|
+
params: { id: UserId.make("019845e1-682f-4b02-a706-3b2422d13aec") }
|
|
74
|
+
}).pipe(Effect.flip)
|
|
75
|
+
assert.strictEqual(error._tag, "UserNotFound")
|
|
76
|
+
}).pipe(Effect.provide(AuthorizationMiddlewareGood)))
|
|
77
|
+
|
|
78
|
+
it.effect("rejects requests without a valid bearer token", () =>
|
|
79
|
+
Effect.gen(function*() {
|
|
80
|
+
const client = yield* makeClient
|
|
81
|
+
|
|
82
|
+
const error = yield* client.users.list({ query: {} }).pipe(Effect.flip)
|
|
83
|
+
assert.strictEqual(error._tag, "Unauthorized")
|
|
84
|
+
}).pipe(Effect.provide(AuthorizationMiddlewareBad)))
|
|
85
|
+
|
|
86
|
+
it.effect("rejects requests with an invalid bearer token", () =>
|
|
87
|
+
Effect.gen(function*() {
|
|
88
|
+
const client = yield* makeClient
|
|
89
|
+
|
|
90
|
+
const error = yield* client.users.getById({
|
|
91
|
+
params: { id: UserId.make("019845e1-682f-4b02-a706-3b2422d13aec") }
|
|
92
|
+
}).pipe(Effect.flip)
|
|
93
|
+
assert.strictEqual(error._tag, "Unauthorized")
|
|
94
|
+
}).pipe(
|
|
95
|
+
Effect.provide(HttpApiMiddleware.layerClient(
|
|
96
|
+
Authorization,
|
|
97
|
+
({ next, request }) => next(HttpClientRequest.bearerToken(request, "wrong-token"))
|
|
98
|
+
))
|
|
99
|
+
))
|
|
100
|
+
})
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { HttpApi, OpenApi } from "effect/unstable/httpapi"
|
|
2
|
+
import { SystemApi } from "./System.ts"
|
|
3
|
+
import { UsersApiGroup } from "./Users.ts"
|
|
4
|
+
|
|
5
|
+
// Defined the root API, which combines all of the groups together. This is the
|
|
6
|
+
// API that you will serve and generate clients for. You can also annotate the
|
|
7
|
+
// API with OpenAPI metadata.
|
|
8
|
+
export class Api extends HttpApi.make("user-api")
|
|
9
|
+
.add(UsersApiGroup)
|
|
10
|
+
.add(SystemApi)
|
|
11
|
+
.annotateMerge(OpenApi.annotations({
|
|
12
|
+
title: "Acme User API"
|
|
13
|
+
}))
|
|
14
|
+
{}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Context, Schema } from "effect"
|
|
2
|
+
import { HttpApiMiddleware, HttpApiSecurity } from "effect/unstable/httpapi"
|
|
3
|
+
import type { User } from "../domain/User.ts"
|
|
4
|
+
|
|
5
|
+
export class CurrentUser extends Context.Service<CurrentUser, User>()("acme/HttpApi/Authorization/CurrentUser") {}
|
|
6
|
+
|
|
7
|
+
export class Unauthorized extends Schema.TaggedError<Unauthorized>()(
|
|
8
|
+
"Unauthorized",
|
|
9
|
+
{
|
|
10
|
+
message: Schema.String
|
|
11
|
+
},
|
|
12
|
+
// You can define error status codes directly on the error class
|
|
13
|
+
{ httpApiStatus: 401 }
|
|
14
|
+
) {}
|
|
15
|
+
|
|
16
|
+
export class Authorization extends HttpApiMiddleware.Service<Authorization, {
|
|
17
|
+
// Middleware can provide services to other middleware and endpoints, which is
|
|
18
|
+
// useful for things like authentication, where you want to inject the current
|
|
19
|
+
// user into the context for other endpoints to consume.
|
|
20
|
+
provides: CurrentUser
|
|
21
|
+
// If your middleware requires dependencies from other middleware, you can
|
|
22
|
+
// specify those as well.
|
|
23
|
+
requires: never
|
|
24
|
+
}>()("acme/HttpApi/Authorization", {
|
|
25
|
+
// This middleware requires clients to also provide an implementation, to
|
|
26
|
+
// inject a api key
|
|
27
|
+
requiredForClient: true,
|
|
28
|
+
// Middleware can optionally define security schemes, which are used to
|
|
29
|
+
// generate OpenAPI docs and decode credientials from incoming requests for
|
|
30
|
+
// you.
|
|
31
|
+
security: {
|
|
32
|
+
bearer: HttpApiSecurity.bearer
|
|
33
|
+
},
|
|
34
|
+
// Middlware can specify errors that it may raise
|
|
35
|
+
error: Unauthorized
|
|
36
|
+
}) {}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/unstable/httpapi"
|
|
2
|
+
|
|
3
|
+
// Top level groups are added to the root of the derived HttpApiClient.
|
|
4
|
+
//
|
|
5
|
+
// `client.health()`
|
|
6
|
+
export class SystemApi extends HttpApiGroup.make("system", { topLevel: true }).add(
|
|
7
|
+
HttpApiEndpoint.get("health", "/health", {
|
|
8
|
+
success: HttpApiSchema.NoContent
|
|
9
|
+
})
|
|
10
|
+
) {}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { Schema } from "effect"
|
|
2
|
+
import { HttpApiEndpoint, HttpApiError, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
|
|
3
|
+
import { User, UserId } from "../domain/User.ts"
|
|
4
|
+
import { SearchQueryTooShort, UserNotFound } from "../domain/UserErrors.ts"
|
|
5
|
+
import { Authorization } from "./Authorization.ts"
|
|
6
|
+
|
|
7
|
+
export class UsersApiGroup extends HttpApiGroup.make("users")
|
|
8
|
+
.add(
|
|
9
|
+
HttpApiEndpoint.get("list", "/", {
|
|
10
|
+
query: {
|
|
11
|
+
search: Schema.optional(Schema.String)
|
|
12
|
+
},
|
|
13
|
+
// Use the `json` variant of the model for API responses. It shares the
|
|
14
|
+
// field declarations with the database variants, but can encode values
|
|
15
|
+
// differently where needed.
|
|
16
|
+
success: Schema.Array(User.json)
|
|
17
|
+
}),
|
|
18
|
+
HttpApiEndpoint.get("search", "/search", {
|
|
19
|
+
// For get requests, payload uses the query string
|
|
20
|
+
payload: {
|
|
21
|
+
search: Schema.String
|
|
22
|
+
},
|
|
23
|
+
success: [
|
|
24
|
+
Schema.Array(User.json),
|
|
25
|
+
Schema.String.pipe(HttpApiSchema.asText({
|
|
26
|
+
contentType: "text/csv"
|
|
27
|
+
}))
|
|
28
|
+
],
|
|
29
|
+
error: [
|
|
30
|
+
SearchQueryTooShort.pipe(
|
|
31
|
+
// If you want an error to return no content, you can use
|
|
32
|
+
// `HttpApiSchema.asNoContent` and provide a decoder that transforms the
|
|
33
|
+
// error into the appropriate type.
|
|
34
|
+
HttpApiSchema.asNoContent({
|
|
35
|
+
decode: () => new SearchQueryTooShort()
|
|
36
|
+
})
|
|
37
|
+
),
|
|
38
|
+
// You can also add some of the built in `HttpApiError`s to handle common
|
|
39
|
+
// error cases like bad requests, unauthorized, etc.
|
|
40
|
+
HttpApiError.RequestTimeoutNoContent
|
|
41
|
+
]
|
|
42
|
+
}),
|
|
43
|
+
HttpApiEndpoint.get("getById", "/:id", {
|
|
44
|
+
params: {
|
|
45
|
+
// Path parameter values are automatically coerced from their string
|
|
46
|
+
// form using `Schema.toCodecStringTree`, so schemas that decode from
|
|
47
|
+
// other types (like numbers) work here as well.
|
|
48
|
+
id: UserId
|
|
49
|
+
},
|
|
50
|
+
success: User.json,
|
|
51
|
+
error: UserNotFound.pipe(
|
|
52
|
+
// If you want an error to return no content, you can use
|
|
53
|
+
// `HttpApiSchema.asNoContent` and provide a decoder that transforms the
|
|
54
|
+
// error into the appropriate type.
|
|
55
|
+
HttpApiSchema.asNoContent({
|
|
56
|
+
decode: () => new UserNotFound()
|
|
57
|
+
})
|
|
58
|
+
)
|
|
59
|
+
}),
|
|
60
|
+
HttpApiEndpoint.post("create", "/", {
|
|
61
|
+
// For post requests, payload uses the request body. It defaults to JSON,
|
|
62
|
+
// but you can specify other content types as well using
|
|
63
|
+
// `HttpApiSchema.asText`, `HttpApiSchema.asMultipart`, etc.
|
|
64
|
+
//
|
|
65
|
+
// The `jsonCreate` variant only exposes the fields clients are allowed
|
|
66
|
+
// to provide, so the generated id and timestamps cannot be set here.
|
|
67
|
+
payload: User.jsonCreate,
|
|
68
|
+
success: User.json
|
|
69
|
+
}),
|
|
70
|
+
HttpApiEndpoint.patch("update", "/:id", {
|
|
71
|
+
params: {
|
|
72
|
+
id: UserId
|
|
73
|
+
},
|
|
74
|
+
// The `jsonUpdate` variant similarly excludes the id and the managed
|
|
75
|
+
// timestamps from the update payload.
|
|
76
|
+
payload: User.jsonUpdate,
|
|
77
|
+
success: User.json,
|
|
78
|
+
error: UserNotFound.pipe(
|
|
79
|
+
HttpApiSchema.asNoContent({
|
|
80
|
+
decode: () => new UserNotFound()
|
|
81
|
+
})
|
|
82
|
+
)
|
|
83
|
+
}),
|
|
84
|
+
HttpApiEndpoint.get("me", "/me", {
|
|
85
|
+
success: User.json,
|
|
86
|
+
error: UserNotFound.pipe(HttpApiSchema.status(404))
|
|
87
|
+
})
|
|
88
|
+
)
|
|
89
|
+
// You can apply middleware to entire groups, which is useful for things like
|
|
90
|
+
// authentication and authorization.
|
|
91
|
+
//
|
|
92
|
+
// You can also apply middleware to individual endpoints if you need more
|
|
93
|
+
// fine-grained control.
|
|
94
|
+
.middleware(Authorization)
|
|
95
|
+
// To add a common prefix to all endpoints in a group, you can use the `prefix`
|
|
96
|
+
// method. This is useful for grouping related endpoints together under a common
|
|
97
|
+
// path segment. In this case, all endpoints in the `UsersApiGroup` will be
|
|
98
|
+
// prefixed with `/users`.
|
|
99
|
+
.prefix("/users")
|
|
100
|
+
// You can add OpenAPI annotations to groups, endpoints, and even parameters and
|
|
101
|
+
// request bodies. These will be merged together to generate the final OpenAPI
|
|
102
|
+
// docs for the API
|
|
103
|
+
.annotateMerge(OpenApi.annotations({
|
|
104
|
+
title: "Users",
|
|
105
|
+
description: "User management endpoints"
|
|
106
|
+
}))
|
|
107
|
+
{}
|