@xata.io/client 0.0.0-alpha.vf2043e7 → 0.0.0-alpha.vf20a10c

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 CHANGED
@@ -1 +1,280 @@
1
- Visit https://github.com/xataio/client-ts for more information.
1
+ # Xata SDK for TypeScript and JavaScript
2
+
3
+ The Xata SDK supports typescript definitions for your Xata database schema. It also works with JavaScript.
4
+
5
+ It has zero dependencies and runs in Node.js, V8, Deno and Bun.
6
+
7
+ ## Installation
8
+
9
+ See our [docs](https://xata.io/docs/sdk/typescript#installation) to get started using the Xata SDK.
10
+
11
+
12
+ ## Table of Contents
13
+
14
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
15
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
16
+
17
+ - [Installation](#installation)
18
+ - [Usage](#usage)
19
+ - [Schema-generated Client](#schema-generated-client)
20
+ - [Schema-less Client](#schema-less-client)
21
+ - [API Design](#api-design)
22
+ - [Creating Records](#creating-records)
23
+ - [Query a Single Record by its ID](#query-a-single-record-by-its-id)
24
+ - [Querying Multiple Records](#querying-multiple-records)
25
+ - [Updating Records](#updating-records)
26
+ - [Deleting Records](#deleting-records)
27
+ - [API Client](#api-client)
28
+ - [Deno support](#deno-support)
29
+
30
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
31
+
32
+ ## Manual Installation
33
+
34
+ ```bash
35
+ npm install @xata.io/client
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ There are three ways to use the SDK:
41
+
42
+ - **Schema-generated Client**: SDK to create/read/update/delete records in a given database following a schema file (with type-safety).
43
+ - **Schema-less Client**: SDK to create/read/update/delete records in any database without schema validation (with partial type-safety).
44
+ - **API Client**: SDK to interact with the whole Xata API and all its endpoints.
45
+
46
+ ### Schema-generated Client
47
+
48
+ To use the schema-generated client, you need to run the code generator utility that comes with [our CLI](https://docs.xata.io/cli/getting-started).
49
+
50
+ To run it (and assuming you have configured the project with `xata init`):
51
+
52
+ ```bash
53
+ xata codegen
54
+ ```
55
+
56
+ In a TypeScript file, start using the generated code like this:
57
+
58
+ ```ts
59
+ import { XataClient } from './xata'; // or wherever you chose to generate the client
60
+
61
+ const xata = new XataClient();
62
+ ```
63
+
64
+ The import above will differ if you chose to generate the code in a different location.
65
+
66
+ The `XataClient` constructor accepts an object with configuration options, like the `fetch` parameter, which is required only if your runtime doesn't provide a global `fetch` function. There's also a `databaseURL` argument that by default will contain a URL pointing to your database (e.g. `https://myworkspace-123abc.xata.sh/db/databasename`). It can be specified in the constructor to overwrite that value if for whatever reason you need to connect to a different workspace or database.
67
+
68
+ The code generator will create two TypeScript types for each schema entity. The base one will be an `Identifiable` entity with the internal properties your entity has and the `Record` one will extend it with a set of operations (update, delete, etc...) and some schema metadata (xata version).
69
+
70
+ ```ts
71
+ interface User extends Identifiable {
72
+ email?: string | null;
73
+ }
74
+
75
+ type UserRecord = User & XataRecord;
76
+
77
+ async function initializeDatabase(admin: User): Promise<UserRecord> {
78
+ return xata.db.users.create(admin);
79
+ }
80
+
81
+ const admin = await initializeDatabase({ email: 'admin@example.com' });
82
+ await admin.update({ email: 'admin@foo.bar' });
83
+ await admin.delete();
84
+ ```
85
+
86
+ You will learn more about the available operations below, under the [`API Design`](#api-design) section.
87
+
88
+ ### Schema-less Client
89
+
90
+ If you don't have a schema file, or you are building a generic way to interact with Xata, you can use the `BaseClient` class without schema validation.
91
+
92
+ ```ts
93
+ import { BaseClient } from '@xata.io/client';
94
+
95
+ const xata = new BaseClient({
96
+ branch: 'branchname',
97
+ apiKey: 'xau_1234abcdef',
98
+ fetch: fetchImplementation // Required if your runtime doesn't provide a global `fetch` function.
99
+ });
100
+ ```
101
+
102
+ It works the same way as the code-generated `XataClient` but doesn't provide type-safety for your model.
103
+
104
+ You can read more on the methods available below, in the next section.
105
+
106
+ ### API Design
107
+
108
+ The Xata SDK to create/read/update/delete records follows the [repository pattern](https://lyz-code.github.io/blue-book/architecture/repository_pattern/). Each table will have a repository object available at `xata.db.[table-name]`.
109
+
110
+ For example if you have a `users` table, there'll be a repository at `xata.db.users`. If you're using the schema-less client, you can also use the `xata.db.[table-name]` syntax to access the repository but without TypeScript auto-completion.
111
+
112
+ #### Creating Records
113
+
114
+ Invoke the `create()` method in the repository. Example:
115
+
116
+ ```ts
117
+ const user = await xata.db.users.create({
118
+ fullName: 'John Smith'
119
+ });
120
+ ```
121
+
122
+ If you want to create a record with a specific ID, you can provide the id as parameter to the `create()` method.
123
+
124
+ ```ts
125
+ const user = await xata.db.users.create('user_admin', {
126
+ fullName: 'John Smith'
127
+ });
128
+ ```
129
+
130
+ And if you want to create or update a record with a specific ID, you can invoke `createOrUpdate()` with an id parameter.
131
+
132
+ ```ts
133
+ const user = await xata.db.users.createOrUpdate('user_admin', {
134
+ fullName: 'John Smith'
135
+ });
136
+ ```
137
+
138
+ #### Query a Single Record by its ID
139
+
140
+ ```ts
141
+ // `user` will be null if the record cannot be found
142
+ const user = await xata.db.users.read('rec_1234abcdef');
143
+ ```
144
+
145
+ #### Querying Multiple Records
146
+
147
+ ```ts
148
+ // Query records selecting all fields.
149
+ const page = await xata.db.users.select().getPaginated();
150
+ const user = await xata.db.users.select().getFirst();
151
+
152
+ // You can also use `xata.db.users` directly, since it's an immutable Query too!
153
+ const page = await xata.db.users.getPaginated();
154
+ const user = await xata.db.users.getFirst();
155
+
156
+ // Query records selecting just one or more fields
157
+ const page = await xata.db.users.select('email', 'profile').getPaginated();
158
+
159
+ // Apply constraints
160
+ const page = await xata.db.users.filter('email', 'foo@example.com').getPaginated();
161
+
162
+ // Sorting
163
+ const page = await xata.db.users.sort('full_name', 'asc').getPaginated();
164
+ ```
165
+
166
+ Query operations (`select()`, `filter()`, `sort()`) return a `Query` object. These objects are immutable. You can add additional constraints, `sort`, etc. by calling their methods, and a new query will be returned. In order to finally make a query to the database you'll invoke `getPaginated()`, `getMany()`, `getAll()`, or `getFirst()`.
167
+
168
+ To learn the differences between these methods, see the [reference](https://docs.xata.io/sdk/reference#query).
169
+
170
+ ```ts
171
+ // Operators that combine multiple conditions can be deconstructed
172
+ const { filter, any, all, not, sort } = xata.db.users;
173
+ const query = filter('email', 'foo@example.com');
174
+
175
+ // Single-column operators are imported directly from the package
176
+ import { gt, includes, startsWith } from '@xata.io/client';
177
+ filter('email', startsWith('username')).not(filter('created_at', gt(somePastDate)));
178
+
179
+ // Queries are immutable objects. This is useful to derive queries from other queries
180
+ const admins = filter('admin', true);
181
+ const spaniardsAdmins = admins.filter('country', 'Spain');
182
+ await admins.getAll(); // still returns all admins
183
+
184
+ // Finally fetch the results of the query
185
+ const users = await query.getAll();
186
+ const firstUser = await query.getFirst();
187
+ ```
188
+
189
+ The `getPaginated()` method will return a `Page` object. It's a wrapper that internally uses cursor based pagination.
190
+
191
+ ```ts
192
+ page.records; // Array of records
193
+ page.hasNextPage(); // Boolean
194
+
195
+ const nextPage = await page.nextPage(); // Page object
196
+ const previousPage = await page.previousPage(); // Page object
197
+ const startPage = await page.startPage(); // Page object
198
+ const endPage = await page.endPage(); // Page object
199
+ ```
200
+
201
+ If you want to use an iterator, both the Repository and the Query classes implement an `AsyncIterable`. Alternatively you can use `getIterator()` and customize the batch size of the iterator:
202
+
203
+ ```ts
204
+ for await (const record of xata.db.users) {
205
+ console.log(record);
206
+ }
207
+
208
+ for await (const record of xata.db.users.filter('team.id', teamId)) {
209
+ console.log(record);
210
+ }
211
+
212
+ for await (const records of xata.db.users.getIterator({ batchSize: 100 })) {
213
+ console.log(records);
214
+ }
215
+ ```
216
+
217
+ #### Updating Records
218
+
219
+ Updating a record leaves the existing object unchanged, but returns a new object with the updated values.
220
+
221
+ ```ts
222
+ // Using an existing object
223
+ const updatedUser = await user.update({
224
+ fullName: 'John Smith Jr.'
225
+ });
226
+
227
+ // Using a record id
228
+ const updatedUser = await xata.db.users.update('rec_1234abcdef', {
229
+ fullName: 'John Smith Jr.'
230
+ });
231
+ ```
232
+
233
+ #### Deleting Records
234
+
235
+ ```ts
236
+ // Using an existing object
237
+ await user.delete();
238
+
239
+ // Using a record id
240
+ await xata.db.users.delete('rec_1234abcdef');
241
+ ```
242
+
243
+ ### API Client
244
+
245
+ One of the main features of the SDK is the ability to interact with the whole Xata API and perform administrative operations such as creating/reading/updating/deleting [workspaces](https://docs.xata.io/concepts/workspaces), databases, tables, branches...
246
+
247
+ To communicate with the SDK we provide a constructor called `XataApiClient` that accepts an API token and an optional fetch implementation method.
248
+
249
+ ```ts
250
+ const api = new XataApiClient({ apiKey: process.env.XATA_API_KEY });
251
+ ```
252
+
253
+ Once you have initialized the API client, the operations are organized following the same hiearchy as in the [official documentation](https://docs.xata.io). You have different namespaces for each entity (ie. `workspaces`, `databases`, `tables`, `branches`, `users`, `records`...).
254
+
255
+ ```ts
256
+ const { id: workspace } = await api.workspaces.createWorkspace({ name: 'example' });
257
+ const { databaseName } = await api.database.createDatabase(workspace, 'database', { region: 'eu-west-1' });
258
+
259
+ await api.branches.createBranch(workspace, databaseName, 'branch');
260
+ await api.tables.createTable(workspace, databaseName, 'branch', 'table');
261
+ await api.tables.setTableSchema(workspace, databaseName, 'branch', 'table', {
262
+ columns: [{ name: 'email', type: 'string' }]
263
+ });
264
+
265
+ const { id: recordId } = await api.records.insertRecord(workspace, databaseName, 'branch', 'table', {
266
+ email: 'example@foo.bar'
267
+ });
268
+
269
+ const record = await api.records.getRecord(workspace, databaseName, 'branch', 'table', recordId);
270
+
271
+ await api.workspaces.deleteWorkspace(workspace);
272
+ ```
273
+
274
+ ## Deno support
275
+
276
+ We publish the client on [deno.land](https://deno.land/x/xata). You can use it by changing the import in the auto-generated `xata.ts` file:
277
+
278
+ ```ts
279
+ import { buildClient, BaseClientOptions, XataRecord } from 'https://deno.land/x/xata/mod.ts';
280
+ ```