@xata.io/client 0.0.0-alpha.vf963379 → 0.0.0-alpha.vf9cb959
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 +20 -0
- package/README.md +265 -1
- package/dist/index.cjs +47 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +59 -26
- package/dist/index.mjs +47 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
@@ -1,5 +1,25 @@
|
|
1
1
|
# @xata.io/client
|
2
2
|
|
3
|
+
## 0.13.0
|
4
|
+
|
5
|
+
### Minor Changes
|
6
|
+
|
7
|
+
- [#375](https://github.com/xataio/client-ts/pull/375) [`c9f34ad`](https://github.com/xataio/client-ts/commit/c9f34ad37d75203083a1dec2fac2b03e096521af) Thanks [@SferaDev](https://github.com/SferaDev)! - Change default pagination size to 20
|
8
|
+
|
9
|
+
* [#375](https://github.com/xataio/client-ts/pull/375) [`5f82e43`](https://github.com/xataio/client-ts/commit/5f82e4394010f40dcbf3faf2d0bdb58a6fc1c37a) Thanks [@SferaDev](https://github.com/SferaDev)! - Return a paginable object in getPaginated
|
10
|
+
|
11
|
+
## 0.12.0
|
12
|
+
|
13
|
+
### Minor Changes
|
14
|
+
|
15
|
+
- [#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
|
16
|
+
|
17
|
+
### Patch Changes
|
18
|
+
|
19
|
+
- [#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+
|
20
|
+
|
21
|
+
* [#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
|
22
|
+
|
3
23
|
## 0.11.0
|
4
24
|
|
5
25
|
### Minor Changes
|
package/README.md
CHANGED
@@ -1 +1,265 @@
|
|
1
|
-
|
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 page = await xata.db.users.select().getPaginated();
|
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 page = await xata.db.users.getPaginated();
|
131
|
+
const user = await xata.db.users.getFirst();
|
132
|
+
|
133
|
+
// Query objects selecting just one or more fields
|
134
|
+
const page = await xata.db.users.select('email', 'profile').getPaginated();
|
135
|
+
|
136
|
+
// Apply constraints
|
137
|
+
const page = await xata.db.users.filter('email', 'foo@example.com').getPaginated();
|
138
|
+
|
139
|
+
// Sorting
|
140
|
+
const page = await xata.db.users.sort('full_name', 'asc').getPaginated();
|
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 `getPaginated()`, `getMany()`, `getAll()`, or `getFirst()`.
|
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.getAll(); // still returns all admins
|
158
|
+
|
159
|
+
// Finally fetch the results of the query
|
160
|
+
const users = await query.getAll();
|
161
|
+
const firstUser = await query.getFirst();
|
162
|
+
```
|
163
|
+
|
164
|
+
The `getPaginated()` method will return a `Page` object. It's a wrapper that internally uses cursor based pagination.
|
165
|
+
|
166
|
+
```ts
|
167
|
+
page.records; // Array of records
|
168
|
+
page.hasNextPage(); // Boolean
|
169
|
+
|
170
|
+
const nextPage = await page.nextPage(); // Page object
|
171
|
+
const previousPage = await page.previousPage(); // Page object
|
172
|
+
const firstPage = await page.firstPage(); // Page object
|
173
|
+
const lastPage = await page.lastPage(); // Page object
|
174
|
+
```
|
175
|
+
|
176
|
+
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:
|
177
|
+
|
178
|
+
```ts
|
179
|
+
for await (const record of xata.db.users) {
|
180
|
+
console.log(record);
|
181
|
+
}
|
182
|
+
|
183
|
+
for await (const record of xata.db.users.filter('team.id', teamId)) {
|
184
|
+
console.log(record);
|
185
|
+
}
|
186
|
+
|
187
|
+
for await (const records of xata.db.users.getIterator({ batchSize: 100 })) {
|
188
|
+
console.log(records);
|
189
|
+
}
|
190
|
+
```
|
191
|
+
|
192
|
+
**Updating objects**
|
193
|
+
|
194
|
+
Updating an object leaves the existing instance unchanged, but returns a new object with the updated values.
|
195
|
+
|
196
|
+
```ts
|
197
|
+
// Using an existing object
|
198
|
+
const updatedUser = await user.update({
|
199
|
+
fullName: 'John Smith Jr.'
|
200
|
+
});
|
201
|
+
|
202
|
+
// Using an object's id
|
203
|
+
const updatedUser = await xata.db.users.update('rec_1234abcdef', {
|
204
|
+
fullName: 'John Smith Jr.'
|
205
|
+
});
|
206
|
+
```
|
207
|
+
|
208
|
+
**Deleting objects**
|
209
|
+
|
210
|
+
```ts
|
211
|
+
// Using an existing object
|
212
|
+
await user.delete();
|
213
|
+
|
214
|
+
// Using an object's id
|
215
|
+
await xata.db.users.delete('rec_1234abcdef');
|
216
|
+
```
|
217
|
+
|
218
|
+
### API Client
|
219
|
+
|
220
|
+
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...
|
221
|
+
|
222
|
+
To communicate with the SDK we provide a constructor called `XataApiClient` that accepts an API token and an optional fetch implementation method.
|
223
|
+
|
224
|
+
```ts
|
225
|
+
const api = new XataApiClient({ apiKey: process.env.XATA_API_KEY });
|
226
|
+
```
|
227
|
+
|
228
|
+
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`...).
|
229
|
+
|
230
|
+
```ts
|
231
|
+
const { id: workspace } = await client.workspaces.createWorkspace({ name: 'example', slug: 'example' });
|
232
|
+
|
233
|
+
const { databaseName } = await client.databases.createDatabase(workspace, 'database');
|
234
|
+
|
235
|
+
await client.branches.createBranch(workspace, databaseName, 'branch');
|
236
|
+
await client.tables.createTable(workspace, databaseName, 'branch', 'table');
|
237
|
+
await client.tables.setTableSchema(workspace, databaseName, 'branch', 'table', {
|
238
|
+
columns: [{ name: 'email', type: 'string' }]
|
239
|
+
});
|
240
|
+
|
241
|
+
const { id: recordId } = await client.records.insertRecord(workspace, databaseName, 'branch', 'table', {
|
242
|
+
email: 'example@foo.bar'
|
243
|
+
});
|
244
|
+
|
245
|
+
const record = await client.records.getRecord(workspace, databaseName, 'branch', 'table', recordId);
|
246
|
+
|
247
|
+
await client.workspaces.deleteWorkspace(workspace);
|
248
|
+
```
|
249
|
+
|
250
|
+
## Deno support
|
251
|
+
|
252
|
+
Right now we are still not publishing the client on deno.land or have support for deno in the codegen.
|
253
|
+
|
254
|
+
However you can already use it with your preferred node CDN with the following import in the auto-generated `xata.ts` file:
|
255
|
+
|
256
|
+
```ts
|
257
|
+
import {
|
258
|
+
BaseClient,
|
259
|
+
Query,
|
260
|
+
Repository,
|
261
|
+
RestRespositoryFactory,
|
262
|
+
XataClientOptions,
|
263
|
+
XataRecord
|
264
|
+
} from 'https://esm.sh/@xata.io/client@<version>/dist/schema?target=deno';
|
265
|
+
```
|
package/dist/index.cjs
CHANGED
@@ -946,13 +946,13 @@ var __privateSet$5 = (obj, member, value, setter) => {
|
|
946
946
|
setter ? setter.call(obj, value) : member.set(obj, value);
|
947
947
|
return value;
|
948
948
|
};
|
949
|
-
var _query;
|
949
|
+
var _query, _page;
|
950
950
|
class Page {
|
951
951
|
constructor(query, meta, records = []) {
|
952
952
|
__privateAdd$6(this, _query, void 0);
|
953
953
|
__privateSet$5(this, _query, query);
|
954
954
|
this.meta = meta;
|
955
|
-
this.records = records;
|
955
|
+
this.records = new RecordArray(this, records);
|
956
956
|
}
|
957
957
|
async nextPage(size, offset) {
|
958
958
|
return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
|
@@ -972,12 +972,40 @@ class Page {
|
|
972
972
|
}
|
973
973
|
_query = new WeakMap();
|
974
974
|
const PAGINATION_MAX_SIZE = 200;
|
975
|
-
const PAGINATION_DEFAULT_SIZE =
|
975
|
+
const PAGINATION_DEFAULT_SIZE = 20;
|
976
976
|
const PAGINATION_MAX_OFFSET = 800;
|
977
977
|
const PAGINATION_DEFAULT_OFFSET = 0;
|
978
978
|
function isCursorPaginationOptions(options) {
|
979
979
|
return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
|
980
980
|
}
|
981
|
+
const _RecordArray = class extends Array {
|
982
|
+
constructor(page, overrideRecords) {
|
983
|
+
super(...overrideRecords ?? page.records);
|
984
|
+
__privateAdd$6(this, _page, void 0);
|
985
|
+
__privateSet$5(this, _page, page);
|
986
|
+
}
|
987
|
+
async nextPage(size, offset) {
|
988
|
+
const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
|
989
|
+
return new _RecordArray(newPage);
|
990
|
+
}
|
991
|
+
async previousPage(size, offset) {
|
992
|
+
const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
|
993
|
+
return new _RecordArray(newPage);
|
994
|
+
}
|
995
|
+
async firstPage(size, offset) {
|
996
|
+
const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
|
997
|
+
return new _RecordArray(newPage);
|
998
|
+
}
|
999
|
+
async lastPage(size, offset) {
|
1000
|
+
const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
|
1001
|
+
return new _RecordArray(newPage);
|
1002
|
+
}
|
1003
|
+
hasNextPage() {
|
1004
|
+
return __privateGet$6(this, _page).meta.page.more;
|
1005
|
+
}
|
1006
|
+
};
|
1007
|
+
let RecordArray = _RecordArray;
|
1008
|
+
_page = new WeakMap();
|
981
1009
|
|
982
1010
|
var __accessCheck$5 = (obj, member, msg) => {
|
983
1011
|
if (!member.has(obj))
|
@@ -1004,7 +1032,7 @@ const _Query = class {
|
|
1004
1032
|
__privateAdd$5(this, _repository, void 0);
|
1005
1033
|
__privateAdd$5(this, _data, { filter: {} });
|
1006
1034
|
this.meta = { page: { cursor: "start", more: true } };
|
1007
|
-
this.records = [];
|
1035
|
+
this.records = new RecordArray(this, []);
|
1008
1036
|
__privateSet$4(this, _table$1, table);
|
1009
1037
|
if (repository) {
|
1010
1038
|
__privateSet$4(this, _repository, repository);
|
@@ -1093,8 +1121,11 @@ const _Query = class {
|
|
1093
1121
|
}
|
1094
1122
|
}
|
1095
1123
|
async getMany(options = {}) {
|
1096
|
-
const
|
1097
|
-
|
1124
|
+
const page = await this.getPaginated(options);
|
1125
|
+
if (page.hasNextPage() && options.pagination?.size === void 0) {
|
1126
|
+
console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
|
1127
|
+
}
|
1128
|
+
return page.records;
|
1098
1129
|
}
|
1099
1130
|
async getAll(options = {}) {
|
1100
1131
|
const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
|
@@ -1142,7 +1173,9 @@ function isIdentifiable(x) {
|
|
1142
1173
|
return isObject(x) && isString(x?.id);
|
1143
1174
|
}
|
1144
1175
|
function isXataRecord(x) {
|
1145
|
-
|
1176
|
+
const record = x;
|
1177
|
+
const metadata = record?.getMetadata();
|
1178
|
+
return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
|
1146
1179
|
}
|
1147
1180
|
|
1148
1181
|
function isSortFilterString(value) {
|
@@ -1532,7 +1565,8 @@ const transformObjectLinks = (object) => {
|
|
1532
1565
|
};
|
1533
1566
|
const initObject = (db, schema, table, object) => {
|
1534
1567
|
const result = {};
|
1535
|
-
|
1568
|
+
const { xata, ...rest } = object ?? {};
|
1569
|
+
Object.assign(result, rest);
|
1536
1570
|
const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
|
1537
1571
|
if (!columns)
|
1538
1572
|
console.error(`Table ${table} not found in schema`);
|
@@ -1568,7 +1602,10 @@ const initObject = (db, schema, table, object) => {
|
|
1568
1602
|
result.delete = function() {
|
1569
1603
|
return db[table].delete(result["id"]);
|
1570
1604
|
};
|
1571
|
-
|
1605
|
+
result.getMetadata = function() {
|
1606
|
+
return xata;
|
1607
|
+
};
|
1608
|
+
for (const prop of ["read", "update", "delete", "getMetadata"]) {
|
1572
1609
|
Object.defineProperty(result, prop, { enumerable: false });
|
1573
1610
|
}
|
1574
1611
|
Object.freeze(result);
|
@@ -1979,6 +2016,7 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
|
|
1979
2016
|
exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
|
1980
2017
|
exports.Page = Page;
|
1981
2018
|
exports.Query = Query;
|
2019
|
+
exports.RecordArray = RecordArray;
|
1982
2020
|
exports.Repository = Repository;
|
1983
2021
|
exports.RestRepository = RestRepository;
|
1984
2022
|
exports.SchemaPlugin = SchemaPlugin;
|