@rushdb/javascript-sdk 0.9.4 → 0.9.5

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.
Files changed (100) hide show
  1. package/dist/index.cjs +1 -0
  2. package/dist/index.mjs +1 -0
  3. package/dist/index.node.d.ts +137 -0
  4. package/dist/index.worker.d.ts +137 -0
  5. package/{types → dist}/sdk/model.d.ts +4 -4
  6. package/{types → dist}/sdk/record.d.ts +3 -3
  7. package/{types → dist}/sdk/sdk.d.ts +24 -24
  8. package/{types → dist}/sdk/transaction.d.ts +2 -2
  9. package/{types → dist}/types/query.d.ts +1 -2
  10. package/package.json +10 -34
  11. package/CHANGELOG.md +0 -180
  12. package/cjs/api/api.js +0 -328
  13. package/cjs/api/constants.js +0 -7
  14. package/cjs/api/create-api.js +0 -323
  15. package/cjs/api/index.js +0 -8
  16. package/cjs/api/rest-api-proxy.js +0 -22
  17. package/cjs/api/types.js +0 -2
  18. package/cjs/api/utils.js +0 -155
  19. package/cjs/common/constants.js +0 -10
  20. package/cjs/common/utils.js +0 -46
  21. package/cjs/index.cjs.node.js +0 -24
  22. package/cjs/index.cjs.worker.js +0 -24
  23. package/cjs/network/FetchHttpClient.js +0 -138
  24. package/cjs/network/HttpClient.js +0 -59
  25. package/cjs/network/NodeHttpClient.js +0 -103
  26. package/cjs/network/index.js +0 -28
  27. package/cjs/network/types.js +0 -2
  28. package/cjs/package.json +0 -4
  29. package/cjs/sdk/constants.js +0 -13
  30. package/cjs/sdk/errors.js +0 -27
  31. package/cjs/sdk/index.js +0 -23
  32. package/cjs/sdk/model.js +0 -147
  33. package/cjs/sdk/record.js +0 -122
  34. package/cjs/sdk/sdk.js +0 -46
  35. package/cjs/sdk/transaction.js +0 -17
  36. package/cjs/sdk/types.js +0 -2
  37. package/cjs/sdk/utils.js +0 -103
  38. package/cjs/types/expressions.js +0 -2
  39. package/cjs/types/index.js +0 -21
  40. package/cjs/types/query.js +0 -2
  41. package/cjs/types/schema.js +0 -2
  42. package/cjs/types/utils.js +0 -2
  43. package/cjs/types/value.js +0 -2
  44. package/esm/api/api.js +0 -324
  45. package/esm/api/constants.js +0 -4
  46. package/esm/api/create-api.js +0 -319
  47. package/esm/api/index.js +0 -2
  48. package/esm/api/rest-api-proxy.js +0 -18
  49. package/esm/api/types.js +0 -1
  50. package/esm/api/utils.js +0 -139
  51. package/esm/common/constants.js +0 -7
  52. package/esm/common/utils.js +0 -37
  53. package/esm/index.esm.node.js +0 -6
  54. package/esm/index.esm.worker.js +0 -6
  55. package/esm/network/FetchHttpClient.js +0 -133
  56. package/esm/network/HttpClient.js +0 -53
  57. package/esm/network/NodeHttpClient.js +0 -98
  58. package/esm/network/index.js +0 -24
  59. package/esm/network/types.js +0 -1
  60. package/esm/package.json +0 -4
  61. package/esm/sdk/constants.js +0 -10
  62. package/esm/sdk/errors.js +0 -21
  63. package/esm/sdk/index.js +0 -7
  64. package/esm/sdk/model.js +0 -143
  65. package/esm/sdk/record.js +0 -115
  66. package/esm/sdk/sdk.js +0 -42
  67. package/esm/sdk/transaction.js +0 -13
  68. package/esm/sdk/types.js +0 -1
  69. package/esm/sdk/utils.js +0 -93
  70. package/esm/types/expressions.js +0 -1
  71. package/esm/types/index.js +0 -5
  72. package/esm/types/query.js +0 -1
  73. package/esm/types/schema.js +0 -1
  74. package/esm/types/utils.js +0 -1
  75. package/esm/types/value.js +0 -1
  76. package/types/index.d.ts +0 -60
  77. /package/{types → dist}/api/api.d.ts +0 -0
  78. /package/{types → dist}/api/constants.d.ts +0 -0
  79. /package/{types → dist}/api/create-api.d.ts +0 -0
  80. /package/{types → dist}/api/index.d.ts +0 -0
  81. /package/{types → dist}/api/rest-api-proxy.d.ts +0 -0
  82. /package/{types → dist}/api/types.d.ts +0 -0
  83. /package/{types → dist}/api/utils.d.ts +0 -0
  84. /package/{types → dist}/common/constants.d.ts +0 -0
  85. /package/{types → dist}/common/utils.d.ts +0 -0
  86. /package/{types → dist}/network/FetchHttpClient.d.ts +0 -0
  87. /package/{types → dist}/network/HttpClient.d.ts +0 -0
  88. /package/{types → dist}/network/NodeHttpClient.d.ts +0 -0
  89. /package/{types → dist}/network/index.d.ts +0 -0
  90. /package/{types → dist}/network/types.d.ts +0 -0
  91. /package/{types → dist}/sdk/constants.d.ts +0 -0
  92. /package/{types → dist}/sdk/errors.d.ts +0 -0
  93. /package/{types → dist}/sdk/index.d.ts +0 -0
  94. /package/{types → dist}/sdk/types.d.ts +0 -0
  95. /package/{types → dist}/sdk/utils.d.ts +0 -0
  96. /package/{types → dist}/types/expressions.d.ts +0 -0
  97. /package/{types → dist}/types/index.d.ts +0 -0
  98. /package/{types → dist}/types/schema.d.ts +0 -0
  99. /package/{types → dist}/types/utils.d.ts +0 -0
  100. /package/{types → dist}/types/value.d.ts +0 -0
@@ -1,133 +0,0 @@
1
- import { DEFAULT_TIMEOUT } from '../common/constants.js';
2
- import { HttpClient, HttpClientGenericResponse } from './HttpClient.js';
3
- /**
4
- * HTTP client which uses a `fetch` function to issue requests.
5
- *
6
- * By default, relies on the global `fetch` function, but an optional function
7
- * can be passed in. If passing in a function, it is expected to match the Web
8
- * Fetch API. As an example, this could be the function provided by the
9
- * node-fetch package (https://github.com/node-fetch/node-fetch).
10
- */
11
- export class FetchHttpClient extends HttpClient {
12
- constructor(fetchFn) {
13
- super();
14
- // Default to global fetch if available
15
- if (!fetchFn) {
16
- if (!globalThis.fetch) {
17
- throw new Error('fetch() function not provided and is not defined in the global scope. ' +
18
- 'You must provide a fetch implementation.');
19
- }
20
- fetchFn = globalThis.fetch;
21
- }
22
- // Both timeout behaviors differs from Node:
23
- // - Fetch uses a single timeout for the entire length of the request.
24
- // - Node is more fine-grained and resets the timeout after each stage of the request.
25
- if (globalThis.AbortController) {
26
- // Utilise native AbortController if available
27
- // AbortController was added in Node v15.0.0, v14.17.0
28
- this._fetchFn = FetchHttpClient.makeFetchWithAbortTimeout(fetchFn);
29
- }
30
- else {
31
- // Fall back to racing against a timeout promise if not available in the runtime
32
- // This does not actually cancel the underlying fetch operation or resources
33
- this._fetchFn = FetchHttpClient.makeFetchWithRaceTimeout(fetchFn);
34
- }
35
- }
36
- static makeFetchWithRaceTimeout(fetchFn) {
37
- return (url, init, timeout) => {
38
- let pendingTimeoutId;
39
- const timeoutPromise = new Promise((_, reject) => {
40
- pendingTimeoutId = setTimeout(() => {
41
- pendingTimeoutId = null;
42
- reject(HttpClient.makeTimeoutError());
43
- }, timeout);
44
- });
45
- const fetchPromise = fetchFn(url, init);
46
- return Promise.race([fetchPromise, timeoutPromise]).finally(() => {
47
- if (pendingTimeoutId) {
48
- clearTimeout(pendingTimeoutId);
49
- }
50
- });
51
- };
52
- }
53
- static makeFetchWithAbortTimeout(fetchFn) {
54
- return async (url, init, timeout) => {
55
- // Use AbortController because AbortSignal.timeout() was added later in Node v17.3.0, v16.14.0
56
- const abort = new AbortController();
57
- let timeoutId = setTimeout(() => {
58
- timeoutId = null;
59
- abort.abort(HttpClient.makeTimeoutError());
60
- }, timeout);
61
- try {
62
- return await fetchFn(url, Object.assign(Object.assign({}, init), { signal: abort.signal }));
63
- }
64
- catch (err) {
65
- // Some implementations, like node-fetch, do not respect the reason passed to AbortController.abort()
66
- // and instead it always throws an AbortError
67
- // We catch this case to normalise all timeout errors
68
- if (err.name === 'AbortError') {
69
- throw HttpClient.makeTimeoutError();
70
- }
71
- else {
72
- throw err;
73
- }
74
- }
75
- finally {
76
- if (timeoutId) {
77
- clearTimeout(timeoutId);
78
- }
79
- }
80
- };
81
- }
82
- async makeRequest(url, { headers, method, protocol, requestData, timeout }) {
83
- // For methods which expect payloads, we should always pass a body value
84
- // even when it is empty. Without this, some JS runtimes (eg. Deno) will
85
- // inject a second Content-Length header.
86
- const methodHasPayload = method == 'POST' || method == 'PUT' || method == 'PATCH';
87
- const body = JSON.stringify(requestData) || (methodHasPayload ? '' : undefined);
88
- const res = await this._fetchFn(url, {
89
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
90
- // @ts-ignore
91
- body,
92
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
93
- // @ts-ignore
94
- headers,
95
- method
96
- }, timeout !== null && timeout !== void 0 ? timeout : DEFAULT_TIMEOUT);
97
- return new FetchHttpClientResponse(res);
98
- }
99
- }
100
- export class FetchHttpClientResponse extends HttpClientGenericResponse {
101
- constructor(res) {
102
- super(res.status, FetchHttpClientResponse._transformHeadersToObject(res.headers));
103
- this._res = res;
104
- }
105
- getRawResponse() {
106
- return this._res;
107
- }
108
- toStream(streamCompleteCallback) {
109
- // Unfortunately `fetch` does not have event handlers for when the stream is
110
- // completely read. We therefore invoke the streamCompleteCallback right
111
- // away. This callback emits a response event with metadata and completes
112
- // metrics, so it's ok to do this without waiting for the stream to be
113
- // completely read.
114
- streamCompleteCallback();
115
- // Fetch's `body` property is expected to be a readable stream of the body.
116
- return this._res.body;
117
- }
118
- toJSON() {
119
- return this._res.json();
120
- }
121
- static _transformHeadersToObject(headers) {
122
- // Fetch uses a Headers instance so this must be converted to a barebones
123
- // JS object to meet the HttpClient interface.
124
- const headersObj = {};
125
- for (const entry of headers) {
126
- if (!Array.isArray(entry) || entry.length != 2) {
127
- throw new Error('Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.');
128
- }
129
- headersObj[entry[0]] = entry[1];
130
- }
131
- return headersObj;
132
- }
133
- }
@@ -1,53 +0,0 @@
1
- export class HttpClient {
2
- makeRequest(url, { headers, method, protocol, requestData, timeout }) {
3
- throw new Error('makeRequest not implemented.');
4
- }
5
- static makeTimeoutError() {
6
- const timeoutErr = new TypeError(HttpClient.TIMEOUT_ERROR_CODE);
7
- timeoutErr.code = HttpClient.TIMEOUT_ERROR_CODE;
8
- return timeoutErr;
9
- }
10
- }
11
- HttpClient.CONNECTION_CLOSED_ERROR_CODES = ['ECONNRESET', 'EPIPE'];
12
- HttpClient.TIMEOUT_ERROR_CODE = 'ETIMEDOUT';
13
- export class HttpClientGenericResponse {
14
- constructor(statusCode, headers) {
15
- this._statusCode = statusCode;
16
- this._headers = headers;
17
- }
18
- getStatusCode() {
19
- return this._statusCode;
20
- }
21
- getHeaders() {
22
- return this._headers;
23
- }
24
- getRawResponse() {
25
- throw new Error('getRawResponse not implemented.');
26
- }
27
- toStream(streamCompleteCallback) {
28
- throw new Error('toStream not implemented.');
29
- }
30
- toJSON() {
31
- throw new Error('toJSON not implemented.');
32
- }
33
- }
34
- export class HttpClientResponse {
35
- constructor(response) {
36
- this._res = response;
37
- }
38
- getStatusCode() {
39
- throw new Error('getStatusCode not implemented.');
40
- }
41
- getHeaders() {
42
- throw new Error('getHeaders not implemented.');
43
- }
44
- getRawResponse() {
45
- throw new Error('getRawResponse not implemented.');
46
- }
47
- toStream(streamCompleteCallback) {
48
- throw new Error('toStream not implemented.');
49
- }
50
- toJSON() {
51
- throw new Error('toJSON not implemented.');
52
- }
53
- }
@@ -1,98 +0,0 @@
1
- import * as http_ from 'http';
2
- import * as https_ from 'https';
3
- import { DEFAULT_TIMEOUT } from '../common/constants.js';
4
- import { HttpClient, HttpClientGenericResponse } from './HttpClient.js';
5
- // `import * as http_ from 'http'` creates a "Module Namespace Exotic Object"
6
- // which is immune to monkey-patching, whereas http_.default (in an ES Module context)
7
- // will resolve to the same thing as require('http'), which is
8
- // monkey-patchable. We care about this because users in their test
9
- // suites might be using a library like "nock" which relies on the ability
10
- // to monkey-patch and intercept calls to http.request.
11
- const http = http_.default || http_;
12
- const https = https_.default || https_;
13
- const defaultHttpAgent = new http.Agent({ keepAlive: true });
14
- const defaultHttpsAgent = new https.Agent({ keepAlive: true });
15
- export class NodeHttpClient extends HttpClient {
16
- constructor(agent) {
17
- super();
18
- this._agent = agent;
19
- }
20
- makeRequest(urlString, { headers, method, protocol, requestData, timeout }) {
21
- const url = new URL(urlString);
22
- const isInsecureConnection = protocol === 'http' || url.protocol === 'http:';
23
- let agent = this._agent;
24
- if (!agent) {
25
- agent = isInsecureConnection ? defaultHttpAgent : defaultHttpsAgent;
26
- }
27
- return new Promise((resolve, reject) => {
28
- const req = (isInsecureConnection ? http : https).request({
29
- agent,
30
- ciphers: 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5',
31
- headers,
32
- host: url.hostname,
33
- method,
34
- path: url.pathname + url.search,
35
- port: url.port
36
- });
37
- req.setTimeout(timeout !== null && timeout !== void 0 ? timeout : DEFAULT_TIMEOUT, () => {
38
- req.destroy(HttpClient.makeTimeoutError());
39
- });
40
- req.on('response', (res) => {
41
- resolve(new NodeHttpClientResponse(res));
42
- });
43
- req.on('error', (error) => {
44
- reject(error);
45
- });
46
- req.once('socket', (socket) => {
47
- const payload = requestData ? JSON.stringify(requestData) : '';
48
- if (socket.connecting) {
49
- socket.once(isInsecureConnection ? 'connect' : 'secureConnect', () => {
50
- // Send payload; we're safe:
51
- req.write(payload);
52
- req.end();
53
- });
54
- }
55
- else {
56
- // we're already connected
57
- req.write(payload);
58
- req.end();
59
- }
60
- });
61
- });
62
- }
63
- }
64
- export class NodeHttpClientResponse extends HttpClientGenericResponse {
65
- constructor(res) {
66
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
67
- // @ts-ignore
68
- super(res.statusCode, res.headers || {});
69
- this._res = res;
70
- }
71
- getRawResponse() {
72
- return this._res;
73
- }
74
- toStream(streamCompleteCallback) {
75
- // The raw response is itself the stream, so we just return that. To be
76
- // backwards compatible, we should invoke the streamCompleteCallback only
77
- // once the stream has been fully consumed.
78
- this._res.once('end', () => streamCompleteCallback());
79
- return this._res;
80
- }
81
- toJSON() {
82
- return new Promise((resolve, reject) => {
83
- let response = '';
84
- this._res.setEncoding('utf8');
85
- this._res.on('data', (chunk) => {
86
- response += chunk;
87
- });
88
- this._res.once('end', () => {
89
- try {
90
- resolve(JSON.parse(response));
91
- }
92
- catch (e) {
93
- reject(e);
94
- }
95
- });
96
- });
97
- }
98
- }
@@ -1,24 +0,0 @@
1
- var __rest = (this && this.__rest) || function (s, e) {
2
- var t = {};
3
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
- t[p] = s[p];
5
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
- t[p[i]] = s[p[i]];
9
- }
10
- return t;
11
- };
12
- const defaultHeaders = {
13
- 'Content-Type': 'application/json'
14
- };
15
- export const createFetcher = ({ httpClient, token, url }) => async (input, _a) => {
16
- var { headers: initHeaders } = _a, init = __rest(_a, ["headers"]);
17
- const response = await httpClient.makeRequest(`${url}${input}`, Object.assign({ credentials: 'omit', headers: Object.assign(Object.assign(Object.assign({}, defaultHeaders), initHeaders), typeof token !== 'undefined' ? { token } : {}) }, init));
18
- if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) {
19
- const data = await response.toJSON();
20
- return data;
21
- }
22
- // @TODO: Make it more useful
23
- throw new Error(`${response.getStatusCode()}`);
24
- };
@@ -1 +0,0 @@
1
- export {};
package/esm/package.json DELETED
@@ -1,4 +0,0 @@
1
- {
2
- "type": "module",
3
- "name": "@rushdb/javascript-sdk"
4
- }
@@ -1,10 +0,0 @@
1
- export const ALLOWED_CONFIG_PROPERTIES = [
2
- 'httpClient',
3
- 'timeout',
4
- 'host',
5
- 'port',
6
- 'protocol',
7
- 'url',
8
- 'validator',
9
- 'logger'
10
- ];
package/esm/sdk/errors.js DELETED
@@ -1,21 +0,0 @@
1
- export class UniquenessError extends Error {
2
- constructor(label, properties) {
3
- super(`Record with label "${label}" and properties ${JSON.stringify(properties)} already exists`);
4
- this.name = 'UniquenessError';
5
- Object.setPrototypeOf(this, UniquenessError.prototype);
6
- }
7
- }
8
- export class EmptyTargetError extends Error {
9
- constructor(message) {
10
- super(message);
11
- this.name = 'EmptyTarget';
12
- Object.setPrototypeOf(this, EmptyTargetError.prototype);
13
- }
14
- }
15
- export class NonUniqueResultError extends Error {
16
- constructor(duplicateCount, searchParams) {
17
- super(`Expected a unique result but found ${duplicateCount} matches for the provided search parameters: ${JSON.stringify(searchParams)}. Ensure your search parameters uniquely identify a single result.`);
18
- this.name = 'NonUniqueResultError';
19
- Object.setPrototypeOf(this, NonUniqueResultError.prototype);
20
- }
21
- }
package/esm/sdk/index.js DELETED
@@ -1,7 +0,0 @@
1
- export * from './sdk.js';
2
- export * from './types.js';
3
- export * from './errors.js';
4
- export * from './transaction.js';
5
- export * from './utils.js';
6
- export * from './record.js';
7
- export * from './model.js';
package/esm/sdk/model.js DELETED
@@ -1,143 +0,0 @@
1
- import { RestApiProxy } from '../api/rest-api-proxy.js';
2
- import { isEmptyObject } from '../common/utils.js';
3
- import { EmptyTargetError, UniquenessError } from './errors.js';
4
- import { mergeDefaultsWithPayload, pickUniqFieldsFromRecord, pickUniqFieldsFromRecords } from './utils.js';
5
- export class Model extends RestApiProxy {
6
- constructor(modelName, schema, RushDBInstance) {
7
- super();
8
- this.label = modelName;
9
- this.schema = schema;
10
- RushDBInstance === null || RushDBInstance === void 0 ? void 0 : RushDBInstance.registerModel(this);
11
- }
12
- getLabel() {
13
- return this.label;
14
- }
15
- async find(params = {}, transaction) {
16
- var _a;
17
- return (_a = this.apiProxy) === null || _a === void 0 ? void 0 : _a.records.find(this.label, params, transaction);
18
- }
19
- async findOne(params = {}, transaction) {
20
- var _a;
21
- return (_a = this.apiProxy) === null || _a === void 0 ? void 0 : _a.records.findOne(this.label, Object.assign({}, params), transaction);
22
- }
23
- async findById(id, transaction) {
24
- return this.findOne({ where: { $id: id } }, transaction);
25
- }
26
- async findUniq(params = {}, transaction) {
27
- var _a;
28
- return (_a = this.apiProxy) === null || _a === void 0 ? void 0 : _a.records.findUniq(this.label, Object.assign({}, params), transaction);
29
- }
30
- async create(record, transaction) {
31
- var _a;
32
- const data = await mergeDefaultsWithPayload(this.schema, record);
33
- const uniqFields = pickUniqFieldsFromRecord(this.schema, data);
34
- if (!isEmptyObject(uniqFields)) {
35
- const tx = transaction !== null && transaction !== void 0 ? transaction : (await this.apiProxy.tx.begin());
36
- const matchingRecords = await this.find({ where: uniqFields }, tx);
37
- const hasOwnTransaction = typeof transaction !== 'undefined';
38
- const canCreate = !((_a = matchingRecords === null || matchingRecords === void 0 ? void 0 : matchingRecords.data) === null || _a === void 0 ? void 0 : _a.length);
39
- if (canCreate) {
40
- const result = await this.apiProxy.records.create(this.label, data, tx);
41
- if (!hasOwnTransaction) {
42
- await tx.commit();
43
- }
44
- return result;
45
- }
46
- else {
47
- if (!hasOwnTransaction) {
48
- await tx.commit();
49
- }
50
- // @TODO: Make it optional
51
- throw new UniquenessError(this.label, uniqFields);
52
- }
53
- }
54
- return await this.apiProxy.records.create(this.label, data, transaction);
55
- }
56
- attach(sourceId, target, options, transaction) {
57
- return this.apiProxy.records.attach(sourceId, target, options, transaction);
58
- }
59
- detach(sourceId, target, options, transaction) {
60
- return this.apiProxy.records.detach(sourceId, target, options, transaction);
61
- }
62
- async handleSetOrUpdate(id, record, method, transaction) {
63
- var _a;
64
- const data = await mergeDefaultsWithPayload(this.schema, record);
65
- const uniqFields = pickUniqFieldsFromRecord(this.schema, data);
66
- if (!isEmptyObject(uniqFields)) {
67
- const tx = transaction !== null && transaction !== void 0 ? transaction : (await this.apiProxy.tx.begin());
68
- const matchingRecords = await this.find({ where: uniqFields }, tx);
69
- const hasOwnTransaction = typeof transaction !== 'undefined';
70
- const canUpdate = !((_a = matchingRecords === null || matchingRecords === void 0 ? void 0 : matchingRecords.data) === null || _a === void 0 ? void 0 : _a.length) ||
71
- (matchingRecords.data.length === 1 && matchingRecords.data[0].__id === id);
72
- if (canUpdate) {
73
- const result = await this.apiProxy.records[method](id, data, tx);
74
- if (!hasOwnTransaction) {
75
- await tx.commit();
76
- }
77
- return result;
78
- }
79
- else {
80
- if (!hasOwnTransaction) {
81
- await tx.commit();
82
- }
83
- throw new UniquenessError(this.label, uniqFields);
84
- }
85
- }
86
- return await this.apiProxy.records[method](id, data, transaction);
87
- }
88
- async set(id, record, transaction) {
89
- return await this.handleSetOrUpdate(id, record, 'set', transaction);
90
- }
91
- async update(id, record, transaction) {
92
- return await this.handleSetOrUpdate(id, record, 'update', transaction);
93
- }
94
- async createMany(records, transaction) {
95
- var _a;
96
- // Begin a transaction if one isn't provided.
97
- const hasOwnTransaction = typeof transaction !== 'undefined';
98
- const tx = transaction !== null && transaction !== void 0 ? transaction : (await this.apiProxy.tx.begin());
99
- try {
100
- // Apply defaults in parallel
101
- const recordsToStore = await Promise.all(records.map(async (record) => {
102
- return await mergeDefaultsWithPayload(this.schema, record);
103
- }));
104
- // Check uniqueness
105
- const uniqProperties = pickUniqFieldsFromRecords(recordsToStore, this.schema, this.label);
106
- if (!isEmptyObject(uniqProperties)) {
107
- const criteria = Object.entries(uniqProperties).map(([key, values]) => ({
108
- [key]: { $in: values }
109
- }));
110
- const matchingRecords = await this.find({
111
- where: {
112
- $or: criteria
113
- }
114
- }, tx);
115
- if ((_a = matchingRecords === null || matchingRecords === void 0 ? void 0 : matchingRecords.data) === null || _a === void 0 ? void 0 : _a.length) {
116
- throw new UniquenessError(this.label, Object.keys(uniqProperties));
117
- }
118
- }
119
- // Create records in the database
120
- const createdRecords = await this.apiProxy.records.createMany(this.label, recordsToStore, tx);
121
- // Commit the transaction if it was created internally
122
- if (!hasOwnTransaction) {
123
- await tx.commit();
124
- }
125
- return createdRecords;
126
- }
127
- catch (error) {
128
- if (!hasOwnTransaction) {
129
- await tx.rollback();
130
- }
131
- throw error;
132
- }
133
- }
134
- async delete(searchParams, transaction) {
135
- if (isEmptyObject(searchParams.where)) {
136
- throw new EmptyTargetError(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);
137
- }
138
- return await this.apiProxy.records.delete(Object.assign(Object.assign({}, searchParams), { labels: [this.label] }), transaction);
139
- }
140
- async deleteById(idOrIds, transaction) {
141
- return await this.apiProxy.records.deleteById(idOrIds, transaction);
142
- }
143
- }
package/esm/sdk/record.js DELETED
@@ -1,115 +0,0 @@
1
- import { RestApiProxy } from '../api/rest-api-proxy.js';
2
- import { idToDate, idToTimestamp } from './utils.js';
3
- export class DBRecordsBatchDraft {
4
- constructor({ label, options = {
5
- returnResult: true,
6
- suggestTypes: true
7
- }, payload }) {
8
- this.label = label;
9
- this.options = options;
10
- this.payload = payload;
11
- }
12
- toJson() {
13
- return {
14
- label: this.label,
15
- options: this.options,
16
- payload: this.payload
17
- };
18
- }
19
- }
20
- export class DBRecordDraft {
21
- constructor({ label, properties = [] }) {
22
- this.label = label;
23
- this.properties = properties;
24
- }
25
- toJson() {
26
- return {
27
- label: this.label,
28
- properties: this.properties
29
- };
30
- }
31
- }
32
- export class DBRecordInstance extends RestApiProxy {
33
- constructor(data) {
34
- super();
35
- this.data = data;
36
- }
37
- get id() {
38
- try {
39
- return this.data.__id;
40
- }
41
- catch (_a) {
42
- throw new Error(`DBRecordInstance: Unable to access 'id'. The Record data is undefined.`);
43
- }
44
- }
45
- get label() {
46
- try {
47
- return this.data.__label;
48
- }
49
- catch (_a) {
50
- throw new Error(`DBRecordInstance: Unable to access 'label'. The Record data is undefined.`);
51
- }
52
- }
53
- get proptypes() {
54
- try {
55
- return this.data.__proptypes;
56
- }
57
- catch (_a) {
58
- throw new Error(`DBRecordInstance: Unable to access 'proptypes'. The Record data' is undefined.`);
59
- }
60
- }
61
- get date() {
62
- try {
63
- return idToDate(this.data.__id);
64
- }
65
- catch (_a) {
66
- throw new Error(`DBRecordInstance: Unable to access 'date'. The Record data is undefined.`);
67
- }
68
- }
69
- get timestamp() {
70
- try {
71
- return idToTimestamp(this.data.__id);
72
- }
73
- catch (_a) {
74
- throw new Error(`DBRecordInstance: Unable to access 'timestamp'. The Record data is undefined.`);
75
- }
76
- }
77
- async delete(transaction) {
78
- if (!this.data) {
79
- throw new Error('DBRecordInstance: Unable to delete Record. The Record data is undefined.');
80
- }
81
- return await this.apiProxy.records.deleteById(this.data.__id, transaction);
82
- }
83
- async update(partialData, transaction) {
84
- if (!this.data) {
85
- throw new Error('DBRecordInstance: Unable to update Record. The Record data is undefined.');
86
- }
87
- return this.apiProxy.records.update(this.data.__id, partialData, transaction);
88
- }
89
- async set(data, transaction) {
90
- if (!this.data) {
91
- throw new Error('DBRecordInstance: Unable to set. The Record data is undefined.');
92
- }
93
- return this.apiProxy.records.set(this.data.__id, data, transaction);
94
- }
95
- async attach(target, options, transaction) {
96
- if (!this.data) {
97
- throw new Error('DBRecordInstance: Unable to attach Record. The Record data is undefined.');
98
- }
99
- return this.apiProxy.records.attach(this.data.__id, target, options, transaction);
100
- }
101
- async detach(target, options, transaction) {
102
- if (!this.data) {
103
- throw new Error('DBRecordInstance: Unable to detach Record. The Record data is undefined.');
104
- }
105
- return this.apiProxy.records.detach(this.data.__id, target, options, transaction);
106
- }
107
- }
108
- export class DBRecordsArrayInstance extends RestApiProxy {
109
- constructor(data, total, searchParams) {
110
- super();
111
- this.data = data;
112
- this.total = total;
113
- this.searchParams = searchParams;
114
- }
115
- }
package/esm/sdk/sdk.js DELETED
@@ -1,42 +0,0 @@
1
- import { RestAPI } from '../api/api.js';
2
- import { DEFAULT_TIMEOUT } from '../common/constants.js';
3
- import { DBRecordInstance } from './record.js';
4
- import { parseConfig, validateInteger } from './utils.js';
5
- export const initSDK = (httpClient) => {
6
- class RushDB extends RestAPI {
7
- constructor(token, config) {
8
- var _a;
9
- const props = parseConfig(config);
10
- super(token, Object.assign(Object.assign({}, props), { httpClient: (_a = props.httpClient) !== null && _a !== void 0 ? _a : httpClient }));
11
- this.state = {
12
- debug: false,
13
- timeout: validateInteger('timeout', props.timeout, DEFAULT_TIMEOUT),
14
- token
15
- };
16
- this.models = new Map();
17
- RushDB.instance = this;
18
- }
19
- static getInstance() {
20
- return RushDB.instance;
21
- }
22
- registerModel(model) {
23
- const label = model.getLabel();
24
- // Inject the API into the model
25
- model.init(this);
26
- this.models.set(label, model);
27
- return model; //as unknown as Model<T['schema']> & Omit<RestAPI, 'find'>
28
- }
29
- getModels() {
30
- return this.models;
31
- }
32
- getModel(label) {
33
- return this.models.get(label);
34
- }
35
- toInstance(record) {
36
- const result = new DBRecordInstance(record);
37
- result.init(this);
38
- return result;
39
- }
40
- }
41
- return RushDB;
42
- };
@@ -1,13 +0,0 @@
1
- import { RestApiProxy } from '../api/rest-api-proxy.js';
2
- export class Transaction extends RestApiProxy {
3
- constructor(id) {
4
- super();
5
- this.id = id;
6
- }
7
- async rollback() {
8
- return await this.apiProxy.tx.rollback(this.id);
9
- }
10
- async commit() {
11
- return await this.apiProxy.tx.commit(this.id);
12
- }
13
- }
package/esm/sdk/types.js DELETED
@@ -1 +0,0 @@
1
- export {};