kinto
Version:
An Offline-First JavaScript client for Kinto.
516 lines (515 loc) • 20.3 kB
TypeScript
import HTTP, { HttpResponse } from "./http";
import endpoints from "./endpoints";
import { AggregateResponse } from "./batch";
import Bucket from "./bucket";
import { HelloResponse, KintoRequest, OperationResponse, Permission, KintoIdObject, MappableObject, KintoObject, PermissionData, KintoResponse, ServerSettings, ServerCapability, User, Emitter, HttpMethod, FetchFunction } from "../types";
import Collection from "./collection";
/**
* Currently supported protocol version.
* @type {String}
*/
export declare const SUPPORTED_PROTOCOL_VERSION = "v1";
export interface KintoClientOptions {
safe?: boolean;
events?: Emitter;
headers?: Record<string, string>;
retry?: number;
bucket?: string;
requestMode?: RequestMode;
timeout?: number;
batch?: boolean;
fetchFunc?: FetchFunction;
}
export interface PaginatedParams {
sort?: string;
filters?: Record<string, string | number>;
limit?: number;
pages?: number;
since?: string;
fields?: string[];
}
export interface PaginationResult<T> {
last_modified: string | null;
data: T[];
next: (nextPage?: string | null) => Promise<PaginationResult<T>>;
hasNextPage: boolean;
totalRecords: number;
}
type BaseBatch = (client: KintoClientBase) => void;
type BucketBatch = (client: Bucket) => void;
type CollectionBatch = (client: Collection) => void;
/**
* High level HTTP client for the Kinto API.
*
* @example
* const client = new KintoClient("https://demo.kinto-storage.org/v1");
* client.bucket("default")
* .collection("my-blog")
* .createRecord({title: "First article"})
* .then(console.log.bind(console))
* .catch(console.error.bind(console));
*/
export default class KintoClientBase {
private _backoffReleaseTime;
private _requests;
private _isBatch;
private _retry;
private _safe;
private _headers;
serverInfo: HelloResponse | null;
events?: Emitter;
http: HTTP;
endpoints: typeof endpoints;
private _remote;
private _version;
/**
* Constructor.
*
* @param {String} remote The remote URL.
* @param {Object} [options={}] The options object.
* @param {Boolean} [options.safe=true] Adds concurrency headers to every requests.
* @param {EventEmitter} [options.events=EventEmitter] The events handler instance.
* @param {Object} [options.headers={}] The key-value headers to pass to each request.
* @param {Object} [options.retry=0] Number of retries when request fails (default: 0)
* @param {String} [options.bucket="default"] The default bucket to use.
* @param {String} [options.requestMode="cors"] The HTTP request mode (from ES6 fetch spec).
* @param {Number} [options.timeout=null] The request timeout in ms, if any.
* @param {Function} [options.fetchFunc=fetch] The function to be used to execute HTTP requests.
*/
constructor(remote: string, options: KintoClientOptions);
/**
* The remote endpoint base URL. Setting the value will also extract and
* validate the version.
* @type {String}
*/
get remote(): string;
/**
* @ignore
*/
set remote(url: string);
/**
* The current server protocol version, eg. `v1`.
* @type {String}
*/
get version(): string;
/**
* Backoff remaining time, in milliseconds. Defaults to zero if no backoff is
* ongoing.
*
* @type {Number}
*/
get backoff(): number;
/**
* Registers HTTP events.
* @private
*/
private _registerHTTPEvents;
/**
* Retrieve a bucket object to perform operations on it.
*
* @param {String} name The bucket name.
* @param {Object} [options={}] The request options.
* @param {Boolean} [options.safe] The resulting safe option.
* @param {Number} [options.retry] The resulting retry option.
* @param {Object} [options.headers] The extended headers object option.
* @return {Bucket}
*/
bucket(name: string, options?: {
safe?: boolean;
retry?: number;
headers?: Record<string, string>;
}): Bucket;
/**
* Set client "headers" for every request, updating previous headers (if any).
*
* @param {Object} headers The headers to merge with existing ones.
*/
setHeaders(headers: Record<string, string>): void;
/**
* Get the value of "headers" for a given request, merging the
* per-request headers with our own "default" headers.
*
* Note that unlike other options, headers aren't overridden, but
* merged instead.
*
* @private
* @param {Object} options The options for a request.
* @returns {Object}
*/
private _getHeaders;
/**
* Get the value of "safe" for a given request, using the
* per-request option if present or falling back to our default
* otherwise.
*
* @private
* @param {Object} options The options for a request.
* @returns {Boolean}
*/
private _getSafe;
/**
* As _getSafe, but for "retry".
*
* @private
*/
private _getRetry;
/**
* Retrieves the server's "hello" endpoint. This endpoint reveals
* server capabilities and settings as well as telling the client
* "who they are" according to their given authorization headers.
*
* @private
* @param {Object} [options={}] The request options.
* @param {Object} [options.headers={}] Headers to use when making
* this request.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Object, Error>}
*/
private _getHello;
/**
* Retrieves server information and persist them locally. This operation is
* usually performed a single time during the instance lifecycle.
*
* @param {Object} [options={}] The request options.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Object, Error>}
*/
fetchServerInfo(options?: {
retry?: number;
}): Promise<HelloResponse>;
/**
* Retrieves Kinto server settings.
*
* @param {Object} [options={}] The request options.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Object, Error>}
*/
fetchServerSettings(options?: {
retry?: number;
}): Promise<ServerSettings>;
/**
* Retrieve server capabilities information.
*
* @param {Object} [options={}] The request options.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Object, Error>}
*/
fetchServerCapabilities(options?: {
retry?: number;
}): Promise<{
[key: string]: ServerCapability;
}>;
/**
* Retrieve authenticated user information.
*
* @param {Object} [options={}] The request options.
* @param {Object} [options.headers={}] Headers to use when making
* this request.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Object, Error>}
*/
fetchUser(options?: {
retry?: number;
headers?: Record<string, string>;
}): Promise<User | undefined>;
/**
* Retrieve authenticated user information.
*
* @param {Object} [options={}] The request options.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Object, Error>}
*/
fetchHTTPApiVersion(options?: {
retry?: number;
}): Promise<string>;
/**
* Process batch requests, chunking them according to the batch_max_requests
* server setting when needed.
*
* @param {Array} requests The list of batch subrequests to perform.
* @param {Object} [options={}] The options object.
* @return {Promise<Object, Error>}
*/
private _batchRequests;
/**
* Sends batch requests to the remote server.
*
* Note: Reserved for internal use only.
*
* @ignore
* @param {Function} fn The function to use for describing batch ops.
* @param {Object} [options={}] The options object.
* @param {Boolean} [options.safe] The safe option.
* @param {Number} [options.retry] The retry option.
* @param {String} [options.bucket] The bucket name option.
* @param {String} [options.collection] The collection name option.
* @param {Object} [options.headers] The headers object option.
* @param {Boolean} [options.aggregate=false] Produces an aggregated result object.
* @return {Promise<Object, Error>}
*/
batch(fn: BaseBatch | BucketBatch | CollectionBatch, options?: {
safe?: boolean;
retry?: number;
bucket?: string;
collection?: string;
headers?: Record<string, string>;
aggregate?: boolean;
}): Promise<OperationResponse<KintoObject>[] | AggregateResponse>;
/**
* Executes an atomic HTTP request.
*
* @param {Object} request The request object.
* @param {String} request.path The path to fetch, relative
* to the Kinto server root.
* @param {String} [request.method="GET"] The method to use in the
* request.
* @param {Body} [request.body] The request body.
* @param {Object} [request.headers={}] The request headers.
* @param {Object} [options={}] The options object.
* @param {Boolean} [options.raw=false] If true, resolve with full response
* @param {Boolean} [options.stringify=true] If true, serialize body data to
* @param {Number} [options.retry=0] The number of times to
* retry a request if the server responds with Retry-After.
* JSON.
* @return {Promise<Object, Error>}
*/
execute<T>(request: KintoRequest, options: {
raw: true;
stringify?: boolean;
retry?: number;
query?: {
[key: string]: string;
};
fields?: string[];
}): Promise<HttpResponse<T>>;
execute<T>(request: KintoRequest, options?: {
raw?: false;
stringify?: boolean;
retry?: number;
query?: {
[key: string]: string;
};
fields?: string[];
}): Promise<T>;
/**
* Perform an operation with a given HTTP method on some pages from
* a paginated list, following the `next-page` header automatically
* until we have processed the requested number of pages. Return a
* response with a `.next()` method that can be called to perform
* the requested HTTP method on more results.
*
* @private
* @param {String} path
* The path to make the request to.
* @param {Object} params
* The parameters to use when making the request.
* @param {String} [params.sort="-last_modified"]
* The sorting order to use when doing operation on pages.
* @param {Object} [params.filters={}]
* The filters to send in the request.
* @param {Number} [params.limit=undefined]
* The limit to send in the request. Undefined means no limit.
* @param {Number} [params.pages=undefined]
* The number of pages to operate on. Undefined means one page. Pass
* Infinity to operate on everything.
* @param {String} [params.since=undefined]
* The ETag from which to start doing operation on pages.
* @param {Array} [params.fields]
* Limit response to just some fields.
* @param {Object} [options={}]
* Additional request-level parameters to use in all requests.
* @param {Object} [options.headers={}]
* Headers to use during all requests.
* @param {Number} [options.retry=0]
* Number of times to retry each request if the server responds
* with Retry-After.
* @param {String} [options.method="GET"]
* The method to use in the request.
*/
paginatedOperation<T>(path: string, params?: PaginatedParams, options?: {
headers?: Record<string, string>;
retry?: number;
method?: HttpMethod;
}): Promise<PaginationResult<T>>;
/**
* Fetch some pages from a paginated list, following the `next-page`
* header automatically until we have fetched the requested number
* of pages. Return a response with a `.next()` method that can be
* called to fetch more results.
*
* @private
* @param {String} path
* The path to make the request to.
* @param {Object} params
* The parameters to use when making the request.
* @param {String} [params.sort="-last_modified"]
* The sorting order to use when fetching.
* @param {Object} [params.filters={}]
* The filters to send in the request.
* @param {Number} [params.limit=undefined]
* The limit to send in the request. Undefined means no limit.
* @param {Number} [params.pages=undefined]
* The number of pages to fetch. Undefined means one page. Pass
* Infinity to fetch everything.
* @param {String} [params.since=undefined]
* The ETag from which to start fetching.
* @param {Array} [params.fields]
* Limit response to just some fields.
* @param {Object} [options={}]
* Additional request-level parameters to use in all requests.
* @param {Object} [options.headers={}]
* Headers to use during all requests.
* @param {Number} [options.retry=0]
* Number of times to retry each request if the server responds
* with Retry-After.
*/
paginatedList<T>(path: string, params?: PaginatedParams, options?: {
headers?: Record<string, string>;
retry?: number;
}): Promise<PaginationResult<T>>;
/**
* Delete multiple objects, following the pagination if the number of
* objects exceeds the page limit until we have deleted the requested
* number of pages. Return a response with a `.next()` method that can
* be called to delete more results.
*
* @private
* @param {String} path
* The path to make the request to.
* @param {Object} params
* The parameters to use when making the request.
* @param {String} [params.sort="-last_modified"]
* The sorting order to use when deleting.
* @param {Object} [params.filters={}]
* The filters to send in the request.
* @param {Number} [params.limit=undefined]
* The limit to send in the request. Undefined means no limit.
* @param {Number} [params.pages=undefined]
* The number of pages to delete. Undefined means one page. Pass
* Infinity to delete everything.
* @param {String} [params.since=undefined]
* The ETag from which to start deleting.
* @param {Array} [params.fields]
* Limit response to just some fields.
* @param {Object} [options={}]
* Additional request-level parameters to use in all requests.
* @param {Object} [options.headers={}]
* Headers to use during all requests.
* @param {Number} [options.retry=0]
* Number of times to retry each request if the server responds
* with Retry-After.
*/
paginatedDelete<T>(path: string, params?: PaginatedParams, options?: {
headers?: Record<string, string>;
retry?: number;
safe?: boolean;
last_modified?: number;
}): Promise<PaginationResult<T>>;
/**
* Lists all permissions.
*
* @param {Object} [options={}] The options object.
* @param {Object} [options.headers={}] Headers to use when making
* this request.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Object[], Error>}
*/
listPermissions(options?: PaginatedParams & {
retry?: number;
headers?: Record<string, string>;
}): Promise<PaginationResult<PermissionData>>;
/**
* Retrieves the list of buckets.
*
* @param {Object} [options={}] The options object.
* @param {Object} [options.headers={}] Headers to use when making
* this request.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @param {Object} [options.filters={}] The filters object.
* @param {Array} [options.fields] Limit response to
* just some fields.
* @return {Promise<Object[], Error>}
*/
listBuckets(options?: PaginatedParams & {
retry?: number;
headers?: Record<string, string>;
filters?: Record<string, string | number>;
fields?: string[];
since?: string;
}): Promise<PaginationResult<KintoObject>>;
/**
* Creates a new bucket on the server.
*
* @param {String|null} id The bucket name (optional).
* @param {Object} [options={}] The options object.
* @param {Boolean} [options.data] The bucket data option.
* @param {Boolean} [options.safe] The safe option.
* @param {Object} [options.headers] The headers object option.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Object, Error>}
*/
createBucket<T extends MappableObject>(id: string | null, options?: {
data?: T & {
id?: string;
};
permissions?: Partial<Record<Permission, string[]>>;
safe?: boolean;
headers?: Record<string, string>;
retry?: number;
}): Promise<KintoResponse<T>>;
/**
* Deletes a bucket from the server.
*
* @ignore
* @param {Object|String} bucket The bucket to delete.
* @param {Object} [options={}] The options object.
* @param {Boolean} [options.safe] The safe option.
* @param {Object} [options.headers] The headers object option.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @param {Number} [options.last_modified] The last_modified option.
* @return {Promise<Object, Error>}
*/
deleteBucket(bucket: string | KintoIdObject, options?: {
safe?: boolean;
headers?: Record<string, string>;
retry?: number;
last_modified?: number;
}): Promise<KintoResponse<{
deleted: boolean;
}>>;
/**
* Deletes buckets.
*
* @param {Object} [options={}] The options object.
* @param {Boolean} [options.safe] The safe option.
* @param {Object} [options.headers={}] Headers to use when making
* this request.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @param {Object} [options.filters={}] The filters object.
* @param {Array} [options.fields] Limit response to
* just some fields.
* @param {Number} [options.last_modified] The last_modified option.
* @return {Promise<Object[], Error>}
*/
deleteBuckets(options?: PaginatedParams & {
safe?: boolean;
retry?: number;
headers?: Record<string, string>;
last_modified?: number;
}): Promise<PaginationResult<KintoObject>>;
createAccount(username: string, password: string): Promise<KintoResponse<{
password: string;
}>>;
}
export {};