@xata.io/client 0.10.2 → 0.13.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/dist/index.mjs CHANGED
@@ -7,8 +7,11 @@ function compact(arr) {
7
7
  function isObject(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
10
+ function isDefined(value) {
11
+ return value !== null && value !== void 0;
12
+ }
10
13
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
14
+ return isDefined(value) && typeof value === "string";
12
15
  }
13
16
  function toBase64(value) {
14
17
  try {
@@ -70,7 +73,12 @@ function getFetchImplementation(userFetch) {
70
73
  return fetchImpl;
71
74
  }
72
75
 
73
- class FetcherError extends Error {
76
+ class ErrorWithCause extends Error {
77
+ constructor(message, options) {
78
+ super(message, options);
79
+ }
80
+ }
81
+ class FetcherError extends ErrorWithCause {
74
82
  constructor(status, data) {
75
83
  super(getMessage(data));
76
84
  this.status = status;
@@ -934,13 +942,13 @@ var __privateSet$5 = (obj, member, value, setter) => {
934
942
  setter ? setter.call(obj, value) : member.set(obj, value);
935
943
  return value;
936
944
  };
937
- var _query;
945
+ var _query, _page;
938
946
  class Page {
939
947
  constructor(query, meta, records = []) {
940
948
  __privateAdd$6(this, _query, void 0);
941
949
  __privateSet$5(this, _query, query);
942
950
  this.meta = meta;
943
- this.records = records;
951
+ this.records = new RecordArray(this, records);
944
952
  }
945
953
  async nextPage(size, offset) {
946
954
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -960,9 +968,40 @@ class Page {
960
968
  }
961
969
  _query = new WeakMap();
962
970
  const PAGINATION_MAX_SIZE = 200;
963
- const PAGINATION_DEFAULT_SIZE = 200;
971
+ const PAGINATION_DEFAULT_SIZE = 20;
964
972
  const PAGINATION_MAX_OFFSET = 800;
965
973
  const PAGINATION_DEFAULT_OFFSET = 0;
974
+ function isCursorPaginationOptions(options) {
975
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
976
+ }
977
+ const _RecordArray = class extends Array {
978
+ constructor(page, overrideRecords) {
979
+ super(...overrideRecords ?? page.records);
980
+ __privateAdd$6(this, _page, void 0);
981
+ __privateSet$5(this, _page, page);
982
+ }
983
+ async nextPage(size, offset) {
984
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
985
+ return new _RecordArray(newPage);
986
+ }
987
+ async previousPage(size, offset) {
988
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
989
+ return new _RecordArray(newPage);
990
+ }
991
+ async firstPage(size, offset) {
992
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
993
+ return new _RecordArray(newPage);
994
+ }
995
+ async lastPage(size, offset) {
996
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
997
+ return new _RecordArray(newPage);
998
+ }
999
+ hasNextPage() {
1000
+ return __privateGet$6(this, _page).meta.page.more;
1001
+ }
1002
+ };
1003
+ let RecordArray = _RecordArray;
1004
+ _page = new WeakMap();
966
1005
 
967
1006
  var __accessCheck$5 = (obj, member, msg) => {
968
1007
  if (!member.has(obj))
@@ -984,18 +1023,19 @@ var __privateSet$4 = (obj, member, value, setter) => {
984
1023
  };
985
1024
  var _table$1, _repository, _data;
986
1025
  const _Query = class {
987
- constructor(repository, table, data, parent) {
1026
+ constructor(repository, table, data, rawParent) {
988
1027
  __privateAdd$5(this, _table$1, void 0);
989
1028
  __privateAdd$5(this, _repository, void 0);
990
1029
  __privateAdd$5(this, _data, { filter: {} });
991
1030
  this.meta = { page: { cursor: "start", more: true } };
992
- this.records = [];
1031
+ this.records = new RecordArray(this, []);
993
1032
  __privateSet$4(this, _table$1, table);
994
1033
  if (repository) {
995
1034
  __privateSet$4(this, _repository, repository);
996
1035
  } else {
997
1036
  __privateSet$4(this, _repository, this);
998
1037
  }
1038
+ const parent = cleanParent(data, rawParent);
999
1039
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1000
1040
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1001
1041
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1067,18 +1107,21 @@ const _Query = class {
1067
1107
  }
1068
1108
  async *getIterator(options = {}) {
1069
1109
  const { batchSize = 1 } = options;
1070
- let offset = 0;
1071
- let end = false;
1072
- while (!end) {
1073
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: batchSize, offset } });
1074
- yield records;
1075
- offset += batchSize;
1076
- end = !meta.page.more;
1110
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1111
+ let more = page.hasNextPage();
1112
+ yield page.records;
1113
+ while (more) {
1114
+ page = await page.nextPage();
1115
+ more = page.hasNextPage();
1116
+ yield page.records;
1077
1117
  }
1078
1118
  }
1079
1119
  async getMany(options = {}) {
1080
- const { records } = await this.getPaginated(options);
1081
- return records;
1120
+ const page = await this.getPaginated(options);
1121
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1122
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1123
+ }
1124
+ return page.records;
1082
1125
  }
1083
1126
  async getAll(options = {}) {
1084
1127
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1115,12 +1158,20 @@ let Query = _Query;
1115
1158
  _table$1 = new WeakMap();
1116
1159
  _repository = new WeakMap();
1117
1160
  _data = new WeakMap();
1161
+ function cleanParent(data, parent) {
1162
+ if (isCursorPaginationOptions(data.pagination)) {
1163
+ return { ...parent, sorting: void 0, filter: void 0 };
1164
+ }
1165
+ return parent;
1166
+ }
1118
1167
 
1119
1168
  function isIdentifiable(x) {
1120
1169
  return isObject(x) && isString(x?.id);
1121
1170
  }
1122
1171
  function isXataRecord(x) {
1123
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1172
+ const record = x;
1173
+ const metadata = record?.getMetadata();
1174
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1124
1175
  }
1125
1176
 
1126
1177
  function isSortFilterString(value) {
@@ -1197,6 +1248,8 @@ class RestRepository extends Query {
1197
1248
  }
1198
1249
  async create(a, b) {
1199
1250
  if (Array.isArray(a)) {
1251
+ if (a.length === 0)
1252
+ return [];
1200
1253
  const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1201
1254
  await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1202
1255
  return records;
@@ -1222,27 +1275,36 @@ class RestRepository extends Query {
1222
1275
  }
1223
1276
  throw new Error("Invalid arguments for create method");
1224
1277
  }
1225
- async read(recordId) {
1226
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1227
- if (cacheRecord)
1228
- return cacheRecord;
1229
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1230
- try {
1231
- const response = await getRecord({
1232
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1233
- ...fetchProps
1234
- });
1235
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1236
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1237
- } catch (e) {
1238
- if (isObject(e) && e.status === 404) {
1239
- return null;
1278
+ async read(a) {
1279
+ if (Array.isArray(a)) {
1280
+ if (a.length === 0)
1281
+ return [];
1282
+ return this.getAll({ filter: { id: { $any: a } } });
1283
+ }
1284
+ if (isString(a)) {
1285
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, a);
1286
+ if (cacheRecord)
1287
+ return cacheRecord;
1288
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1289
+ try {
1290
+ const response = await getRecord({
1291
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: a },
1292
+ ...fetchProps
1293
+ });
1294
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1295
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1296
+ } catch (e) {
1297
+ if (isObject(e) && e.status === 404) {
1298
+ return null;
1299
+ }
1300
+ throw e;
1240
1301
  }
1241
- throw e;
1242
1302
  }
1243
1303
  }
1244
1304
  async update(a, b) {
1245
1305
  if (Array.isArray(a)) {
1306
+ if (a.length === 0)
1307
+ return [];
1246
1308
  if (a.length > 100) {
1247
1309
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1248
1310
  }
@@ -1264,6 +1326,8 @@ class RestRepository extends Query {
1264
1326
  }
1265
1327
  async createOrUpdate(a, b) {
1266
1328
  if (Array.isArray(a)) {
1329
+ if (a.length === 0)
1330
+ return [];
1267
1331
  if (a.length > 100) {
1268
1332
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1269
1333
  }
@@ -1285,6 +1349,8 @@ class RestRepository extends Query {
1285
1349
  }
1286
1350
  async delete(a) {
1287
1351
  if (Array.isArray(a)) {
1352
+ if (a.length === 0)
1353
+ return;
1288
1354
  if (a.length > 100) {
1289
1355
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1290
1356
  }
@@ -1310,6 +1376,7 @@ class RestRepository extends Query {
1310
1376
  body: {
1311
1377
  query,
1312
1378
  fuzziness: options.fuzziness,
1379
+ highlight: options.highlight,
1313
1380
  filter: options.filter
1314
1381
  },
1315
1382
  ...fetchProps
@@ -1494,7 +1561,8 @@ const transformObjectLinks = (object) => {
1494
1561
  };
1495
1562
  const initObject = (db, schema, table, object) => {
1496
1563
  const result = {};
1497
- Object.assign(result, object);
1564
+ const { xata, ...rest } = object ?? {};
1565
+ Object.assign(result, rest);
1498
1566
  const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1499
1567
  if (!columns)
1500
1568
  console.error(`Table ${table} not found in schema`);
@@ -1502,10 +1570,10 @@ const initObject = (db, schema, table, object) => {
1502
1570
  const value = result[column.name];
1503
1571
  switch (column.type) {
1504
1572
  case "datetime": {
1505
- const date = new Date(value);
1506
- if (isNaN(date.getTime())) {
1573
+ const date = value !== void 0 ? new Date(value) : void 0;
1574
+ if (date && isNaN(date.getTime())) {
1507
1575
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1508
- } else {
1576
+ } else if (date) {
1509
1577
  result[column.name] = date;
1510
1578
  }
1511
1579
  break;
@@ -1530,7 +1598,10 @@ const initObject = (db, schema, table, object) => {
1530
1598
  result.delete = function() {
1531
1599
  return db[table].delete(result["id"]);
1532
1600
  };
1533
- for (const prop of ["read", "update", "delete"]) {
1601
+ result.getMetadata = function() {
1602
+ return xata;
1603
+ };
1604
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1534
1605
  Object.defineProperty(result, prop, { enumerable: false });
1535
1606
  }
1536
1607
  Object.freeze(result);
@@ -1712,10 +1783,10 @@ _schema = new WeakMap();
1712
1783
  _search = new WeakSet();
1713
1784
  search_fn = async function(query, options, getFetchProps) {
1714
1785
  const fetchProps = await getFetchProps();
1715
- const { tables, fuzziness } = options ?? {};
1786
+ const { tables, fuzziness, highlight } = options ?? {};
1716
1787
  const { records } = await searchBranch({
1717
1788
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1718
- body: { tables, query, fuzziness },
1789
+ body: { tables, query, fuzziness, highlight },
1719
1790
  ...fetchProps
1720
1791
  });
1721
1792
  return records;
@@ -1933,5 +2004,5 @@ class XataError extends Error {
1933
2004
  }
1934
2005
  }
1935
2006
 
1936
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2007
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
1937
2008
  //# sourceMappingURL=index.mjs.map