@xata.io/client 0.11.0 → 0.12.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @xata.io/client
2
2
 
3
+ ## 0.12.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#376](https://github.com/xataio/client-ts/pull/376) [`db3c88e`](https://github.com/xataio/client-ts/commit/db3c88e1f2bee6d308afb8d6e95b7c090a87e7a7) Thanks [@SferaDev](https://github.com/SferaDev)! - Hide xata object and expose getMetadata method
8
+
9
+ ### Patch Changes
10
+
11
+ - [#364](https://github.com/xataio/client-ts/pull/364) [`1cde95f`](https://github.com/xataio/client-ts/commit/1cde95f05a6b9fbf0564ea05400140f0cef41a3a) Thanks [@SferaDev](https://github.com/SferaDev)! - Add peer dep of TS 4.5+
12
+
13
+ * [#362](https://github.com/xataio/client-ts/pull/362) [`57bf0e2`](https://github.com/xataio/client-ts/commit/57bf0e2e049ed0498683ff42d287983f295342b7) Thanks [@SferaDev](https://github.com/SferaDev)! - Do not show error if date is not defined
14
+
3
15
  ## 0.11.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -1 +1,258 @@
1
- Visit https://github.com/xataio/client-ts for more information.
1
+ # Xata SDK for TypeScript and JavaScript
2
+
3
+ This SDK has zero dependencies, so it can be used in many JavaScript runtimes including Node.js, Cloudflare workers, Deno, Electron, etc.
4
+
5
+ It also works in browsers for the same reason. But this is strongly discouraged because the API token would be leaked.
6
+
7
+ ## Installing
8
+
9
+ ```bash
10
+ npm install @xata.io/client
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ There are three ways to use the SDK:
16
+
17
+ - **Schema-generated Client**: SDK to create/read/update/delete records in a given database following a schema file (with type-safety).
18
+ - **Schema-less Client**: SDK to create/read/update/delete records in any database without schema validation (with partial type-safety).
19
+ - **API Client**: SDK to interact with the whole Xata API and all its endpoints.
20
+
21
+ ### Schema-generated Client
22
+
23
+ To use the schema-generated client, you need to run the code generator utility that comes with [our CLI](../../cli/README.md).
24
+
25
+ To run it (and assuming you have configured the project with `xata init`):
26
+
27
+ ```bash
28
+ xata codegen
29
+ ```
30
+
31
+ In a TypeScript file start using the generated code:
32
+
33
+ ```ts
34
+ import { XataClient } from './xata';
35
+
36
+ const xata = new XataClient({
37
+ fetch: fetchImplementation // Required if your runtime doesn't provide a global `fetch` function.
38
+ });
39
+ ```
40
+
41
+ The import above will differ if you chose to genreate the code in a different location.
42
+
43
+ The `fetch` paramter 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.
44
+
45
+ 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).
46
+
47
+ ```ts
48
+ interface User extends Identifiable {
49
+ email?: string | null;
50
+ }
51
+
52
+ type UserRecord = User & XataRecord;
53
+
54
+ async function initializeDatabase(admin: User): Promise<UserRecord> {
55
+ return xata.db.users.create(admin);
56
+ }
57
+
58
+ const admin = await initializeDatabase({ email: 'admin@example.com' });
59
+ await admin.update({ email: 'admin@foo.bar' });
60
+ await admin.delete();
61
+ ```
62
+
63
+ You will learn more about the available operations below, under the `API Design` section.
64
+
65
+ ### Schema-less Client
66
+
67
+ 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.
68
+
69
+ ```ts
70
+ import { BaseClient } from '@xata.io/client';
71
+
72
+ const xata = new BaseClient({
73
+ branch: 'branchname',
74
+ apiKey: 'xau_1234abcdef',
75
+ fetch: fetchImplementation // Required if your runtime doesn't provide a global `fetch` function.
76
+ });
77
+ ```
78
+
79
+ It works the same way as the code-generated `XataClient` but doesn't provide type-safety for your model.
80
+
81
+ You can read more on the methods available below, under the `API Design` section.
82
+
83
+ ### API Design
84
+
85
+ The Xata SDK to create/read/update/delete records follows the repository pattern. Each table will have a repository object available at `xata.db.[table-name]`.
86
+
87
+ 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.
88
+
89
+ **Creating objects**
90
+
91
+ Invoke the `create()` method in the repository. Example:
92
+
93
+ ```ts
94
+ const user = await xata.db.users.create({
95
+ fullName: 'John Smith'
96
+ });
97
+ ```
98
+
99
+ If you want to create a record with a specific ID, you can invoke `insert()`.
100
+
101
+ ```ts
102
+ const user = await xata.db.users.insert('user_admin', {
103
+ fullName: 'John Smith'
104
+ });
105
+ ```
106
+
107
+ And if you want to create or insert a record with a specific ID, you can invoke `updateOrInsert()`.
108
+
109
+ ```ts
110
+ const user = await client.db.users.updateOrInsert('user_admin', {
111
+ fullName: 'John Smith'
112
+ });
113
+ ```
114
+
115
+ **Query a single object by its id**
116
+
117
+ ```ts
118
+ // `user` will be null if the object cannot be found
119
+ const user = await xata.db.users.read('rec_1234abcdef');
120
+ ```
121
+
122
+ **Querying multiple objects**
123
+
124
+ ```ts
125
+ // Query objects selecting all fields.
126
+ const users = await xata.db.users.select().getMany();
127
+ const user = await xata.db.users.select().getFirst();
128
+
129
+ // You can also use `xata.db.users` directly, since it's an immutable Query too!
130
+ const users = await xata.db.users.getMany();
131
+ const user = await xata.db.users.getFirst();
132
+
133
+ // Query objects selecting just one or more fields
134
+ const users = await xata.db.users.select('email', 'profile').getMany();
135
+
136
+ // Apply constraints
137
+ const users = await xata.db.users.filter('email', 'foo@example.com').getMany();
138
+
139
+ // Sorting
140
+ const users = await xata.db.users.sort('fullName', 'asc').getMany();
141
+ ```
142
+
143
+ 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 `getAll()`, `getFirst()`, `getMany()` or `getPaginated()`.
144
+
145
+ ```ts
146
+ // Operators that combine multiple conditions can be deconstructed
147
+ const { filter, any, all, not, sort } = xata.db.users;
148
+ const query = filter('email', 'foo@example.com');
149
+
150
+ // Single-column operators are imported directly from the package
151
+ import { gt, includes, startsWith } from '@xata.io/client';
152
+ filter('email', startsWith('username')).not(filter('created_at', gt(somePastDate)));
153
+
154
+ // Queries are immutable objects. This is useful to derive queries from other queries
155
+ const admins = filter('admin', true);
156
+ const spaniardsAdmins = admins.filter('country', 'Spain');
157
+ await admins.getMany(); // still returns all admins
158
+
159
+ // Finally fetch the results of the query
160
+ const users = await query.getMany();
161
+ const firstUser = await query.getFirst();
162
+
163
+ // Also you can paginate the results
164
+ const page = await query.getPaginated();
165
+ const hasPage2 = page.hasNextPage();
166
+ const page2 = await page.nextPage();
167
+ ```
168
+
169
+ 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:
170
+
171
+ ```ts
172
+ for await (const record of xata.db.users) {
173
+ console.log(record);
174
+ }
175
+
176
+ for await (const record of xata.db.users.filter('team.id', teamId)) {
177
+ console.log(record);
178
+ }
179
+
180
+ for await (const records of xata.db.users.getIterator({ batchSize: 100 })) {
181
+ console.log(records);
182
+ }
183
+ ```
184
+
185
+ **Updating objects**
186
+
187
+ Updating an object leaves the existing instance unchanged, but returns a new object with the updated values.
188
+
189
+ ```ts
190
+ // Using an existing object
191
+ const updatedUser = await user.update({
192
+ fullName: 'John Smith Jr.'
193
+ });
194
+
195
+ // Using an object's id
196
+ const updatedUser = await xata.db.users.update('rec_1234abcdef', {
197
+ fullName: 'John Smith Jr.'
198
+ });
199
+ ```
200
+
201
+ **Deleting objects**
202
+
203
+ ```ts
204
+ // Using an existing object
205
+ await user.delete();
206
+
207
+ // Using an object's id
208
+ await xata.db.users.delete('rec_1234abcdef');
209
+ ```
210
+
211
+ #### Deno support
212
+
213
+ Right now we are still not publishing the client on deno.land or have support for deno in the codegen.
214
+
215
+ However you can already use it with your preferred node CDN with the following import in the auto-generated `xata.ts` file:
216
+
217
+ ```ts
218
+ import {
219
+ BaseClient,
220
+ Query,
221
+ Repository,
222
+ RestRespositoryFactory,
223
+ XataClientOptions,
224
+ XataRecord
225
+ } from 'https://esm.sh/@xata.io/client@<version>/dist/schema?target=deno';
226
+ ```
227
+
228
+ ### API Client
229
+
230
+ 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, databases, tables, branches...
231
+
232
+ To communicate with the SDK we provide a constructor called `XataApiClient` that accepts an API token and an optional fetch implementation method.
233
+
234
+ ```ts
235
+ const api = new XataApiClient({ apiKey: process.env.XATA_API_KEY });
236
+ ```
237
+
238
+ 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`...).
239
+
240
+ ```ts
241
+ const { id: workspace } = await client.workspaces.createWorkspace({ name: 'example', slug: 'example' });
242
+
243
+ const { databaseName } = await client.databases.createDatabase(workspace, 'database');
244
+
245
+ await client.branches.createBranch(workspace, databaseName, 'branch');
246
+ await client.tables.createTable(workspace, databaseName, 'branch', 'table');
247
+ await client.tables.setTableSchema(workspace, databaseName, 'branch', 'table', {
248
+ columns: [{ name: 'email', type: 'string' }]
249
+ });
250
+
251
+ const { id: recordId } = await client.records.insertRecord(workspace, databaseName, 'branch', 'table', {
252
+ email: 'example@foo.bar'
253
+ });
254
+
255
+ const record = await client.records.getRecord(workspace, databaseName, 'branch', 'table', recordId);
256
+
257
+ await client.workspaces.deleteWorkspace(workspace);
258
+ ```
package/dist/index.cjs CHANGED
@@ -1142,7 +1142,9 @@ function isIdentifiable(x) {
1142
1142
  return isObject(x) && isString(x?.id);
1143
1143
  }
1144
1144
  function isXataRecord(x) {
1145
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1145
+ const record = x;
1146
+ const metadata = record?.getMetadata();
1147
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1146
1148
  }
1147
1149
 
1148
1150
  function isSortFilterString(value) {
@@ -1532,7 +1534,8 @@ const transformObjectLinks = (object) => {
1532
1534
  };
1533
1535
  const initObject = (db, schema, table, object) => {
1534
1536
  const result = {};
1535
- Object.assign(result, object);
1537
+ const { xata, ...rest } = object ?? {};
1538
+ Object.assign(result, rest);
1536
1539
  const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1537
1540
  if (!columns)
1538
1541
  console.error(`Table ${table} not found in schema`);
@@ -1540,10 +1543,10 @@ const initObject = (db, schema, table, object) => {
1540
1543
  const value = result[column.name];
1541
1544
  switch (column.type) {
1542
1545
  case "datetime": {
1543
- const date = new Date(value);
1544
- if (isNaN(date.getTime())) {
1546
+ const date = value !== void 0 ? new Date(value) : void 0;
1547
+ if (date && isNaN(date.getTime())) {
1545
1548
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1546
- } else {
1549
+ } else if (date) {
1547
1550
  result[column.name] = date;
1548
1551
  }
1549
1552
  break;
@@ -1568,7 +1571,10 @@ const initObject = (db, schema, table, object) => {
1568
1571
  result.delete = function() {
1569
1572
  return db[table].delete(result["id"]);
1570
1573
  };
1571
- for (const prop of ["read", "update", "delete"]) {
1574
+ result.getMetadata = function() {
1575
+ return xata;
1576
+ };
1577
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1572
1578
  Object.defineProperty(result, prop, { enumerable: false });
1573
1579
  }
1574
1580
  Object.freeze(result);