@xata.io/client 0.1.5 → 0.4.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 +24 -0
- package/LICENSE +201 -0
- package/dist/api/client.d.ts +95 -0
- package/dist/api/client.js +235 -0
- package/dist/api/components.d.ts +1440 -0
- package/dist/api/components.js +1001 -0
- package/dist/api/fetcher.d.ts +25 -0
- package/dist/api/fetcher.js +78 -0
- package/dist/api/index.d.ts +7 -0
- package/dist/api/index.js +21 -0
- package/dist/api/parameters.d.ts +16 -0
- package/dist/api/parameters.js +2 -0
- package/dist/api/providers.d.ts +8 -0
- package/dist/api/providers.js +29 -0
- package/dist/api/responses.d.ts +44 -0
- package/dist/api/responses.js +2 -0
- package/dist/api/schemas.d.ts +311 -0
- package/dist/api/schemas.js +2 -0
- package/dist/index.d.ts +2 -126
- package/dist/index.js +16 -324
- package/dist/schema/filters.d.ts +20 -0
- package/dist/schema/filters.js +24 -0
- package/dist/schema/index.d.ts +6 -0
- package/dist/schema/index.js +26 -0
- package/dist/schema/operators.d.ts +72 -0
- package/dist/schema/operators.js +91 -0
- package/dist/schema/pagination.d.ts +83 -0
- package/dist/schema/pagination.js +94 -0
- package/dist/schema/query.d.ts +128 -0
- package/dist/schema/query.js +254 -0
- package/dist/schema/record.d.ts +41 -0
- package/dist/schema/record.js +2 -0
- package/dist/schema/repository.d.ts +109 -0
- package/dist/schema/repository.js +280 -0
- package/dist/schema/selection.d.ts +14 -0
- package/dist/schema/selection.js +2 -0
- package/dist/util/lang.d.ts +2 -0
- package/dist/util/lang.js +10 -0
- package/dist/util/types.d.ts +3 -0
- package/dist/util/types.js +2 -0
- package/package.json +4 -3
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -182
- package/src/index.test.ts +0 -222
- package/src/index.ts +0 -468
@@ -0,0 +1,280 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9
|
+
});
|
10
|
+
};
|
11
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
12
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
13
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
14
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
15
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
16
|
+
};
|
17
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
18
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
19
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
20
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
21
|
+
};
|
22
|
+
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
23
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
24
|
+
var m = o[Symbol.asyncIterator], i;
|
25
|
+
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
26
|
+
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
27
|
+
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
28
|
+
};
|
29
|
+
var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _BaseClient_links, _BaseClient_branch;
|
30
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
31
|
+
exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
|
32
|
+
const api_1 = require("../api");
|
33
|
+
const filters_1 = require("./filters");
|
34
|
+
const pagination_1 = require("./pagination");
|
35
|
+
const query_1 = require("./query");
|
36
|
+
/**
|
37
|
+
* Common interface for performing operations on a table.
|
38
|
+
*/
|
39
|
+
class Repository extends query_1.Query {
|
40
|
+
}
|
41
|
+
exports.Repository = Repository;
|
42
|
+
class RestRepository extends Repository {
|
43
|
+
constructor(client, table) {
|
44
|
+
super(null, table, {});
|
45
|
+
_RestRepository_instances.add(this);
|
46
|
+
_RestRepository_client.set(this, void 0);
|
47
|
+
_RestRepository_fetch.set(this, void 0);
|
48
|
+
_RestRepository_table.set(this, void 0);
|
49
|
+
__classPrivateFieldSet(this, _RestRepository_client, client, "f");
|
50
|
+
__classPrivateFieldSet(this, _RestRepository_table, table, "f");
|
51
|
+
// TODO: Remove when integrating with API client
|
52
|
+
const fetchImpl = typeof fetch !== 'undefined' ? fetch : __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch;
|
53
|
+
if (!fetchImpl) {
|
54
|
+
throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
|
55
|
+
}
|
56
|
+
__classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
|
57
|
+
}
|
58
|
+
create(object) {
|
59
|
+
return __awaiter(this, void 0, void 0, function* () {
|
60
|
+
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
|
61
|
+
const record = transformObjectLinks(object);
|
62
|
+
const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
|
63
|
+
workspace: '{workspaceId}',
|
64
|
+
dbBranchName: '{dbBranch}',
|
65
|
+
tableName: __classPrivateFieldGet(this, _RestRepository_table, "f")
|
66
|
+
}, body: record }, fetchProps));
|
67
|
+
const finalObject = yield this.read(response.id);
|
68
|
+
if (!finalObject) {
|
69
|
+
throw new Error('The server failed to save the record');
|
70
|
+
}
|
71
|
+
return finalObject;
|
72
|
+
});
|
73
|
+
}
|
74
|
+
createMany(objects) {
|
75
|
+
return __awaiter(this, void 0, void 0, function* () {
|
76
|
+
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
|
77
|
+
const records = objects.map((object) => transformObjectLinks(object));
|
78
|
+
const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
|
79
|
+
const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
|
80
|
+
if (finalObjects.length !== objects.length) {
|
81
|
+
throw new Error('The server failed to save some records');
|
82
|
+
}
|
83
|
+
return finalObjects;
|
84
|
+
});
|
85
|
+
}
|
86
|
+
read(recordId) {
|
87
|
+
return __awaiter(this, void 0, void 0, function* () {
|
88
|
+
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
|
89
|
+
const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
|
90
|
+
return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
|
91
|
+
});
|
92
|
+
}
|
93
|
+
update(recordId, object) {
|
94
|
+
return __awaiter(this, void 0, void 0, function* () {
|
95
|
+
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
|
96
|
+
const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
|
97
|
+
const item = yield this.read(response.id);
|
98
|
+
if (!item)
|
99
|
+
throw new Error('The server failed to save the record');
|
100
|
+
return item;
|
101
|
+
});
|
102
|
+
}
|
103
|
+
insert(recordId, object) {
|
104
|
+
return __awaiter(this, void 0, void 0, function* () {
|
105
|
+
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
|
106
|
+
const record = transformObjectLinks(object);
|
107
|
+
const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
|
108
|
+
workspace: '{workspaceId}',
|
109
|
+
dbBranchName: '{dbBranch}',
|
110
|
+
tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
|
111
|
+
recordId
|
112
|
+
}, body: record }, fetchProps));
|
113
|
+
const finalObject = yield this.read(response.id);
|
114
|
+
if (!finalObject) {
|
115
|
+
throw new Error('The server failed to save the record');
|
116
|
+
}
|
117
|
+
return finalObject;
|
118
|
+
});
|
119
|
+
}
|
120
|
+
updateOrInsert(recordId, object) {
|
121
|
+
return __awaiter(this, void 0, void 0, function* () {
|
122
|
+
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
|
123
|
+
const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
|
124
|
+
const item = yield this.read(response.id);
|
125
|
+
if (!item)
|
126
|
+
throw new Error('The server failed to save the record');
|
127
|
+
return item;
|
128
|
+
});
|
129
|
+
}
|
130
|
+
delete(recordId) {
|
131
|
+
return __awaiter(this, void 0, void 0, function* () {
|
132
|
+
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
|
133
|
+
yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
|
134
|
+
});
|
135
|
+
}
|
136
|
+
query(query, options = {}) {
|
137
|
+
var _a, _b, _c;
|
138
|
+
return __awaiter(this, void 0, void 0, function* () {
|
139
|
+
const data = query.getQueryOptions();
|
140
|
+
const body = {
|
141
|
+
filter: Object.values(data.filter).some(Boolean) ? data.filter : undefined,
|
142
|
+
sort: (_a = (0, filters_1.buildSortFilter)(options === null || options === void 0 ? void 0 : options.sort)) !== null && _a !== void 0 ? _a : data.sort,
|
143
|
+
page: (_b = options === null || options === void 0 ? void 0 : options.page) !== null && _b !== void 0 ? _b : data.page,
|
144
|
+
columns: (_c = options === null || options === void 0 ? void 0 : options.columns) !== null && _c !== void 0 ? _c : data.columns
|
145
|
+
};
|
146
|
+
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
|
147
|
+
const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps));
|
148
|
+
const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
|
149
|
+
// TODO: We should properly type this any
|
150
|
+
return new pagination_1.Page(query, meta, records);
|
151
|
+
});
|
152
|
+
}
|
153
|
+
}
|
154
|
+
exports.RestRepository = RestRepository;
|
155
|
+
_RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
|
156
|
+
return __awaiter(this, void 0, void 0, function* () {
|
157
|
+
const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
|
158
|
+
return {
|
159
|
+
fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
|
160
|
+
apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
|
161
|
+
apiUrl: '',
|
162
|
+
// Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
|
163
|
+
workspacesApiUrl: (path, params) => {
|
164
|
+
var _a, _b;
|
165
|
+
const baseUrl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.databaseURL) !== null && _a !== void 0 ? _a : '';
|
166
|
+
const hasBranch = (_b = params.dbBranchName) !== null && _b !== void 0 ? _b : params.branch;
|
167
|
+
const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branch}` : '');
|
168
|
+
return baseUrl + newPath;
|
169
|
+
}
|
170
|
+
};
|
171
|
+
});
|
172
|
+
};
|
173
|
+
class RestRespositoryFactory {
|
174
|
+
createRepository(client, table) {
|
175
|
+
return new RestRepository(client, table);
|
176
|
+
}
|
177
|
+
}
|
178
|
+
exports.RestRespositoryFactory = RestRespositoryFactory;
|
179
|
+
class BaseClient {
|
180
|
+
constructor(options, links = {}) {
|
181
|
+
_BaseClient_links.set(this, void 0);
|
182
|
+
_BaseClient_branch.set(this, void 0);
|
183
|
+
if (!options.databaseURL || !options.apiKey || !options.branch) {
|
184
|
+
throw new Error('Options databaseURL, apiKey and branch are required');
|
185
|
+
}
|
186
|
+
this.options = options;
|
187
|
+
__classPrivateFieldSet(this, _BaseClient_links, links, "f");
|
188
|
+
const factory = options.repositoryFactory || new RestRespositoryFactory();
|
189
|
+
this.db = new Proxy({}, {
|
190
|
+
get: (_target, prop) => {
|
191
|
+
if (typeof prop !== 'string')
|
192
|
+
throw new Error('Invalid table name');
|
193
|
+
return factory.createRepository(this, prop);
|
194
|
+
}
|
195
|
+
});
|
196
|
+
}
|
197
|
+
initObject(table, object) {
|
198
|
+
const o = {};
|
199
|
+
Object.assign(o, object);
|
200
|
+
const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
|
201
|
+
for (const link of tableLinks) {
|
202
|
+
const [field, linkTable] = link;
|
203
|
+
const value = o[field];
|
204
|
+
if (value && typeof value === 'object') {
|
205
|
+
const { id } = value;
|
206
|
+
if (Object.keys(value).find((col) => col === 'id')) {
|
207
|
+
o[field] = this.initObject(linkTable, value);
|
208
|
+
}
|
209
|
+
else if (id) {
|
210
|
+
o[field] = {
|
211
|
+
id,
|
212
|
+
get: () => {
|
213
|
+
this.db[linkTable].read(id);
|
214
|
+
}
|
215
|
+
};
|
216
|
+
}
|
217
|
+
}
|
218
|
+
}
|
219
|
+
const db = this.db;
|
220
|
+
o.read = function () {
|
221
|
+
return db[table].read(o['id']);
|
222
|
+
};
|
223
|
+
o.update = function (data) {
|
224
|
+
return db[table].update(o['id'], data);
|
225
|
+
};
|
226
|
+
o.delete = function () {
|
227
|
+
return db[table].delete(o['id']);
|
228
|
+
};
|
229
|
+
for (const prop of ['read', 'update', 'delete']) {
|
230
|
+
Object.defineProperty(o, prop, { enumerable: false });
|
231
|
+
}
|
232
|
+
// TODO: links and rev links
|
233
|
+
Object.freeze(o);
|
234
|
+
return o;
|
235
|
+
}
|
236
|
+
getBranch() {
|
237
|
+
var e_1, _a;
|
238
|
+
return __awaiter(this, void 0, void 0, function* () {
|
239
|
+
if (__classPrivateFieldGet(this, _BaseClient_branch, "f"))
|
240
|
+
return __classPrivateFieldGet(this, _BaseClient_branch, "f");
|
241
|
+
const { branch: param } = this.options;
|
242
|
+
const strategies = Array.isArray(param) ? [...param] : [param];
|
243
|
+
const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
|
244
|
+
return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy;
|
245
|
+
});
|
246
|
+
try {
|
247
|
+
for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
|
248
|
+
const strategy = strategies_1_1.value;
|
249
|
+
const branch = yield evaluateBranch(strategy);
|
250
|
+
if (branch) {
|
251
|
+
__classPrivateFieldSet(this, _BaseClient_branch, branch, "f");
|
252
|
+
return branch;
|
253
|
+
}
|
254
|
+
}
|
255
|
+
}
|
256
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
257
|
+
finally {
|
258
|
+
try {
|
259
|
+
if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
|
260
|
+
}
|
261
|
+
finally { if (e_1) throw e_1.error; }
|
262
|
+
}
|
263
|
+
throw new Error('Unable to resolve branch value');
|
264
|
+
});
|
265
|
+
}
|
266
|
+
}
|
267
|
+
exports.BaseClient = BaseClient;
|
268
|
+
_BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
|
269
|
+
const isBranchStrategyBuilder = (strategy) => {
|
270
|
+
return typeof strategy === 'function';
|
271
|
+
};
|
272
|
+
// TODO: We can find a better implementation for links
|
273
|
+
const transformObjectLinks = (object) => {
|
274
|
+
return Object.entries(object).reduce((acc, [key, value]) => {
|
275
|
+
if (value && typeof value === 'object' && typeof value.id === 'string') {
|
276
|
+
return Object.assign(Object.assign({}, acc), { [key]: value.id });
|
277
|
+
}
|
278
|
+
return Object.assign(Object.assign({}, acc), { [key]: value });
|
279
|
+
}, {});
|
280
|
+
};
|
@@ -0,0 +1,14 @@
|
|
1
|
+
import { XataRecord } from '..';
|
2
|
+
import { StringKeys, UnionToIntersection, Values } from '../util/types';
|
3
|
+
import { Query } from './query';
|
4
|
+
import { Identifiable } from './record';
|
5
|
+
declare type Queries<T> = {
|
6
|
+
[key in keyof T as T[key] extends Query<any> ? key : never]: T[key];
|
7
|
+
};
|
8
|
+
declare type InternalProperties = keyof XataRecord;
|
9
|
+
export declare type Selectable<T extends XataRecord> = Omit<T, InternalProperties> & Identifiable;
|
10
|
+
export declare type SelectableColumn<O> = '*' | (O extends Array<unknown> ? never : O extends Record<string, any> ? '*' | Values<{
|
11
|
+
[K in StringKeys<O>]: O[K] extends Record<string, any> ? `${K}.${SelectableColumn<O[K]>}` : K;
|
12
|
+
}> : '');
|
13
|
+
export declare type Select<T, K extends SelectableColumn<T>> = UnionToIntersection<K extends keyof T ? Pick<T, K> : T> & Queries<T> & XataRecord;
|
14
|
+
export {};
|
@@ -0,0 +1,10 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.compact = void 0;
|
4
|
+
function notEmpty(value) {
|
5
|
+
return value !== null && value !== undefined;
|
6
|
+
}
|
7
|
+
function compact(arr) {
|
8
|
+
return arr.filter(notEmpty);
|
9
|
+
}
|
10
|
+
exports.compact = compact;
|
package/package.json
CHANGED
@@ -1,12 +1,12 @@
|
|
1
1
|
{
|
2
2
|
"name": "@xata.io/client",
|
3
|
-
"version": "0.
|
3
|
+
"version": "0.4.0",
|
4
4
|
"description": "Xata.io SDK for TypeScript and JavaScript",
|
5
5
|
"main": "./dist/index.js",
|
6
6
|
"types": "./dist/index.d.ts",
|
7
7
|
"scripts": {
|
8
8
|
"test": "echo \"Error: no test specified\" && exit 1",
|
9
|
-
"build": "tsc",
|
9
|
+
"build": "tsc -p tsconfig.build.json",
|
10
10
|
"prepack": "npm run build"
|
11
11
|
},
|
12
12
|
"repository": {
|
@@ -19,5 +19,6 @@
|
|
19
19
|
"bugs": {
|
20
20
|
"url": "https://github.com/xataio/client-ts/issues"
|
21
21
|
},
|
22
|
-
"homepage": "https://github.com/xataio/client-ts
|
22
|
+
"homepage": "https://github.com/xataio/client-ts/blob/main/client/README.md",
|
23
|
+
"gitHead": "d29cf06c96a17f69ca80c57b430059abc90fcad8"
|
23
24
|
}
|
package/dist/index.test.d.ts
DELETED
@@ -1 +0,0 @@
|
|
1
|
-
export {};
|
package/dist/index.test.js
DELETED
@@ -1,182 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9
|
-
});
|
10
|
-
};
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
12
|
-
const _1 = require("./");
|
13
|
-
const fetch = jest.fn();
|
14
|
-
const client = new _1.BaseClient({
|
15
|
-
fetch,
|
16
|
-
apiKey: '1234',
|
17
|
-
databaseURL: 'https://my-workspace-5df34do.staging.xatabase.co/db/xata:main'
|
18
|
-
}, {});
|
19
|
-
const users = new _1.RestRepository(client, 'users');
|
20
|
-
describe('request', () => {
|
21
|
-
test('builds the right arguments for a GET request', () => __awaiter(void 0, void 0, void 0, function* () {
|
22
|
-
fetch.mockReset().mockImplementation(() => {
|
23
|
-
return {
|
24
|
-
ok: true,
|
25
|
-
json: () => __awaiter(void 0, void 0, void 0, function* () { return ({}); })
|
26
|
-
};
|
27
|
-
});
|
28
|
-
users.request('GET', '/foo');
|
29
|
-
expect(fetch).toHaveBeenCalledTimes(1);
|
30
|
-
expect(fetch.mock.calls[0]).toMatchInlineSnapshot(`
|
31
|
-
Array [
|
32
|
-
"https://my-workspace-5df34do.staging.xatabase.co/db/xata:main/foo",
|
33
|
-
Object {
|
34
|
-
"body": undefined,
|
35
|
-
"headers": Object {
|
36
|
-
"Accept": "*/*",
|
37
|
-
"Authorization": "Bearer 1234",
|
38
|
-
"Content-Type": "application/json",
|
39
|
-
},
|
40
|
-
"method": "GET",
|
41
|
-
},
|
42
|
-
]
|
43
|
-
`);
|
44
|
-
}));
|
45
|
-
test('builds the right arguments for a POST request', () => __awaiter(void 0, void 0, void 0, function* () {
|
46
|
-
fetch.mockReset().mockImplementation(() => {
|
47
|
-
return {
|
48
|
-
ok: true,
|
49
|
-
json: () => __awaiter(void 0, void 0, void 0, function* () { return ({}); })
|
50
|
-
};
|
51
|
-
});
|
52
|
-
users.request('POST', '/foo', { a: 1 });
|
53
|
-
expect(fetch).toHaveBeenCalledTimes(1);
|
54
|
-
expect(fetch.mock.calls[0]).toMatchInlineSnapshot(`
|
55
|
-
Array [
|
56
|
-
"https://my-workspace-5df34do.staging.xatabase.co/db/xata:main/foo",
|
57
|
-
Object {
|
58
|
-
"body": "{\\"a\\":1}",
|
59
|
-
"headers": Object {
|
60
|
-
"Accept": "*/*",
|
61
|
-
"Authorization": "Bearer 1234",
|
62
|
-
"Content-Type": "application/json",
|
63
|
-
},
|
64
|
-
"method": "POST",
|
65
|
-
},
|
66
|
-
]
|
67
|
-
`);
|
68
|
-
}));
|
69
|
-
test('throws if the response is not ok', () => __awaiter(void 0, void 0, void 0, function* () {
|
70
|
-
fetch.mockImplementation(() => {
|
71
|
-
return {
|
72
|
-
ok: false,
|
73
|
-
status: 404,
|
74
|
-
statusText: 'Not Found'
|
75
|
-
};
|
76
|
-
});
|
77
|
-
expect(users.request('GET', '/foo')).rejects.toThrow(new _1.XataError('Not Found', 404));
|
78
|
-
}));
|
79
|
-
test('throws with the error from the server if the response is not ok', () => __awaiter(void 0, void 0, void 0, function* () {
|
80
|
-
fetch.mockImplementation(() => {
|
81
|
-
return {
|
82
|
-
ok: false,
|
83
|
-
status: 404,
|
84
|
-
statusText: 'Not Found',
|
85
|
-
json: () => __awaiter(void 0, void 0, void 0, function* () { return ({ message: 'Resource not found' }); })
|
86
|
-
};
|
87
|
-
});
|
88
|
-
expect(users.request('GET', '/foo')).rejects.toThrow(new _1.XataError('Resource not found', 404));
|
89
|
-
}));
|
90
|
-
test('returns the json body if the response is ok', () => __awaiter(void 0, void 0, void 0, function* () {
|
91
|
-
const json = { a: 1 };
|
92
|
-
fetch.mockImplementation(() => {
|
93
|
-
return {
|
94
|
-
ok: true,
|
95
|
-
json: () => __awaiter(void 0, void 0, void 0, function* () { return json; })
|
96
|
-
};
|
97
|
-
});
|
98
|
-
const result = yield users.request('GET', '/foo');
|
99
|
-
expect(result).toEqual(json);
|
100
|
-
}));
|
101
|
-
});
|
102
|
-
function expectRequest(expectedRequest, callback, response) {
|
103
|
-
return __awaiter(this, void 0, void 0, function* () {
|
104
|
-
const request = jest.fn(() => __awaiter(this, void 0, void 0, function* () { return response; }));
|
105
|
-
users.request = request;
|
106
|
-
yield callback();
|
107
|
-
const { calls } = request.mock;
|
108
|
-
expect(calls.length).toBe(1);
|
109
|
-
const [method, path, body] = calls[0];
|
110
|
-
expect(method).toBe(expectedRequest.method);
|
111
|
-
expect(path).toBe(expectedRequest.path);
|
112
|
-
expect(JSON.stringify(body)).toBe(JSON.stringify(expectedRequest.body));
|
113
|
-
});
|
114
|
-
}
|
115
|
-
describe('query', () => {
|
116
|
-
describe('getMany', () => {
|
117
|
-
test('simple query', () => __awaiter(void 0, void 0, void 0, function* () {
|
118
|
-
const expected = { method: 'POST', path: '/tables/users/query', body: {} };
|
119
|
-
expectRequest(expected, () => users.getMany(), { records: [] });
|
120
|
-
}));
|
121
|
-
test('query with one filter', () => __awaiter(void 0, void 0, void 0, function* () {
|
122
|
-
const expected = { method: 'POST', path: '/tables/users/query', body: { filter: { $all: [{ name: 'foo' }] } } };
|
123
|
-
expectRequest(expected, () => users.filter('name', 'foo').getMany(), { records: [] });
|
124
|
-
}));
|
125
|
-
});
|
126
|
-
describe('getOne', () => {
|
127
|
-
test('returns a single object', () => __awaiter(void 0, void 0, void 0, function* () {
|
128
|
-
const result = { records: [{ id: '1234' }] };
|
129
|
-
const expected = { method: 'POST', path: '/tables/users/query', body: {} };
|
130
|
-
expectRequest(expected, () => __awaiter(void 0, void 0, void 0, function* () {
|
131
|
-
const first = yield users.select().getOne();
|
132
|
-
expect(first === null || first === void 0 ? void 0 : first.id).toBe(result.records[0].id);
|
133
|
-
}), result);
|
134
|
-
}));
|
135
|
-
test('returns null if no objects are returned', () => __awaiter(void 0, void 0, void 0, function* () {
|
136
|
-
const result = { records: [] };
|
137
|
-
const expected = { method: 'POST', path: '/tables/users/query', body: {} };
|
138
|
-
expectRequest(expected, () => __awaiter(void 0, void 0, void 0, function* () {
|
139
|
-
const first = yield users.getOne();
|
140
|
-
expect(first).toBeNull();
|
141
|
-
}), result);
|
142
|
-
}));
|
143
|
-
});
|
144
|
-
});
|
145
|
-
describe('read', () => {
|
146
|
-
test('reads an object by id successfully', () => __awaiter(void 0, void 0, void 0, function* () {
|
147
|
-
const id = 'rec_1234';
|
148
|
-
const expected = { method: 'GET', path: `/tables/users/data/${id}`, body: undefined };
|
149
|
-
expectRequest(expected, () => users.read(id));
|
150
|
-
}));
|
151
|
-
});
|
152
|
-
describe('Repository.update', () => {
|
153
|
-
test('updates and object successfully', () => __awaiter(void 0, void 0, void 0, function* () {
|
154
|
-
const object = { id: 'rec_1234', xata: { version: 1 }, name: 'Ada' };
|
155
|
-
const expected = { method: 'PUT', path: `/tables/users/data/${object.id}`, body: object };
|
156
|
-
expectRequest(expected, () => __awaiter(void 0, void 0, void 0, function* () {
|
157
|
-
const result = yield users.update(object.id, object);
|
158
|
-
expect(result.id).toBe(object.id);
|
159
|
-
}), { id: object.id });
|
160
|
-
}));
|
161
|
-
});
|
162
|
-
describe('Repository.delete', () => {
|
163
|
-
test('deletes a record by id successfully', () => __awaiter(void 0, void 0, void 0, function* () {
|
164
|
-
const id = 'rec_1234';
|
165
|
-
const expected = { method: 'DELETE', path: `/tables/users/data/${id}`, body: undefined };
|
166
|
-
expectRequest(expected, () => __awaiter(void 0, void 0, void 0, function* () {
|
167
|
-
const result = yield users.delete(id);
|
168
|
-
expect(result).toBe(undefined);
|
169
|
-
}));
|
170
|
-
}));
|
171
|
-
});
|
172
|
-
describe('create', () => {
|
173
|
-
test('successful', () => __awaiter(void 0, void 0, void 0, function* () {
|
174
|
-
const created = { id: 'rec_1234', _version: 0 };
|
175
|
-
const object = { name: 'Ada' };
|
176
|
-
const expected = { method: 'POST', path: '/tables/users/data', body: object };
|
177
|
-
expectRequest(expected, () => __awaiter(void 0, void 0, void 0, function* () {
|
178
|
-
const result = yield users.create(object);
|
179
|
-
expect(result.id).toBe(created.id);
|
180
|
-
}), created);
|
181
|
-
}));
|
182
|
-
});
|