@xata.io/client
Advanced tools
Comparing version 0.0.0-alpha.3c907b2 to 0.0.0-alpha.3d0997b
@@ -7,3 +7,3 @@ import type * as Types from './components'; | ||
export interface XataApiClientOptions { | ||
fetchImpl: FetchImpl; | ||
fetch: FetchImpl; | ||
apiKey: string; | ||
@@ -13,9 +13,9 @@ host?: HostProvider; | ||
export declare class XataApiClient { | ||
private extraProps; | ||
#private; | ||
constructor(options: XataApiClientOptions); | ||
get user(): UserApi; | ||
get workspace(): WorkspaceApi; | ||
get database(): DatabaseApi; | ||
get branch(): BranchApi; | ||
get table(): TableApi; | ||
get workspaces(): WorkspaceApi; | ||
get databases(): DatabaseApi; | ||
get branches(): BranchApi; | ||
get tables(): TableApi; | ||
get records(): RecordsApi; | ||
@@ -59,3 +59,3 @@ } | ||
getBranchDetails(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName): Promise<Schemas.DBBranch>; | ||
createBranch(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, from?: string, options?: Types.CreateBranchRequestBody): Promise<undefined>; | ||
createBranch(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, from?: string, options?: Types.CreateBranchRequestBody): Promise<void>; | ||
deleteBranch(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName): Promise<void>; | ||
@@ -87,3 +87,5 @@ updateBranchMetadata(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, metadata?: Schemas.BranchMetadata): Promise<void>; | ||
insertRecord(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, tableName: Schemas.TableName, record: Record<string, any>): Promise<Types.InsertRecordResponse>; | ||
insertRecordWithID(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, tableName: Schemas.TableName, recordId: Schemas.RecordID, record: Record<string, any>, options?: Types.InsertRecordWithIDQueryParams): Promise<Types.InsertRecordWithIDResponse>; | ||
insertRecordWithID(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, tableName: Schemas.TableName, recordId: Schemas.RecordID, record: Record<string, any>, options?: Types.InsertRecordWithIDQueryParams): Promise<Responses.RecordUpdateResponse>; | ||
updateRecordWithID(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, tableName: Schemas.TableName, recordId: Schemas.RecordID, record: Record<string, any>, options?: Types.UpdateRecordWithIDQueryParams): Promise<Responses.RecordUpdateResponse>; | ||
upsertRecordWithID(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, tableName: Schemas.TableName, recordId: Schemas.RecordID, record: Record<string, any>, options?: Types.UpsertRecordWithIDQueryParams): Promise<Responses.RecordUpdateResponse>; | ||
deleteRecord(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, tableName: Schemas.TableName, recordId: Schemas.RecordID): Promise<void>; | ||
@@ -93,3 +95,4 @@ getRecord(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, tableName: Schemas.TableName, recordId: Schemas.RecordID, options?: Types.GetRecordRequestBody): Promise<Schemas.XataRecord>; | ||
queryTable(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, tableName: Schemas.TableName, query: Types.QueryTableRequestBody): Promise<Responses.QueryResponse>; | ||
searchBranch(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, query: Types.SearchBranchRequestBody): Promise<Responses.SearchResponse>; | ||
} | ||
export {}; |
"use strict"; | ||
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { | ||
if (kind === "m") throw new TypeError("Private method is not writable"); | ||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); | ||
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"); | ||
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; | ||
}; | ||
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { | ||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); | ||
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"); | ||
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); | ||
}; | ||
var _XataApiClient_extraProps; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.XataApiClient = void 0; | ||
const errors_1 = require("../util/errors"); | ||
const components_1 = require("./components"); | ||
@@ -10,8 +21,10 @@ const providers_1 = require("./providers"); | ||
var _a; | ||
const fetchImpl = typeof fetch !== 'undefined' ? fetch : options.fetchImpl; | ||
_XataApiClient_extraProps.set(this, void 0); | ||
const fetchImpl = typeof fetch !== 'undefined' ? fetch : options.fetch; | ||
if (!fetchImpl) { | ||
throw new Error(errors_1.errors.noFetchImplementation); | ||
/** @todo add a link after docs exist */ | ||
throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`); | ||
} | ||
const provider = (_a = options.host) !== null && _a !== void 0 ? _a : 'production'; | ||
this.extraProps = { | ||
__classPrivateFieldSet(this, _XataApiClient_extraProps, { | ||
apiUrl: (0, providers_1.getHostUrl)(provider, 'main'), | ||
@@ -21,24 +34,25 @@ workspacesApiUrl: (0, providers_1.getHostUrl)(provider, 'workspaces'), | ||
apiKey: options.apiKey | ||
}; | ||
}, "f"); | ||
} | ||
get user() { | ||
return new UserApi(this.extraProps); | ||
return new UserApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f")); | ||
} | ||
get workspace() { | ||
return new WorkspaceApi(this.extraProps); | ||
get workspaces() { | ||
return new WorkspaceApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f")); | ||
} | ||
get database() { | ||
return new DatabaseApi(this.extraProps); | ||
get databases() { | ||
return new DatabaseApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f")); | ||
} | ||
get branch() { | ||
return new BranchApi(this.extraProps); | ||
get branches() { | ||
return new BranchApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f")); | ||
} | ||
get table() { | ||
return new TableApi(this.extraProps); | ||
get tables() { | ||
return new TableApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f")); | ||
} | ||
get records() { | ||
return new RecordsApi(this.extraProps); | ||
return new RecordsApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f")); | ||
} | ||
} | ||
exports.XataApiClient = XataApiClient; | ||
_XataApiClient_extraProps = new WeakMap(); | ||
class UserApi { | ||
@@ -196,2 +210,8 @@ constructor(extraProps) { | ||
} | ||
updateRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) { | ||
return components_1.operationsByTag.records.updateRecordWithID(Object.assign({ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId }, queryParams: options, body: record }, this.extraProps)); | ||
} | ||
upsertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) { | ||
return components_1.operationsByTag.records.upsertRecordWithID(Object.assign({ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId }, queryParams: options, body: record }, this.extraProps)); | ||
} | ||
deleteRecord(workspace, database, branch, tableName, recordId) { | ||
@@ -209,2 +229,5 @@ return components_1.operationsByTag.records.deleteRecord(Object.assign({ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId } }, this.extraProps)); | ||
} | ||
searchBranch(workspace, database, branch, query) { | ||
return components_1.operationsByTag.records.searchBranch(Object.assign({ pathParams: { workspace, dbBranchName: `${database}:${branch}` }, body: query }, this.extraProps)); | ||
} | ||
} |
@@ -164,40 +164,2 @@ /** | ||
export declare const inviteWorkspaceMember: (variables: InviteWorkspaceMemberVariables) => Promise<Schemas.WorkspaceInvite>; | ||
export declare type UpdateWorkspaceMemberInvitePathParams = { | ||
workspaceId: Schemas.WorkspaceID; | ||
inviteId: Schemas.InviteID; | ||
}; | ||
export declare type UpdateWorkspaceMemberInviteRequestBody = { | ||
role: Schemas.Role; | ||
}; | ||
export declare type UpdateWorkspaceMemberInviteVariables = { | ||
body: UpdateWorkspaceMemberInviteRequestBody; | ||
pathParams: UpdateWorkspaceMemberInvitePathParams; | ||
} & FetcherExtraProps; | ||
/** | ||
* This operation provides a way to update an invite. | ||
* The role can be updated while the email cannot. | ||
*/ | ||
export declare const updateWorkspaceMemberInvite: (variables: UpdateWorkspaceMemberInviteVariables) => Promise<Schemas.WorkspaceInvite>; | ||
export declare type CancelWorkspaceMemberInvitePathParams = { | ||
workspaceId: Schemas.WorkspaceID; | ||
inviteId: Schemas.InviteID; | ||
}; | ||
export declare type CancelWorkspaceMemberInviteVariables = { | ||
pathParams: CancelWorkspaceMemberInvitePathParams; | ||
} & FetcherExtraProps; | ||
/** | ||
* This operation provides a way to cancel invites by deleting them. Already accepted invites cannot be deleted. | ||
*/ | ||
export declare const cancelWorkspaceMemberInvite: (variables: CancelWorkspaceMemberInviteVariables) => Promise<undefined>; | ||
export declare type ResendWorkspaceMemberInvitePathParams = { | ||
workspaceId: Schemas.WorkspaceID; | ||
inviteId: Schemas.InviteID; | ||
}; | ||
export declare type ResendWorkspaceMemberInviteVariables = { | ||
pathParams: ResendWorkspaceMemberInvitePathParams; | ||
} & FetcherExtraProps; | ||
/** | ||
* This operation provides a way to resend an Invite notification. Invite notifications can only be sent for Invites not yet accepted. | ||
*/ | ||
export declare const resendWorkspaceMemberInvite: (variables: ResendWorkspaceMemberInviteVariables) => Promise<undefined>; | ||
export declare type AcceptWorkspaceMemberInvitePathParams = { | ||
@@ -570,8 +532,2 @@ workspaceId: Schemas.WorkspaceID; | ||
}; | ||
export declare type InsertRecordWithIDResponse = { | ||
id: string; | ||
xata: { | ||
version: number; | ||
}; | ||
}; | ||
export declare type InsertRecordWithIDVariables = { | ||
@@ -585,3 +541,33 @@ body?: Record<string, any>; | ||
*/ | ||
export declare const insertRecordWithID: (variables: InsertRecordWithIDVariables) => Promise<InsertRecordWithIDResponse>; | ||
export declare const insertRecordWithID: (variables: InsertRecordWithIDVariables) => Promise<Responses.RecordUpdateResponse>; | ||
export declare type UpdateRecordWithIDPathParams = { | ||
dbBranchName: Schemas.DBBranchName; | ||
tableName: Schemas.TableName; | ||
recordId: Schemas.RecordID; | ||
workspace: string; | ||
}; | ||
export declare type UpdateRecordWithIDQueryParams = { | ||
ifVersion?: number; | ||
}; | ||
export declare type UpdateRecordWithIDVariables = { | ||
body?: Record<string, any>; | ||
pathParams: UpdateRecordWithIDPathParams; | ||
queryParams?: UpdateRecordWithIDQueryParams; | ||
} & FetcherExtraProps; | ||
export declare const updateRecordWithID: (variables: UpdateRecordWithIDVariables) => Promise<Responses.RecordUpdateResponse>; | ||
export declare type UpsertRecordWithIDPathParams = { | ||
dbBranchName: Schemas.DBBranchName; | ||
tableName: Schemas.TableName; | ||
recordId: Schemas.RecordID; | ||
workspace: string; | ||
}; | ||
export declare type UpsertRecordWithIDQueryParams = { | ||
ifVersion?: number; | ||
}; | ||
export declare type UpsertRecordWithIDVariables = { | ||
body?: Record<string, any>; | ||
pathParams: UpsertRecordWithIDPathParams; | ||
queryParams?: UpsertRecordWithIDQueryParams; | ||
} & FetcherExtraProps; | ||
export declare const upsertRecordWithID: (variables: UpsertRecordWithIDVariables) => Promise<Responses.RecordUpdateResponse>; | ||
export declare type DeleteRecordPathParams = { | ||
@@ -1362,2 +1348,3 @@ dbBranchName: Schemas.DBBranchName; | ||
query: string; | ||
fuzziness?: number; | ||
}; | ||
@@ -1369,3 +1356,3 @@ export declare type SearchBranchVariables = { | ||
/** | ||
* Run a free text search operation across the Database. | ||
* Run a free text search operation across the database branch. | ||
*/ | ||
@@ -1392,5 +1379,2 @@ export declare const searchBranch: (variables: SearchBranchVariables) => Promise<Responses.SearchResponse>; | ||
inviteWorkspaceMember: (variables: InviteWorkspaceMemberVariables) => Promise<Schemas.WorkspaceInvite>; | ||
updateWorkspaceMemberInvite: (variables: UpdateWorkspaceMemberInviteVariables) => Promise<Schemas.WorkspaceInvite>; | ||
cancelWorkspaceMemberInvite: (variables: CancelWorkspaceMemberInviteVariables) => Promise<undefined>; | ||
resendWorkspaceMemberInvite: (variables: ResendWorkspaceMemberInviteVariables) => Promise<undefined>; | ||
acceptWorkspaceMemberInvite: (variables: AcceptWorkspaceMemberInviteVariables) => Promise<undefined>; | ||
@@ -1429,3 +1413,5 @@ }; | ||
insertRecord: (variables: InsertRecordVariables) => Promise<InsertRecordResponse>; | ||
insertRecordWithID: (variables: InsertRecordWithIDVariables) => Promise<InsertRecordWithIDResponse>; | ||
insertRecordWithID: (variables: InsertRecordWithIDVariables) => Promise<Responses.RecordUpdateResponse>; | ||
updateRecordWithID: (variables: UpdateRecordWithIDVariables) => Promise<Responses.RecordUpdateResponse>; | ||
upsertRecordWithID: (variables: UpsertRecordWithIDVariables) => Promise<Responses.RecordUpdateResponse>; | ||
deleteRecord: (variables: DeleteRecordVariables) => Promise<undefined>; | ||
@@ -1432,0 +1418,0 @@ getRecord: (variables: GetRecordVariables) => Promise<Schemas.XataRecord>; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.operationsByTag = exports.searchBranch = exports.queryTable = exports.bulkInsertTableRecords = exports.getRecord = exports.deleteRecord = exports.insertRecordWithID = exports.insertRecord = exports.updateColumn = exports.deleteColumn = exports.getColumn = exports.addTableColumn = exports.getTableColumns = exports.setTableSchema = exports.getTableSchema = exports.updateTable = exports.deleteTable = exports.createTable = exports.getBranchStats = exports.getBranchMigrationPlan = exports.executeBranchMigrationPlan = exports.getBranchMigrationHistory = exports.getBranchMetadata = exports.updateBranchMetadata = exports.deleteBranch = exports.createBranch = exports.getBranchDetails = exports.deleteDatabase = exports.createDatabase = exports.getBranchList = exports.getDatabaseList = exports.acceptWorkspaceMemberInvite = exports.resendWorkspaceMemberInvite = exports.cancelWorkspaceMemberInvite = exports.updateWorkspaceMemberInvite = exports.inviteWorkspaceMember = exports.removeWorkspaceMember = exports.updateWorkspaceMemberRole = exports.getWorkspaceMembersList = exports.deleteWorkspace = exports.updateWorkspace = exports.getWorkspace = exports.getWorkspacesList = exports.createWorkspace = exports.deleteUserAPIKey = exports.createUserAPIKey = exports.getUserAPIKeys = exports.deleteUser = exports.updateUser = exports.getUser = void 0; | ||
exports.operationsByTag = exports.searchBranch = exports.queryTable = exports.bulkInsertTableRecords = exports.getRecord = exports.deleteRecord = exports.upsertRecordWithID = exports.updateRecordWithID = exports.insertRecordWithID = exports.insertRecord = exports.updateColumn = exports.deleteColumn = exports.getColumn = exports.addTableColumn = exports.getTableColumns = exports.setTableSchema = exports.getTableSchema = exports.updateTable = exports.deleteTable = exports.createTable = exports.getBranchStats = exports.getBranchMigrationPlan = exports.executeBranchMigrationPlan = exports.getBranchMigrationHistory = exports.getBranchMetadata = exports.updateBranchMetadata = exports.deleteBranch = exports.createBranch = exports.getBranchDetails = exports.deleteDatabase = exports.createDatabase = exports.getBranchList = exports.getDatabaseList = exports.acceptWorkspaceMemberInvite = exports.inviteWorkspaceMember = exports.removeWorkspaceMember = exports.updateWorkspaceMemberRole = exports.getWorkspaceMembersList = exports.deleteWorkspace = exports.updateWorkspace = exports.getWorkspace = exports.getWorkspacesList = exports.createWorkspace = exports.deleteUserAPIKey = exports.createUserAPIKey = exports.getUserAPIKeys = exports.deleteUser = exports.updateUser = exports.getUser = void 0; | ||
/** | ||
@@ -86,18 +86,2 @@ * Generated by @openapi-codegen | ||
/** | ||
* This operation provides a way to update an invite. | ||
* The role can be updated while the email cannot. | ||
*/ | ||
const updateWorkspaceMemberInvite = (variables) => (0, fetcher_1.fetch)(Object.assign({ url: '/workspaces/{workspaceId}/invites/{inviteId}', method: 'patch' }, variables)); | ||
exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite; | ||
/** | ||
* This operation provides a way to cancel invites by deleting them. Already accepted invites cannot be deleted. | ||
*/ | ||
const cancelWorkspaceMemberInvite = (variables) => (0, fetcher_1.fetch)(Object.assign({ url: '/workspaces/{workspaceId}/invites/{inviteId}', method: 'delete' }, variables)); | ||
exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite; | ||
/** | ||
* This operation provides a way to resend an Invite notification. Invite notifications can only be sent for Invites not yet accepted. | ||
*/ | ||
const resendWorkspaceMemberInvite = (variables) => (0, fetcher_1.fetch)(Object.assign({ url: '/workspaces/{workspaceId}/invites/{inviteId}/resend', method: 'post' }, variables)); | ||
exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite; | ||
/** | ||
* Accept the invitation to join a workspace. If the operation succeeds the user will be a member of the workspace | ||
@@ -226,2 +210,6 @@ */ | ||
exports.insertRecordWithID = insertRecordWithID; | ||
const updateRecordWithID = (variables) => (0, fetcher_1.fetch)(Object.assign({ url: '/db/{dbBranchName}/tables/{tableName}/data/{recordId}', method: 'patch' }, variables)); | ||
exports.updateRecordWithID = updateRecordWithID; | ||
const upsertRecordWithID = (variables) => (0, fetcher_1.fetch)(Object.assign({ url: '/db/{dbBranchName}/tables/{tableName}/data/{recordId}', method: 'post' }, variables)); | ||
exports.upsertRecordWithID = upsertRecordWithID; | ||
const deleteRecord = (variables) => (0, fetcher_1.fetch)(Object.assign({ url: '/db/{dbBranchName}/tables/{tableName}/data/{recordId}', method: 'delete' }, variables)); | ||
@@ -948,3 +936,3 @@ exports.deleteRecord = deleteRecord; | ||
/** | ||
* Run a free text search operation across the Database. | ||
* Run a free text search operation across the database branch. | ||
*/ | ||
@@ -965,5 +953,2 @@ const searchBranch = (variables) => (0, fetcher_1.fetch)(Object.assign({ url: '/db/{dbBranchName}/search', method: 'post' }, variables)); | ||
inviteWorkspaceMember: exports.inviteWorkspaceMember, | ||
updateWorkspaceMemberInvite: exports.updateWorkspaceMemberInvite, | ||
cancelWorkspaceMemberInvite: exports.cancelWorkspaceMemberInvite, | ||
resendWorkspaceMemberInvite: exports.resendWorkspaceMemberInvite, | ||
acceptWorkspaceMemberInvite: exports.acceptWorkspaceMemberInvite | ||
@@ -999,2 +984,4 @@ }, | ||
insertRecordWithID: exports.insertRecordWithID, | ||
updateRecordWithID: exports.updateRecordWithID, | ||
upsertRecordWithID: exports.upsertRecordWithID, | ||
deleteRecord: exports.deleteRecord, | ||
@@ -1001,0 +988,0 @@ getRecord: exports.getRecord, |
@@ -10,5 +10,6 @@ export declare type FetchImpl = (url: string, init?: { | ||
}>; | ||
export declare type WorkspaceApiUrlBuilder = (path: string, pathParams: Record<string, string>) => string; | ||
export declare type FetcherExtraProps = { | ||
apiUrl: string; | ||
workspacesApiUrl: string; | ||
workspacesApiUrl: string | WorkspaceApiUrlBuilder; | ||
fetchImpl: FetchImpl; | ||
@@ -25,2 +26,2 @@ apiKey: string; | ||
}; | ||
export declare function fetch<TData, TBody extends Record<string, unknown> | undefined, THeaders extends Record<string, unknown>, TQueryParams extends Record<string, unknown>, TPathParams extends Record<string, string>>({ url, method, body, headers, pathParams, queryParams, fetchImpl, apiKey, apiUrl, workspacesApiUrl }: FetcherOptions<TBody, THeaders, TQueryParams, TPathParams> & FetcherExtraProps): Promise<TData>; | ||
export declare function fetch<TData, TBody extends Record<string, unknown> | undefined, THeaders extends Record<string, unknown>, TQueryParams extends Record<string, unknown>, TPathParams extends Record<string, string>>({ url: path, method, body, headers, pathParams, queryParams, fetchImpl, apiKey, apiUrl, workspacesApiUrl }: FetcherOptions<TBody, THeaders, TQueryParams, TPathParams> & FetcherExtraProps): Promise<TData>; |
@@ -19,24 +19,27 @@ "use strict"; | ||
const fallbackError = { message: 'Network response was not ok' }; | ||
function baseURLForWorkspace(workspacesApiUrl, workspace) { | ||
// Node.js on localhost won't resolve localhost subdomains unless mapped in /etc/hosts | ||
// So, instead, we use localhost without subdomains, but will add a Host header | ||
if (typeof window === 'undefined' && workspacesApiUrl.includes('localhost:')) { | ||
return workspacesApiUrl.replace('{workspaceId}.', ''); | ||
} | ||
return workspacesApiUrl.replace('{workspaceId}', workspace); | ||
function buildBaseUrl({ path, workspacesApiUrl, apiUrl, pathParams }) { | ||
if (!(pathParams === null || pathParams === void 0 ? void 0 : pathParams.workspace)) | ||
return `${apiUrl}${path}`; | ||
const url = typeof workspacesApiUrl === 'string' ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams); | ||
return url.replace('{workspaceId}', pathParams.workspace); | ||
} | ||
function hostHeaderForWorkspace(workspacesApiUrl, workspace) { | ||
const url = baseURLForWorkspace(workspacesApiUrl, workspace); | ||
if (!url) | ||
return; | ||
const [, hostname] = url.split('://'); | ||
return hostname; | ||
// The host header is needed by Node.js on localhost. | ||
// It is ignored by fetch() in the frontend | ||
function hostHeader(url) { | ||
var _a; | ||
const pattern = /.*:\/\/(?<host>[^/]+).*/; | ||
const { groups } = (_a = pattern.exec(url)) !== null && _a !== void 0 ? _a : {}; | ||
return (groups === null || groups === void 0 ? void 0 : groups.host) ? { Host: groups.host } : {}; | ||
} | ||
function fetch({ url, method, body, headers, pathParams, queryParams, fetchImpl, apiKey, apiUrl, workspacesApiUrl }) { | ||
function fetch({ url: path, method, body, headers, pathParams, queryParams, fetchImpl, apiKey, apiUrl, workspacesApiUrl }) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const baseURL = (pathParams === null || pathParams === void 0 ? void 0 : pathParams.workspace) ? baseURLForWorkspace(workspacesApiUrl, pathParams.workspace) : apiUrl; | ||
const response = yield fetchImpl(`${baseURL}${resolveUrl(url, queryParams, pathParams)}`, { | ||
const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl }); | ||
const fullUrl = resolveUrl(baseUrl, queryParams, pathParams); | ||
// Node.js on localhost won't resolve localhost subdomains unless mapped in /etc/hosts | ||
// So, instead, we use localhost without subdomains, but will add a Host header | ||
const url = fullUrl.includes('localhost') ? fullUrl.replace(/^[^.]+\./, 'http://') : fullUrl; | ||
const response = yield fetchImpl(url, { | ||
method: method.toUpperCase(), | ||
body: body ? JSON.stringify(body) : undefined, | ||
headers: Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), { Authorization: `Bearer ${apiKey}` }), ((pathParams === null || pathParams === void 0 ? void 0 : pathParams.workspace) ? { Host: hostHeaderForWorkspace(workspacesApiUrl, pathParams.workspace) } : {})) | ||
headers: Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), hostHeader(fullUrl)), { Authorization: `Bearer ${apiKey}` }) | ||
}); | ||
@@ -52,6 +55,3 @@ // No content | ||
} | ||
if (jsonResponse.success) { | ||
throw withStatus(jsonResponse.data, response.status); | ||
} | ||
else if (jsonResponse.message) { | ||
if (jsonResponse.message) { | ||
throw withStatus({ message: jsonResponse.message }, response.status); | ||
@@ -58,0 +58,0 @@ } |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -6,0 +10,0 @@ if (k2 === undefined) k2 = k; |
@@ -8,3 +8,2 @@ /** | ||
export declare type APIKeyNameParam = Schemas.APIKeyName; | ||
export declare type InviteIDParam = Schemas.InviteID; | ||
export declare type InviteKeyParam = Schemas.InviteKey; | ||
@@ -11,0 +10,0 @@ export declare type UserIDParam = Schemas.UserID; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getHostUrl = void 0; | ||
const errors_1 = require("../util/errors"); | ||
function getHostUrl(provider, type) { | ||
@@ -12,3 +11,3 @@ if (isValidAlias(provider)) { | ||
} | ||
throw new Error(errors_1.errors.invalidApiProvider); | ||
throw new Error('Invalid API provider'); | ||
} | ||
@@ -15,0 +14,0 @@ exports.getHostUrl = getHostUrl; |
@@ -26,2 +26,8 @@ /** | ||
}; | ||
export declare type RecordUpdateResponse = { | ||
id: string; | ||
xata: { | ||
version: number; | ||
}; | ||
}; | ||
export declare type QueryResponse = { | ||
@@ -28,0 +34,0 @@ records: Schemas.XataRecord[]; |
@@ -133,3 +133,3 @@ /** | ||
name: string; | ||
type: 'bool' | 'int' | 'float' | 'string' | 'text' | 'email' | 'multiple' | 'link' | 'object'; | ||
type: 'bool' | 'int' | 'string' | 'text' | 'email' | 'multiple' | 'link' | 'object'; | ||
link?: { | ||
@@ -136,0 +136,0 @@ table: string; |
@@ -1,58 +0,1 @@ | ||
import { Page } from './schema/pagination'; | ||
import { Query, QueryOptions } from './schema/query'; | ||
import { Selectable, SelectableColumn, Select } from './schema/selection'; | ||
export interface XataRecord { | ||
id: string; | ||
xata: { | ||
version: number; | ||
}; | ||
read(): Promise<this>; | ||
update(data: Selectable<this>): Promise<this>; | ||
delete(): Promise<void>; | ||
} | ||
export declare abstract class Repository<T extends XataRecord> extends Query<T> { | ||
abstract create(object: Selectable<T>): Promise<T>; | ||
abstract createMany(objects: Selectable<T>[]): Promise<T[]>; | ||
abstract read(id: string): Promise<T | null>; | ||
abstract update(id: string, object: Partial<T>): Promise<T>; | ||
abstract delete(id: string): void; | ||
abstract query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>; | ||
} | ||
export declare class RestRepository<T extends XataRecord> extends Repository<T> { | ||
#private; | ||
constructor(client: BaseClient<any>, table: string); | ||
request<T>(method: string, path: string, body?: unknown): Promise<T | undefined>; | ||
create(object: T): Promise<T>; | ||
createMany(objects: T[]): Promise<T[]>; | ||
read(id: string): Promise<T | null>; | ||
update(id: string, object: Partial<T>): Promise<T>; | ||
delete(id: string): Promise<void>; | ||
query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>; | ||
} | ||
interface RepositoryFactory { | ||
createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>; | ||
} | ||
export declare class RestRespositoryFactory implements RepositoryFactory { | ||
createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>; | ||
} | ||
declare type BranchStrategyValue = string | undefined | null; | ||
declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>; | ||
declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder; | ||
declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>; | ||
export declare type XataClientOptions = { | ||
fetch?: unknown; | ||
databaseURL?: string; | ||
branch: BranchStrategyOption; | ||
apiKey: string; | ||
repositoryFactory?: RepositoryFactory; | ||
}; | ||
export declare class BaseClient<D extends Record<string, Repository<any>>> { | ||
options: XataClientOptions; | ||
private links; | ||
private branch; | ||
db: D; | ||
constructor(options: XataClientOptions, links: Links); | ||
initObject<T>(table: string, object: object): T; | ||
getBranch(): Promise<string>; | ||
} | ||
export declare class XataError extends Error { | ||
@@ -62,4 +5,3 @@ readonly status: number; | ||
} | ||
export declare type Links = Record<string, Array<string[]>>; | ||
export * from './api'; | ||
export * from './schema'; |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -12,261 +16,4 @@ if (k2 === undefined) k2 = k; | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { | ||
if (kind === "m") throw new TypeError("Private method is not writable"); | ||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); | ||
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"); | ||
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; | ||
}; | ||
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { | ||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); | ||
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"); | ||
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); | ||
}; | ||
var __asyncValues = (this && this.__asyncValues) || function (o) { | ||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); | ||
var m = o[Symbol.asyncIterator], i; | ||
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); | ||
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); }); }; } | ||
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } | ||
}; | ||
var _RestRepository_client, _RestRepository_fetch, _RestRepository_table; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.XataError = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0; | ||
const filters_1 = require("./schema/filters"); | ||
const pagination_1 = require("./schema/pagination"); | ||
const query_1 = require("./schema/query"); | ||
const errors_1 = require("./util/errors"); | ||
class Repository extends query_1.Query { | ||
} | ||
exports.Repository = Repository; | ||
class RestRepository extends Repository { | ||
constructor(client, table) { | ||
super(null, table, {}); | ||
_RestRepository_client.set(this, void 0); | ||
_RestRepository_fetch.set(this, void 0); | ||
_RestRepository_table.set(this, void 0); | ||
__classPrivateFieldSet(this, _RestRepository_client, client, "f"); | ||
__classPrivateFieldSet(this, _RestRepository_table, table, "f"); | ||
const doWeHaveFetch = typeof fetch !== 'undefined'; | ||
const isInjectedFetchProblematic = !__classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch; | ||
if (doWeHaveFetch) { | ||
__classPrivateFieldSet(this, _RestRepository_fetch, fetch, "f"); | ||
} | ||
else if (isInjectedFetchProblematic) { | ||
throw new Error(errors_1.errors.falsyFetchImplementation); | ||
} | ||
else { | ||
__classPrivateFieldSet(this, _RestRepository_fetch, __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch, "f"); | ||
} | ||
} | ||
request(method, path, body) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const { databaseURL, apiKey } = __classPrivateFieldGet(this, _RestRepository_client, "f").options; | ||
const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch(); | ||
const fetchImpl = __classPrivateFieldGet(this, _RestRepository_fetch, "f"); | ||
const resp = yield fetchImpl(`${databaseURL}:${branch}${path}`, { | ||
method, | ||
headers: { | ||
Accept: '*/*', | ||
'Content-Type': 'application/json', | ||
Authorization: `Bearer ${apiKey}` | ||
}, | ||
body: JSON.stringify(body) | ||
}); | ||
if (!resp.ok) { | ||
try { | ||
const json = yield resp.json(); | ||
const message = json.message; | ||
if (typeof message === 'string') { | ||
throw new XataError(message, resp.status); | ||
} | ||
} | ||
catch (err) { | ||
if (err instanceof XataError) | ||
throw err; | ||
// Ignore errors for other reasons. | ||
// For example if the response's body cannot be parsed as JSON | ||
} | ||
throw new XataError(resp.statusText, resp.status); | ||
} | ||
if (resp.status === 204) | ||
return undefined; | ||
return resp.json(); | ||
}); | ||
} | ||
create(object) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const record = transformObjectLinks(object); | ||
const response = yield this.request('POST', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/data`, record); | ||
if (!response) { | ||
throw new Error("The server didn't return any data for the query"); | ||
} | ||
const finalObject = yield this.read(response.id); | ||
if (!finalObject) { | ||
throw new Error('The server failed to save the record'); | ||
} | ||
return finalObject; | ||
}); | ||
} | ||
createMany(objects) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const records = objects.map((object) => transformObjectLinks(object)); | ||
const response = yield this.request('POST', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/bulk`, { records }); | ||
if (!response) { | ||
throw new Error("The server didn't return any data for the query"); | ||
} | ||
// TODO: Use filer.$any() to get all the records | ||
const finalObjects = yield Promise.all(response.recordIDs.map((id) => this.read(id))); | ||
if (finalObjects.some((object) => !object)) { | ||
throw new Error('The server failed to save the record'); | ||
} | ||
return finalObjects; | ||
}); | ||
} | ||
read(id) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const response = yield this.request('GET', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/data/${id}`); | ||
if (!response) | ||
return null; | ||
return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response); | ||
} | ||
catch (err) { | ||
if (err.status === 404) | ||
return null; | ||
throw err; | ||
} | ||
}); | ||
} | ||
update(id, object) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.request('PUT', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/data/${id}`, object); | ||
if (!response) { | ||
throw new Error("The server didn't return any data for the query"); | ||
} | ||
// TODO: Review this, not sure we are properly initializing the object | ||
return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response); | ||
}); | ||
} | ||
delete(id) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
yield this.request('DELETE', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/data/${id}`); | ||
}); | ||
} | ||
query(query, options) { | ||
var _a, _b, _c; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const data = query.getData(); | ||
const body = { | ||
filter: Object.values(data.filter).some(Boolean) ? data.filter : undefined, | ||
sort: (_a = (0, filters_1.buildSortFilter)(options === null || options === void 0 ? void 0 : options.sort)) !== null && _a !== void 0 ? _a : data.sort, | ||
page: (_b = options === null || options === void 0 ? void 0 : options.page) !== null && _b !== void 0 ? _b : data.page, | ||
columns: (_c = options === null || options === void 0 ? void 0 : options.columns) !== null && _c !== void 0 ? _c : data.columns | ||
}; | ||
const response = yield this.request('POST', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/query`, body); | ||
if (!response) { | ||
throw new Error("The server didn't return any data for the query"); | ||
} | ||
const { meta, records: objects } = response; | ||
const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record)); | ||
// TODO: We should properly type this any | ||
return new pagination_1.Page(query, meta, records); | ||
}); | ||
} | ||
} | ||
exports.RestRepository = RestRepository; | ||
_RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(); | ||
class RestRespositoryFactory { | ||
createRepository(client, table) { | ||
return new RestRepository(client, table); | ||
} | ||
} | ||
exports.RestRespositoryFactory = RestRespositoryFactory; | ||
class BaseClient { | ||
constructor(options, links) { | ||
if (!options.databaseURL || !options.apiKey || !options.branch) { | ||
throw new Error('Options databaseURL, apiKey and branch are required'); | ||
} | ||
this.options = options; | ||
this.links = links; | ||
} | ||
initObject(table, object) { | ||
const o = {}; | ||
Object.assign(o, object); | ||
const tableLinks = this.links[table] || []; | ||
for (const link of tableLinks) { | ||
const [field, linkTable] = link; | ||
const value = o[field]; | ||
if (value && typeof value === 'object') { | ||
const { id } = value; | ||
if (Object.keys(value).find((col) => col === 'id')) { | ||
o[field] = this.initObject(linkTable, value); | ||
} | ||
else if (id) { | ||
o[field] = { | ||
id, | ||
get: () => { | ||
this.db[linkTable].read(id); | ||
} | ||
}; | ||
} | ||
} | ||
} | ||
const db = this.db; | ||
o.read = function () { | ||
return db[table].read(o['id']); | ||
}; | ||
o.update = function (data) { | ||
return db[table].update(o['id'], data); | ||
}; | ||
o.delete = function () { | ||
return db[table].delete(o['id']); | ||
}; | ||
for (const prop of ['read', 'update', 'delete']) { | ||
Object.defineProperty(o, prop, { enumerable: false }); | ||
} | ||
// TODO: links and rev links | ||
Object.freeze(o); | ||
return o; | ||
} | ||
getBranch() { | ||
var e_1, _a; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (this.branch) | ||
return this.branch; | ||
const { branch: param } = this.options; | ||
const strategies = Array.isArray(param) ? [...param] : [param]; | ||
const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () { | ||
return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy; | ||
}); | ||
try { | ||
for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) { | ||
const strategy = strategies_1_1.value; | ||
const branch = yield evaluateBranch(strategy); | ||
if (branch) { | ||
this.branch = branch; | ||
return branch; | ||
} | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
throw new Error('Unable to resolve branch value'); | ||
}); | ||
} | ||
} | ||
exports.BaseClient = BaseClient; | ||
exports.XataError = void 0; | ||
class XataError extends Error { | ||
@@ -279,15 +26,3 @@ constructor(message, status) { | ||
exports.XataError = XataError; | ||
const isBranchStrategyBuilder = (strategy) => { | ||
return typeof strategy === 'function'; | ||
}; | ||
// TODO: We can find a better implementation for links | ||
const transformObjectLinks = (object) => { | ||
return Object.entries(object).reduce((acc, [key, value]) => { | ||
if (value && typeof value === 'object' && typeof value.id === 'string') { | ||
return Object.assign(Object.assign({}, acc), { [key]: value.id }); | ||
} | ||
return Object.assign(Object.assign({}, acc), { [key]: value }); | ||
}, {}); | ||
}; | ||
__exportStar(require("./api"), exports); | ||
__exportStar(require("./schema"), exports); |
export * from './operators'; | ||
export type { XataRecord } from './record'; | ||
export { Repository, RestRepository, RestRespositoryFactory, BaseClient } from './repository'; | ||
export type { XataClientOptions } from './repository'; | ||
export { Query } from './query'; |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -13,2 +17,10 @@ if (k2 === undefined) k2 = k; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Query = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0; | ||
__exportStar(require("./operators"), exports); | ||
var repository_1 = require("./repository"); | ||
Object.defineProperty(exports, "Repository", { enumerable: true, get: function () { return repository_1.Repository; } }); | ||
Object.defineProperty(exports, "RestRepository", { enumerable: true, get: function () { return repository_1.RestRepository; } }); | ||
Object.defineProperty(exports, "RestRespositoryFactory", { enumerable: true, get: function () { return repository_1.RestRespositoryFactory; } }); | ||
Object.defineProperty(exports, "BaseClient", { enumerable: true, get: function () { return repository_1.BaseClient; } }); | ||
var query_1 = require("./query"); | ||
Object.defineProperty(exports, "Query", { enumerable: true, get: function () { return query_1.Query; } }); |
@@ -9,3 +9,12 @@ import { XataRecord } from '..'; | ||
}; | ||
export declare class Page<T extends XataRecord, R extends XataRecord> { | ||
export interface Paginable<T extends XataRecord, R extends XataRecord = T> { | ||
meta: PaginationQueryMeta; | ||
records: R[]; | ||
nextPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
previousPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
firstPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
lastPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
hasNextPage(): boolean; | ||
} | ||
export declare class Page<T extends XataRecord, R extends XataRecord> implements Paginable<T, R> { | ||
#private; | ||
@@ -12,0 +21,0 @@ readonly meta: PaginationQueryMeta; |
import { XataRecord, Repository } from '..'; | ||
import { FilterExpression, SortExpression, PageConfig, ColumnsFilter } from '../api/schemas'; | ||
import { DeepConstraint, FilterConstraints, SortDirection, SortFilter } from './filters'; | ||
import { PaginationOptions, Page } from './pagination'; | ||
import { PaginationOptions, Page, Paginable, PaginationQueryMeta } from './pagination'; | ||
import { Selectable, SelectableColumn, Select } from './selection'; | ||
export declare type QueryOptions<T> = { | ||
export declare type QueryOptions<T extends XataRecord> = { | ||
page?: PaginationOptions; | ||
columns?: Array<keyof Selectable<T>>; | ||
columns?: Extract<keyof Selectable<T>, string>[]; | ||
sort?: SortFilter<T> | SortFilter<T>[]; | ||
}; | ||
export declare type FilterExpression = { | ||
$exists?: string; | ||
$existsNot?: string; | ||
$any?: FilterList; | ||
$all?: FilterList; | ||
$none?: FilterList; | ||
$not?: FilterList; | ||
} & { | ||
[key: string]: FilterColumn; | ||
}; | ||
export declare type FilterList = FilterExpression | FilterExpression[]; | ||
export declare type FilterColumn = FilterColumnIncludes | FilterPredicate | FilterList; | ||
/** | ||
* @maxProperties 1 | ||
* @minProperties 1 | ||
*/ | ||
export declare type FilterColumnIncludes = { | ||
$includes?: FilterPredicate; | ||
$includesAny?: FilterPredicate; | ||
$includesAll?: FilterPredicate; | ||
$includesNone?: FilterPredicate; | ||
}; | ||
export declare type FilterPredicate = FilterValue | FilterPredicate[] | FilterPredicateOp | FilterPredicateRangeOp; | ||
/** | ||
* @maxProperties 1 | ||
* @minProperties 1 | ||
*/ | ||
export declare type FilterPredicateOp = { | ||
$any?: FilterPredicate[]; | ||
$all?: FilterPredicate[]; | ||
$none?: FilterPredicate | FilterPredicate[]; | ||
$not?: FilterPredicate | FilterPredicate[]; | ||
$is?: FilterValue | FilterValue[]; | ||
$isNot?: FilterValue | FilterValue[]; | ||
$lt?: FilterRangeValue; | ||
$le?: FilterRangeValue; | ||
$gt?: FilterRangeValue; | ||
$ge?: FilterRangeValue; | ||
$contains?: string; | ||
$startsWith?: string; | ||
$endsWith?: string; | ||
$pattern?: string; | ||
}; | ||
export declare type FilterPredicateRangeOp = { | ||
$lt?: FilterRangeValue; | ||
$le?: FilterRangeValue; | ||
$gt?: FilterRangeValue; | ||
$ge?: FilterRangeValue; | ||
}; | ||
export declare type FilterRangeValue = number | string; | ||
export declare type FilterValue = number | string | boolean; | ||
export declare type SortExpression = string[] | { | ||
[key: string]: SortOrder; | ||
} | { | ||
[key: string]: SortOrder; | ||
}[]; | ||
export declare type SortOrder = 'asc' | 'desc'; | ||
export declare type PageConfig = { | ||
after?: string; | ||
before?: string; | ||
first?: string; | ||
last?: string; | ||
size?: number; | ||
offset?: number; | ||
}; | ||
export declare type ColumnsFilter = string[]; | ||
export declare type QueryTableData = { | ||
export declare type QueryTableOptions = { | ||
filter: FilterExpression; | ||
@@ -82,6 +17,8 @@ sort?: SortExpression; | ||
}; | ||
export declare class Query<T extends XataRecord, R extends XataRecord = T> { | ||
export declare class Query<T extends XataRecord, R extends XataRecord = T> implements Paginable<T, R> { | ||
#private; | ||
constructor(repository: Repository<T> | null, table: string, data: Partial<QueryTableData>, parent?: Partial<QueryTableData>); | ||
getData(): QueryTableData; | ||
readonly meta: PaginationQueryMeta; | ||
readonly records: R[]; | ||
constructor(repository: Repository<T> | null, table: string, data: Partial<QueryTableOptions>, parent?: Partial<QueryTableOptions>); | ||
getQueryOptions(): QueryTableOptions; | ||
any(...queries: Query<T, R>[]): Query<T, R>; | ||
@@ -92,10 +29,16 @@ all(...queries: Query<T, R>[]): Query<T, R>; | ||
filter(constraints: FilterConstraints<T>): Query<T, R>; | ||
filter<F extends keyof T>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>; | ||
filter<F extends keyof Selectable<T>>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>; | ||
sort<F extends keyof T>(column: F, direction: SortDirection): Query<T, R>; | ||
select<K extends SelectableColumn<T>>(columns: K[]): Query<T, Select<T, K>>; | ||
getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>; | ||
getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, typeof options extends { | ||
columns: SelectableColumn<T>[]; | ||
} ? Select<T, typeof options['columns'][number]> : R>>; | ||
[Symbol.asyncIterator](): AsyncIterableIterator<R>; | ||
getIterator(chunk: number, options?: Omit<QueryOptions<T>, 'page'>): AsyncGenerator<R[]>; | ||
getMany<Options extends QueryOptions<T>>(options?: Options): Promise<(typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R)[]>; | ||
getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<(typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R) | null>; | ||
getMany<Options extends QueryOptions<T>>(options?: Options): Promise<(typeof options extends { | ||
columns: SelectableColumn<T>[]; | ||
} ? Select<T, typeof options['columns'][number]> : R)[]>; | ||
getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<(typeof options extends { | ||
columns: SelectableColumn<T>[]; | ||
} ? Select<T, typeof options['columns'][number]> : R) | null>; | ||
/**async deleteAll(): Promise<number> { | ||
@@ -106,4 +49,6 @@ // TODO: Return number of affected rows | ||
nextPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
previousPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
firstPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
lastPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
hasNextPage(): boolean; | ||
} |
@@ -51,2 +51,5 @@ "use strict"; | ||
_Query_data.set(this, { filter: {} }); | ||
// Implements pagination | ||
this.meta = { page: { cursor: 'start', more: true } }; | ||
this.records = []; | ||
__classPrivateFieldSet(this, _Query_table, table, "f"); | ||
@@ -74,19 +77,19 @@ if (repository) { | ||
} | ||
getData() { | ||
getQueryOptions() { | ||
return __classPrivateFieldGet(this, _Query_data, "f"); | ||
} | ||
any(...queries) { | ||
const $any = (0, lang_1.compact)(queries.map((query) => query.getData().filter.$any)).flat(); | ||
const $any = queries.map((query) => query.getQueryOptions().filter); | ||
return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $any } }, __classPrivateFieldGet(this, _Query_data, "f")); | ||
} | ||
all(...queries) { | ||
const $all = (0, lang_1.compact)(queries.map((query) => query.getData().filter.$all)).flat(); | ||
const $all = queries.map((query) => query.getQueryOptions().filter); | ||
return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f")); | ||
} | ||
not(...queries) { | ||
const $not = (0, lang_1.compact)(queries.map((query) => query.getData().filter.$not)).flat(); | ||
const $not = queries.map((query) => query.getQueryOptions().filter); | ||
return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $not } }, __classPrivateFieldGet(this, _Query_data, "f")); | ||
} | ||
none(...queries) { | ||
const $none = (0, lang_1.compact)(queries.map((query) => query.getData().filter.$none)).flat(); | ||
const $none = queries.map((query) => query.getQueryOptions().filter); | ||
return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $none } }, __classPrivateFieldGet(this, _Query_data, "f")); | ||
@@ -115,5 +118,3 @@ } | ||
getPaginated(options = {}) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return __classPrivateFieldGet(this, _Query_repository, "f").query(this, options); | ||
}); | ||
return __classPrivateFieldGet(this, _Query_repository, "f").query(this, options); | ||
} | ||
@@ -167,17 +168,17 @@ [(_Query_table = new WeakMap(), _Query_repository = new WeakMap(), _Query_data = new WeakMap(), Symbol.asyncIterator)]() { | ||
nextPage(size, offset) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.firstPage(size, offset); | ||
}); | ||
return this.firstPage(size, offset); | ||
} | ||
previousPage(size, offset) { | ||
return this.firstPage(size, offset); | ||
} | ||
firstPage(size, offset) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.getPaginated({ page: { size, offset } }); | ||
}); | ||
return this.getPaginated({ page: { size, offset } }); | ||
} | ||
lastPage(size, offset) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.getPaginated({ page: { size, offset, before: 'end' } }); | ||
}); | ||
return this.getPaginated({ page: { size, offset, before: 'end' } }); | ||
} | ||
hasNextPage() { | ||
return this.meta.page.more; | ||
} | ||
} | ||
exports.Query = Query; |
import { XataRecord } from '..'; | ||
import { PartialBy } from '../util/lang'; | ||
import { StringKeys, UnionToIntersection, Values } from '../util/types'; | ||
@@ -7,9 +8,4 @@ import { Query } from './query'; | ||
}; | ||
declare type OmitQueries<T> = { | ||
[key in keyof T as T[key] extends Query<any> ? never : key]: T[key]; | ||
}; | ||
declare type OmitMethods<T> = { | ||
[key in keyof T as T[key] extends Function ? never : key]: T[key]; | ||
}; | ||
export declare type Selectable<T> = Omit<OmitQueries<OmitMethods<T>>, 'id' | 'xata'>; | ||
declare type InternalProperties = keyof Omit<XataRecord, 'id'>; | ||
export declare type Selectable<T extends XataRecord> = Omit<PartialBy<T, 'id'>, InternalProperties>; | ||
export declare type SelectableColumn<O> = '*' | (O extends Array<unknown> ? never : O extends Record<string, any> ? '*' | Values<{ | ||
@@ -16,0 +12,0 @@ [K in StringKeys<O>]: O[K] extends Record<string, any> ? `${K}.${SelectableColumn<O[K]>}` : K; |
export declare function compact<T>(arr: Array<T | null | undefined>): T[]; | ||
export declare type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; |
{ | ||
"name": "@xata.io/client", | ||
"version": "0.0.0-alpha.3c907b2", | ||
"version": "0.0.0-alpha.3d0997b", | ||
"description": "Xata.io SDK for TypeScript and JavaScript", | ||
@@ -23,3 +23,3 @@ "main": "./dist/index.js", | ||
"homepage": "https://github.com/xataio/client-ts/blob/main/client/README.md", | ||
"gitHead": "3c907b2b2a82d70950b5ed942b21f953859c681d" | ||
"gitHead": "3d0997bebdbadbb500bec4fede95a774431d16c4" | ||
} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
174681
41
5
4137