diff --git a/src/administration.ts b/src/administration.ts index 6009e8fe..26298982 100644 --- a/src/administration.ts +++ b/src/administration.ts @@ -58,7 +58,7 @@ export type EngineInfo = { * Index type aliases supported by the storage engine. */ indexes?: Record; - } + }; }; }; @@ -127,7 +127,7 @@ export type ServerStatusInformation = { */ foxxApi: boolean; /** - * A host identifier defined by the HOST or NODE_NAME environment variable, + * A host identifier defined by the HOST or NODE_NAME environment variable, * or a fallback value using a machine identifier or the cluster/Agency address. */ host: string; @@ -318,7 +318,7 @@ export type ClusterSupportInfo = { * Number of servers in the cluster. */ servers: number; - } + }; }; /** * (Cluster only.) Information about the ArangoDB instance as well as the @@ -347,4 +347,4 @@ export interface QueueTimeMetrics { * in seconds. */ getAvg(): number; -}; +} diff --git a/src/analyzers.ts b/src/analyzers.ts index 8d7dc17f..05a5f31a 100644 --- a/src/analyzers.ts +++ b/src/analyzers.ts @@ -77,43 +77,42 @@ export type CreateAnalyzerOptions = type CreateAnalyzerOptionsType< Type extends AnalyzerType, - Properties = void + Properties = void, > = Properties extends void ? { - /** - * Type of the Analyzer. - */ - type: Type; - /** - * Features to enable for this Analyzer. - */ - features?: AnalyzerFeature[]; - /** - * This Analyzer does not take additional properties. - */ - properties?: Record; - } + /** + * Type of the Analyzer. + */ + type: Type; + /** + * Features to enable for this Analyzer. + */ + features?: AnalyzerFeature[]; + /** + * This Analyzer does not take additional properties. + */ + properties?: Record; + } : { - /** - * Type of the Analyzer. - */ - type: Type; - /** - * Features to enable for this Analyzer. - */ - features?: AnalyzerFeature[]; - /** - * Additional properties for the Analyzer. - */ - properties: Properties; - }; + /** + * Type of the Analyzer. + */ + type: Type; + /** + * Features to enable for this Analyzer. + */ + features?: AnalyzerFeature[]; + /** + * Additional properties for the Analyzer. + */ + properties: Properties; + }; /** * Options for creating an Identity Analyzer. */ -export type CreateIdentityAnalyzerOptions = CreateAnalyzerOptionsType< - "identity" ->; +export type CreateIdentityAnalyzerOptions = + CreateAnalyzerOptionsType<"identity">; /** * Options for creating a Delimiter Analyzer. @@ -122,12 +121,12 @@ export type CreateDelimiterAnalyzerOptions = CreateAnalyzerOptionsType< "delimiter", | string | { - /** - * This value will be used as delimiter to split text into tokens as - * specified in RFC 4180, without starting new records on newlines. - */ - delimiter: string; - } + /** + * This value will be used as delimiter to split text into tokens as + * specified in RFC 4180, without starting new records on newlines. + */ + delimiter: string; + } >; /** @@ -583,7 +582,7 @@ export type AnalyzerDescription = */ type AnalyzerDescriptionType< Type extends string, - Properties = Record + Properties = Record, > = { /** * A unique name for this Analyzer. @@ -932,43 +931,43 @@ export class Analyzer { * ``` */ create( - options: Options + options: Options, ): Promise< Options extends CreateIdentityAnalyzerOptions - ? IdentityAnalyzerDescription - : Options extends CreateDelimiterAnalyzerOptions - ? DelimiterAnalyzerDescription - : Options extends CreateStemAnalyzerOptions - ? StemAnalyzerDescription - : Options extends CreateNormAnalyzerOptions - ? NormAnalyzerDescription - : Options extends CreateNgramAnalyzerOptions - ? NgramAnalyzerDescription - : Options extends CreateTextAnalyzerOptions - ? TextAnalyzerDescription - : Options extends CreateSegmentationAnalyzerOptions - ? SegmentationAnalyzerDescription - : Options extends CreateAqlAnalyzerOptions - ? AqlAnalyzerDescription - : Options extends CreatePipelineAnalyzerOptions - ? PipelineAnalyzerDescription - : Options extends CreateStopwordsAnalyzerOptions - ? StopwordsAnalyzerDescription - : Options extends CreateCollationAnalyzerOptions - ? CollationAnalyzerDescription - : Options extends CreateMinHashAnalyzerOptions - ? MinHashAnalyzerDescription - : Options extends CreateClassificationAnalyzerOptions - ? ClassificationAnalyzerDescription - : Options extends CreateNearestNeighborsAnalyzerOptions - ? NearestNeighborsAnalyzerDescription - : Options extends CreateGeoJsonAnalyzerOptions - ? GeoJsonAnalyzerDescription - : Options extends CreateGeoPointAnalyzerOptions - ? GeoPointAnalyzerDescription - : Options extends CreateGeoS2AnalyzerOptions - ? GeoS2AnalyzerDescription - : AnalyzerDescription + ? IdentityAnalyzerDescription + : Options extends CreateDelimiterAnalyzerOptions + ? DelimiterAnalyzerDescription + : Options extends CreateStemAnalyzerOptions + ? StemAnalyzerDescription + : Options extends CreateNormAnalyzerOptions + ? NormAnalyzerDescription + : Options extends CreateNgramAnalyzerOptions + ? NgramAnalyzerDescription + : Options extends CreateTextAnalyzerOptions + ? TextAnalyzerDescription + : Options extends CreateSegmentationAnalyzerOptions + ? SegmentationAnalyzerDescription + : Options extends CreateAqlAnalyzerOptions + ? AqlAnalyzerDescription + : Options extends CreatePipelineAnalyzerOptions + ? PipelineAnalyzerDescription + : Options extends CreateStopwordsAnalyzerOptions + ? StopwordsAnalyzerDescription + : Options extends CreateCollationAnalyzerOptions + ? CollationAnalyzerDescription + : Options extends CreateMinHashAnalyzerOptions + ? MinHashAnalyzerDescription + : Options extends CreateClassificationAnalyzerOptions + ? ClassificationAnalyzerDescription + : Options extends CreateNearestNeighborsAnalyzerOptions + ? NearestNeighborsAnalyzerDescription + : Options extends CreateGeoJsonAnalyzerOptions + ? GeoJsonAnalyzerDescription + : Options extends CreateGeoPointAnalyzerOptions + ? GeoPointAnalyzerDescription + : Options extends CreateGeoS2AnalyzerOptions + ? GeoS2AnalyzerDescription + : AnalyzerDescription > { return this._db.request({ method: "POST", @@ -991,7 +990,9 @@ export class Analyzer { * // the Analyzer "some-analyzer" no longer exists * ``` */ - drop(force: boolean = false): Promise> { + drop( + force: boolean = false, + ): Promise> { return this._db.request({ method: "DELETE", pathname: `/_api/analyzer/${encodeURIComponent(this._name)}`, @@ -999,4 +1000,4 @@ export class Analyzer { }); } } -//#endregion \ No newline at end of file +//#endregion diff --git a/src/aql.ts b/src/aql.ts index a45ae84c..5229ce3e 100644 --- a/src/aql.ts +++ b/src/aql.ts @@ -224,7 +224,7 @@ export function aql( 2, strings[i] + src.strings[0], ...src.strings.slice(1, src.args.length), - src.strings[src.args.length] + strings[i + 1] + src.strings[src.args.length] + strings[i + 1], ); } else { query += rawValue.query + strings[i + 1]; @@ -319,7 +319,7 @@ export function aql( * ``` */ export function literal( - value: string | number | boolean | AqlLiteral | null | undefined + value: string | number | boolean | AqlLiteral | null | undefined, ): AqlLiteral { if (isAqlLiteral(value)) { return value; diff --git a/src/collections.ts b/src/collections.ts index f8818046..38929f21 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -26,7 +26,7 @@ import { COLLECTION_NOT_FOUND, DOCUMENT_NOT_FOUND } from "./lib/codes.js"; * @param collection - A value that might be a collection. */ export function isArangoCollection( - collection: any + collection: any, ): collection is ArangoCollection { return Boolean(collection && collection.isArangoCollection); } @@ -38,7 +38,7 @@ export function isArangoCollection( * @param collection - Collection name or {@link ArangoCollection} object. */ export function collectionToString( - collection: string | ArangoCollection + collection: string | ArangoCollection, ): string { if (isArangoCollection(collection)) { return String(collection.name); @@ -663,8 +663,10 @@ export interface DocumentCollection< create( options?: CreateCollectionOptions & { type?: CollectionType; - } - ): Promise>; + }, + ): Promise< + connection.ArangoApiResponse + >; /** * Retrieves the collection's properties. * @@ -692,8 +694,10 @@ export interface DocumentCollection< * ``` */ properties( - properties: CollectionPropertiesOptions - ): Promise>; + properties: CollectionPropertiesOptions, + ): Promise< + connection.ArangoApiResponse + >; /** * Retrieves information about the number of documents in a collection. * @@ -741,11 +745,11 @@ export interface DocumentCollection< * ``` */ figures( - details?: boolean + details?: boolean, ): Promise< connection.ArangoApiResponse< CollectionDescription & - CollectionProperties & { count: number; figures: Record } + CollectionProperties & { count: number; figures: Record } > >; /** @@ -778,7 +782,7 @@ export interface DocumentCollection< * ``` */ checksum( - options?: CollectionChecksumOptions + options?: CollectionChecksumOptions, ): Promise< connection.ArangoApiResponse< CollectionDescription & { revision: string; checksum: string } @@ -806,7 +810,9 @@ export interface DocumentCollection< * // collection1 and collection3 represent the same ArangoDB collection! * ``` */ - rename(newName: string): Promise>; + rename( + newName: string, + ): Promise>; /** * Deletes all documents in the collection. * @@ -819,7 +825,9 @@ export interface DocumentCollection< * // the collection "some-collection" is now empty * ``` */ - truncate(options?: TruncateCollectionOptions): Promise>; + truncate( + options?: TruncateCollectionOptions, + ): Promise>; /** * Deletes the collection from the database. * @@ -834,7 +842,7 @@ export interface DocumentCollection< * ``` */ drop( - options?: DropCollectionOptions + options?: DropCollectionOptions, ): Promise>; /** * Triggers compaction for a collection. @@ -864,7 +872,7 @@ export interface DocumentCollection< * ``` */ getResponsibleShard( - document: Partial> + document: Partial>, ): Promise; /** * Derives a document `_id` from the given selector for this collection. @@ -922,7 +930,7 @@ export interface DocumentCollection< */ documentExists( selector: documents.DocumentSelector, - options?: documents.DocumentExistsOptions + options?: documents.DocumentExistsOptions, ): Promise; /** * Retrieves the document matching the given key or id. @@ -960,7 +968,7 @@ export interface DocumentCollection< */ document( selector: documents.DocumentSelector, - options?: documents.ReadDocumentOptions + options?: documents.ReadDocumentOptions, ): Promise>; /** * Retrieves the document matching the given key or id. @@ -999,7 +1007,7 @@ export interface DocumentCollection< */ document( selector: documents.DocumentSelector, - graceful: boolean + graceful: boolean, ): Promise>; /** * Retrieves the documents matching the given key or id values. @@ -1025,7 +1033,7 @@ export interface DocumentCollection< */ documents( selectors: (string | documents.ObjectWithDocumentKey)[], - options?: documents.BulkReadDocumentsOptions + options?: documents.BulkReadDocumentsOptions, ): Promise[]>; /** * Inserts a new document with the given `data` into the collection. @@ -1046,7 +1054,7 @@ export interface DocumentCollection< */ save( data: documents.DocumentData, - options?: documents.InsertDocumentOptions + options?: documents.InsertDocumentOptions, ): Promise< documents.DocumentOperationMetadata & { new?: documents.Document; @@ -1076,13 +1084,13 @@ export interface DocumentCollection< */ saveAll( data: Array>, - options?: documents.InsertDocumentOptions + options?: documents.InsertDocumentOptions, ): Promise< Array< | (documents.DocumentOperationMetadata & { - new?: documents.Document; - old?: documents.Document; - }) + new?: documents.Document; + old?: documents.Document; + }) | documents.DocumentOperationFailure > >; @@ -1113,7 +1121,7 @@ export interface DocumentCollection< replace( selector: documents.DocumentSelector, newData: documents.DocumentData, - options?: documents.ReplaceDocumentOptions + options?: documents.ReplaceDocumentOptions, ): Promise< documents.DocumentOperationMetadata & { new?: documents.Document; @@ -1146,15 +1154,16 @@ export interface DocumentCollection< */ replaceAll( newData: Array< - documents.DocumentData & ({ _key: string } | { _id: string }) + documents.DocumentData & + ({ _key: string } | { _id: string }) >, - options?: Omit + options?: Omit, ): Promise< Array< | (documents.DocumentOperationMetadata & { - new?: documents.Document; - old?: documents.Document; - }) + new?: documents.Document; + old?: documents.Document; + }) | documents.DocumentOperationFailure > >; @@ -1185,7 +1194,7 @@ export interface DocumentCollection< update( selector: documents.DocumentSelector, newData: documents.Patch>, - options?: documents.UpdateDocumentOptions + options?: documents.UpdateDocumentOptions, ): Promise< documents.DocumentOperationMetadata & { new?: documents.Document; @@ -1218,15 +1227,16 @@ export interface DocumentCollection< */ updateAll( newData: Array< - documents.Patch> & ({ _key: string } | { _id: string }) + documents.Patch> & + ({ _key: string } | { _id: string }) >, - options?: Omit + options?: Omit, ): Promise< Array< | (documents.DocumentOperationMetadata & { - new?: documents.Document; - old?: documents.Document; - }) + new?: documents.Document; + old?: documents.Document; + }) | documents.DocumentOperationFailure > >; @@ -1259,8 +1269,10 @@ export interface DocumentCollection< */ remove( selector: documents.DocumentSelector, - options?: documents.RemoveDocumentOptions - ): Promise }>; + options?: documents.RemoveDocumentOptions, + ): Promise< + documents.DocumentMetadata & { old?: documents.Document } + >; /** * Removes existing documents from the collection. * @@ -1281,10 +1293,12 @@ export interface DocumentCollection< */ removeAll( selectors: (string | documents.ObjectWithDocumentKey)[], - options?: Omit + options?: Omit, ): Promise< Array< - | (documents.DocumentMetadata & { old?: documents.Document }) + | (documents.DocumentMetadata & { + old?: documents.Document; + }) | documents.DocumentOperationFailure > >; @@ -1309,7 +1323,7 @@ export interface DocumentCollection< */ import( data: documents.DocumentData[], - options?: documents.ImportDocumentsOptions + options?: documents.ImportDocumentsOptions, ): Promise; /** * Bulk imports the given `data` into the collection. @@ -1335,7 +1349,7 @@ export interface DocumentCollection< */ import( data: any[][], - options?: documents.ImportDocumentsOptions + options?: documents.ImportDocumentsOptions, ): Promise; /** * Bulk imports the given `data` into the collection. @@ -1397,7 +1411,7 @@ export interface DocumentCollection< data: Buffer | Blob | string, options?: documents.ImportDocumentsOptions & { type?: "documents" | "list" | "auto"; - } + }, ): Promise; //#endregion @@ -1436,8 +1450,12 @@ export interface DocumentCollection< * }); * ``` */ - indexes( - options?: indexes.ListIndexesOptions + indexes< + IndexType extends + | indexes.IndexDescription + | indexes.HiddenIndexDescription = indexes.IndexDescription, + >( + options?: indexes.ListIndexesOptions, ): Promise; /** * Returns an index description by name or `id` if it exists. @@ -1471,8 +1489,12 @@ export interface DocumentCollection< * ``` */ ensureIndex( - options: indexes.EnsurePersistentIndexOptions - ): Promise>; + options: indexes.EnsurePersistentIndexOptions, + ): Promise< + connection.ArangoApiResponse< + indexes.PersistentIndexDescription & { isNewlyCreated: boolean } + > + >; /** * Creates a TTL index on the collection if it does not already exist. * @@ -1503,8 +1525,12 @@ export interface DocumentCollection< * ``` */ ensureIndex( - options: indexes.EnsureTtlIndexOptions - ): Promise>; + options: indexes.EnsureTtlIndexOptions, + ): Promise< + connection.ArangoApiResponse< + indexes.TtlIndexDescription & { isNewlyCreated: boolean } + > + >; /** * Creates a multi-dimensional index on the collection if it does not already exist. * @@ -1524,8 +1550,12 @@ export interface DocumentCollection< * ``` */ ensureIndex( - options: indexes.EnsureMdiIndexOptions - ): Promise>; + options: indexes.EnsureMdiIndexOptions, + ): Promise< + connection.ArangoApiResponse< + indexes.MdiIndexDescription & { isNewlyCreated: boolean } + > + >; /** * Creates a geo index on the collection if it does not already exist. * @@ -1544,8 +1574,12 @@ export interface DocumentCollection< * ``` */ ensureIndex( - options: indexes.EnsureGeoIndexOptions - ): Promise>; + options: indexes.EnsureGeoIndexOptions, + ): Promise< + connection.ArangoApiResponse< + indexes.GeoIndexDescription & { isNewlyCreated: boolean } + > + >; /** * Creates a inverted index on the collection if it does not already exist. * @@ -1563,8 +1597,12 @@ export interface DocumentCollection< * ``` */ ensureIndex( - options: indexes.EnsureInvertedIndexOptions - ): Promise>; + options: indexes.EnsureInvertedIndexOptions, + ): Promise< + connection.ArangoApiResponse< + indexes.InvertedIndexDescription & { isNewlyCreated: boolean } + > + >; /** * Creates an index on the collection if it does not already exist. * @@ -1584,8 +1622,12 @@ export interface DocumentCollection< * ``` */ ensureIndex( - options: indexes.EnsureIndexOptions - ): Promise>; + options: indexes.EnsureIndexOptions, + ): Promise< + connection.ArangoApiResponse< + indexes.IndexDescription & { isNewlyCreated: boolean } + > + >; /** * Deletes the index with the given name or `id` from the database. * @@ -1600,7 +1642,7 @@ export interface DocumentCollection< * ``` */ dropIndex( - selector: indexes.IndexSelector + selector: indexes.IndexSelector, ): Promise>; //#endregion } @@ -1675,7 +1717,7 @@ export interface EdgeCollection< */ document( selector: documents.DocumentSelector, - options?: documents.ReadDocumentOptions + options?: documents.ReadDocumentOptions, ): Promise>; /** * Retrieves the document matching the given key or id. @@ -1714,7 +1756,7 @@ export interface EdgeCollection< */ document( selector: documents.DocumentSelector, - graceful: boolean + graceful: boolean, ): Promise>; /** * Retrieves the documents matching the given key or id values. @@ -1740,7 +1782,7 @@ export interface EdgeCollection< */ documents( selectors: (string | documents.ObjectWithDocumentKey)[], - options?: documents.BulkReadDocumentsOptions + options?: documents.BulkReadDocumentsOptions, ): Promise[]>; /** * Inserts a new document with the given `data` into the collection. @@ -1760,7 +1802,7 @@ export interface EdgeCollection< */ save( data: documents.EdgeData, - options?: documents.InsertDocumentOptions + options?: documents.InsertDocumentOptions, ): Promise< documents.DocumentOperationMetadata & { new?: documents.Edge; @@ -1788,13 +1830,13 @@ export interface EdgeCollection< */ saveAll( data: Array>, - options?: documents.InsertDocumentOptions + options?: documents.InsertDocumentOptions, ): Promise< Array< | (documents.DocumentOperationMetadata & { - new?: documents.Edge; - old?: documents.Edge; - }) + new?: documents.Edge; + old?: documents.Edge; + }) | documents.DocumentOperationFailure > >; @@ -1833,7 +1875,7 @@ export interface EdgeCollection< replace( selector: documents.DocumentSelector, newData: documents.DocumentData, - options?: documents.ReplaceDocumentOptions + options?: documents.ReplaceDocumentOptions, ): Promise< documents.DocumentOperationMetadata & { new?: documents.Edge; @@ -1882,15 +1924,16 @@ export interface EdgeCollection< */ replaceAll( newData: Array< - documents.DocumentData & ({ _key: string } | { _id: string }) + documents.DocumentData & + ({ _key: string } | { _id: string }) >, - options?: documents.ReplaceDocumentOptions + options?: documents.ReplaceDocumentOptions, ): Promise< Array< | (documents.DocumentOperationMetadata & { - new?: documents.Edge; - old?: documents.Edge; - }) + new?: documents.Edge; + old?: documents.Edge; + }) | documents.DocumentOperationFailure > >; @@ -1929,7 +1972,7 @@ export interface EdgeCollection< update( selector: documents.DocumentSelector, newData: documents.Patch>, - options?: documents.UpdateDocumentOptions + options?: documents.UpdateDocumentOptions, ): Promise< documents.DocumentOperationMetadata & { new?: documents.Edge; @@ -1976,15 +2019,16 @@ export interface EdgeCollection< */ updateAll( newData: Array< - documents.Patch> & ({ _key: string } | { _id: string }) + documents.Patch> & + ({ _key: string } | { _id: string }) >, - options?: documents.UpdateDocumentOptions + options?: documents.UpdateDocumentOptions, ): Promise< Array< | (documents.DocumentOperationMetadata & { - new?: documents.Edge; - old?: documents.Edge; - }) + new?: documents.Edge; + old?: documents.Edge; + }) | documents.DocumentOperationFailure > >; @@ -2009,8 +2053,10 @@ export interface EdgeCollection< */ remove( selector: documents.DocumentSelector, - options?: documents.RemoveDocumentOptions - ): Promise }>; + options?: documents.RemoveDocumentOptions, + ): Promise< + documents.DocumentMetadata & { old?: documents.Edge } + >; /** * Removes existing documents from the collection. * @@ -2031,7 +2077,7 @@ export interface EdgeCollection< */ removeAll( selectors: documents.DocumentSelector[], - options?: documents.RemoveDocumentOptions + options?: documents.RemoveDocumentOptions, ): Promise< Array< | (documents.DocumentMetadata & { old?: documents.Edge }) @@ -2058,7 +2104,7 @@ export interface EdgeCollection< */ import( data: documents.EdgeData[], - options?: documents.ImportDocumentsOptions + options?: documents.ImportDocumentsOptions, ): Promise; /** * Bulk imports the given `data` into the collection. @@ -2083,7 +2129,7 @@ export interface EdgeCollection< */ import( data: any[][], - options?: documents.ImportDocumentsOptions + options?: documents.ImportDocumentsOptions, ): Promise; /** * Bulk imports the given `data` into the collection. @@ -2142,7 +2188,7 @@ export interface EdgeCollection< data: Buffer | Blob | string, options?: documents.ImportDocumentsOptions & { type?: "documents" | "list" | "auto"; - } + }, ): Promise; //#endregion @@ -2174,8 +2220,10 @@ export interface EdgeCollection< */ edges( selector: documents.DocumentSelector, - options?: documents.DocumentEdgesOptions - ): Promise>>; + options?: documents.DocumentEdgesOptions, + ): Promise< + connection.ArangoApiResponse> + >; /** * Retrieves a list of all incoming edges of the document matching the given * `selector`. @@ -2203,8 +2251,10 @@ export interface EdgeCollection< */ inEdges( selector: documents.DocumentSelector, - options?: documents.DocumentEdgesOptions - ): Promise>>; + options?: documents.DocumentEdgesOptions, + ): Promise< + connection.ArangoApiResponse> + >; /** * Retrieves a list of all outgoing edges of the document matching the given * `selector`. @@ -2232,8 +2282,10 @@ export interface EdgeCollection< */ outEdges( selector: documents.DocumentSelector, - options?: documents.DocumentEdgesOptions - ): Promise>>; + options?: documents.DocumentEdgesOptions, + ): Promise< + connection.ArangoApiResponse> + >; //#endregion } //#endregion @@ -2243,12 +2295,13 @@ export interface EdgeCollection< * @internal */ export class Collection< - EntryResultType extends Record = any, - EntryInputType extends Record = EntryResultType, -> + EntryResultType extends Record = any, + EntryInputType extends Record = EntryResultType, + > implements - EdgeCollection, - DocumentCollection { + EdgeCollection, + DocumentCollection +{ protected _name: string; protected _db: databases.Database; @@ -2294,7 +2347,7 @@ export class Collection< create( options: CreateCollectionOptions & { type?: CollectionType; - } = {} + } = {}, ) { const { waitForSyncReplication = undefined, @@ -2337,8 +2390,10 @@ export class Collection< } properties( - properties?: CollectionPropertiesOptions - ): Promise> { + properties?: CollectionPropertiesOptions, + ): Promise< + connection.ArangoApiResponse + > { if (!properties) { return this._db.request({ pathname: `/_api/collection/${encodeURIComponent(this._name)}/properties`, @@ -2366,18 +2421,19 @@ export class Collection< { method: "PUT", pathname: `/_api/collection/${encodeURIComponent( - this._name + this._name, )}/recalculateCount`, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } figures( - details = false + details = false, ): Promise< connection.ArangoApiResponse< - CollectionDescription & CollectionProperties & { count: number; figures: Record } + CollectionDescription & + CollectionProperties & { count: number; figures: Record } > > { return this._db.request({ @@ -2397,7 +2453,7 @@ export class Collection< } checksum( - options?: CollectionChecksumOptions + options?: CollectionChecksumOptions, ): Promise< connection.ArangoApiResponse< CollectionDescription & { revision: string; checksum: string } @@ -2415,7 +2471,9 @@ export class Collection< return result; } - truncate(options?: TruncateCollectionOptions): Promise> { + truncate( + options?: TruncateCollectionOptions, + ): Promise> { return this._db.request({ method: "PUT", pathname: `/_api/collection/${this._name}/truncate`, @@ -2432,28 +2490,26 @@ export class Collection< } compact() { - return this._db.request( - { - method: "PUT", - pathname: `/_api/collection/${this._name}/compact`, - } - ); + return this._db.request({ + method: "PUT", + pathname: `/_api/collection/${this._name}/compact`, + }); } //#endregion //#region Document operations getResponsibleShard( - document: Partial> + document: Partial>, ): Promise { return this._db.request( { method: "PUT", pathname: `/_api/collection/${encodeURIComponent( - this._name + this._name, )}/responsibleShard`, body: document, }, - (res) => res.parsedBody.shardId + (res) => res.parsedBody.shardId, ); } @@ -2463,7 +2519,7 @@ export class Collection< async documentExists( selector: documents.DocumentSelector, - options: documents.DocumentExistsOptions = {} + options: documents.DocumentExistsOptions = {}, ): Promise { const { ifMatch = undefined, ifNoneMatch = undefined } = options; const headers = {} as Record; @@ -2474,7 +2530,7 @@ export class Collection< { method: "HEAD", pathname: `/_api/document/${encodeURI( - documents._documentHandle(selector, this._name) + documents._documentHandle(selector, this._name), )}`, headers, }, @@ -2483,7 +2539,7 @@ export class Collection< throw new errors.HttpError(res); } return true; - } + }, ); } catch (err: any) { if (err.code === 404) { @@ -2495,7 +2551,7 @@ export class Collection< documents( selectors: (string | documents.ObjectWithDocumentKey)[], - options: documents.BulkReadDocumentsOptions = {} + options: documents.BulkReadDocumentsOptions = {}, ) { const { allowDirtyRead = undefined } = options; return this._db.request({ @@ -2509,7 +2565,7 @@ export class Collection< async document( selector: documents.DocumentSelector, - options: boolean | documents.ReadDocumentOptions = {} + options: boolean | documents.ReadDocumentOptions = {}, ) { if (typeof options === "boolean") { options = { graceful: options }; @@ -2526,7 +2582,7 @@ export class Collection< const result = this._db.request( { pathname: `/_api/document/${encodeURI( - documents._documentHandle(selector, this._name) + documents._documentHandle(selector, this._name), )}`, headers, allowDirtyRead, @@ -2536,7 +2592,7 @@ export class Collection< throw new errors.HttpError(res); } return res.parsedBody; - } + }, ); if (!graceful) return result; try { @@ -2549,7 +2605,10 @@ export class Collection< } } - save(data: documents.DocumentData, options?: documents.InsertDocumentOptions) { + save( + data: documents.DocumentData, + options?: documents.InsertDocumentOptions, + ) { return this._db.request( { method: "POST", @@ -2557,13 +2616,13 @@ export class Collection< body: data, search: options, }, - (res) => (options?.silent ? undefined : res.parsedBody) + (res) => (options?.silent ? undefined : res.parsedBody), ); } saveAll( data: Array>, - options?: documents.InsertDocumentOptions + options?: documents.InsertDocumentOptions, ) { return this._db.request( { @@ -2572,14 +2631,14 @@ export class Collection< body: data, search: options, }, - (res) => (options?.silent ? undefined : res.parsedBody) + (res) => (options?.silent ? undefined : res.parsedBody), ); } replace( selector: documents.DocumentSelector, newData: documents.DocumentData, - options: documents.ReplaceDocumentOptions = {} + options: documents.ReplaceDocumentOptions = {}, ) { const { ifMatch = undefined, ...opts } = options; const headers = {} as Record; @@ -2588,21 +2647,22 @@ export class Collection< { method: "PUT", pathname: `/_api/document/${encodeURI( - documents._documentHandle(selector, this._name) + documents._documentHandle(selector, this._name), )}`, headers, body: newData, search: opts, }, - (res) => (options?.silent ? undefined : res.parsedBody) + (res) => (options?.silent ? undefined : res.parsedBody), ); } replaceAll( newData: Array< - documents.DocumentData & ({ _key: string } | { _id: string }) + documents.DocumentData & + ({ _key: string } | { _id: string }) >, - options?: documents.ReplaceDocumentOptions + options?: documents.ReplaceDocumentOptions, ) { return this._db.request( { @@ -2611,14 +2671,14 @@ export class Collection< body: newData, search: options, }, - (res) => (options?.silent ? undefined : res.parsedBody) + (res) => (options?.silent ? undefined : res.parsedBody), ); } update( selector: documents.DocumentSelector, newData: documents.Patch>, - options: documents.UpdateDocumentOptions = {} + options: documents.UpdateDocumentOptions = {}, ) { const { ifMatch = undefined, ...opts } = options; const headers = {} as Record; @@ -2627,21 +2687,22 @@ export class Collection< { method: "PATCH", pathname: `/_api/document/${encodeURI( - documents._documentHandle(selector, this._name) + documents._documentHandle(selector, this._name), )}`, headers, body: newData, search: opts, }, - (res) => (options?.silent ? undefined : res.parsedBody) + (res) => (options?.silent ? undefined : res.parsedBody), ); } updateAll( newData: Array< - documents.Patch> & ({ _key: string } | { _id: string }) + documents.Patch> & + ({ _key: string } | { _id: string }) >, - options?: documents.UpdateDocumentOptions + options?: documents.UpdateDocumentOptions, ) { return this._db.request( { @@ -2650,11 +2711,14 @@ export class Collection< body: newData, search: options, }, - (res) => (options?.silent ? undefined : res.parsedBody) + (res) => (options?.silent ? undefined : res.parsedBody), ); } - remove(selector: documents.DocumentSelector, options: documents.RemoveDocumentOptions = {}) { + remove( + selector: documents.DocumentSelector, + options: documents.RemoveDocumentOptions = {}, + ) { const { ifMatch = undefined, ...opts } = options; const headers = {} as Record; if (ifMatch) headers["if-match"] = ifMatch; @@ -2662,18 +2726,18 @@ export class Collection< { method: "DELETE", pathname: `/_api/document/${encodeURI( - documents._documentHandle(selector, this._name) + documents._documentHandle(selector, this._name), )}`, headers, search: opts, }, - (res) => (options?.silent ? undefined : res.parsedBody) + (res) => (options?.silent ? undefined : res.parsedBody), ); } removeAll( selectors: (string | documents.ObjectWithDocumentKey)[], - options?: documents.RemoveDocumentOptions + options?: documents.RemoveDocumentOptions, ) { return this._db.request( { @@ -2682,7 +2746,7 @@ export class Collection< body: selectors, search: options, }, - (res) => (options?.silent ? undefined : res.parsedBody) + (res) => (options?.silent ? undefined : res.parsedBody), ); } @@ -2690,7 +2754,7 @@ export class Collection< data: Buffer | Blob | string | any[], options: documents.ImportDocumentsOptions & { type?: "documents" | "list" | "auto"; - } = {} + } = {}, ): Promise { const search = { ...options, collection: this._name }; if (Array.isArray(data)) { @@ -2712,7 +2776,7 @@ export class Collection< protected _edges( selector: documents.DocumentSelector, options: documents.DocumentEdgesOptions = {}, - direction?: "in" | "out" + direction?: "in" | "out", ) { const { allowDirtyRead = undefined } = options; return this._db.request({ @@ -2725,15 +2789,24 @@ export class Collection< }); } - edges(vertex: documents.DocumentSelector, options?: documents.DocumentEdgesOptions) { + edges( + vertex: documents.DocumentSelector, + options?: documents.DocumentEdgesOptions, + ) { return this._edges(vertex, options); } - inEdges(vertex: documents.DocumentSelector, options?: documents.DocumentEdgesOptions) { + inEdges( + vertex: documents.DocumentSelector, + options?: documents.DocumentEdgesOptions, + ) { return this._edges(vertex, options, "in"); } - outEdges(vertex: documents.DocumentSelector, options?: documents.DocumentEdgesOptions) { + outEdges( + vertex: documents.DocumentSelector, + options?: documents.DocumentEdgesOptions, + ) { return this._edges(vertex, options, "out"); } //#endregion @@ -2744,10 +2817,10 @@ export class Collection< { method: "PUT", pathname: `/_api/collection/${encodeURIComponent( - this._name + this._name, )}/loadIndexesIntoMemory`, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -2757,7 +2830,7 @@ export class Collection< pathname: "/_api/index", search: { collection: this._name, ...options }, }, - (res) => res.parsedBody.indexes + (res) => res.parsedBody.indexes, ); } @@ -2784,4 +2857,4 @@ export class Collection< } //#endregion } -//#endregion \ No newline at end of file +//#endregion diff --git a/src/configuration.ts b/src/configuration.ts index 54e703cd..69ee050c 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -54,7 +54,9 @@ export type BearerAuthCredentials = { /** * Determines if the given credentials are for Bearer token authentication. */ -export function isBearerAuth(auth: BasicAuthCredentials | BearerAuthCredentials): auth is BearerAuthCredentials { +export function isBearerAuth( + auth: BasicAuthCredentials | BearerAuthCredentials, +): auth is BearerAuthCredentials { return auth.hasOwnProperty("token"); } //#endregion @@ -190,4 +192,4 @@ export type ConfigOptions = connection.CommonRequestOptions & { */ responseQueueTimeSamples?: number; }; -//#endregion \ No newline at end of file +//#endregion diff --git a/src/connection.ts b/src/connection.ts index 5cd5883f..33667898 100644 --- a/src/connection.ts +++ b/src/connection.ts @@ -11,13 +11,13 @@ import * as administration from "./administration.js"; import * as configuration from "./configuration.js"; import * as databases from "./databases.js"; import * as errors from "./errors.js"; +import { ERROR_ARANGO_CONFLICT } from "./lib/codes.js"; import * as util from "./lib/util.js"; import { LinkedList } from "./lib/x3-linkedlist.js"; -import { ERROR_ARANGO_CONFLICT } from "./lib/codes.js"; const MIME_JSON = /\/(json|javascript)(\W|$)/; const LEADER_ENDPOINT_HEADER = "x-arango-endpoint"; -const REASON_TIMEOUT = 'timeout'; +const REASON_TIMEOUT = "timeout"; //#region Host /** @@ -32,7 +32,17 @@ type Host = { * @param pathname - URL path, relative to the server URL. * @param options - Options for this fetch request. */ - fetch: (options: Omit) => Promise; + fetch: ( + options: Omit< + RequestOptions, + | "maxRetries" + | "retryOnConflict" + | "allowDirtyRead" + | "hostUrl" + | "expectBinary" + | "isBinary" + >, + ) => Promise; /** * @internal * @@ -68,7 +78,7 @@ function createHost(arangojsHostUrl: string, agentOptions?: any): Host { }; } if (agentOptions) { - createDispatcher = (async () => { + createDispatcher = async () => { let undici: any; try { // Prevent overzealous bundlers from attempting to bundle undici @@ -76,35 +86,45 @@ function createHost(arangojsHostUrl: string, agentOptions?: any): Host { undici = await import(undiciName); } catch (cause) { if (socketPath) { - throw new Error('Undici is required for Unix domain sockets', { cause }); + throw new Error("Undici is required for Unix domain sockets", { + cause, + }); } - throw new Error('Undici is required when using config.agentOptions', { cause }); + throw new Error("Undici is required when using config.agentOptions", { + cause, + }); } fetch = undici.fetch; return new undici.Agent(agentOptions); - }); + }; } const pending = new Map(); return { - async fetch( - { - method, - pathname, - search, - headers: requestHeaders, - body, - timeout, - fetchOptions, - beforeRequest, - afterResponse, - }: Omit) { + async fetch({ + method, + pathname, + search, + headers: requestHeaders, + body, + timeout, + fetchOptions, + beforeRequest, + afterResponse, + }: Omit< + RequestOptions, + | "maxRetries" + | "retryOnConflict" + | "allowDirtyRead" + | "hostUrl" + | "expectBinary" + | "isBinary" + >) { const url = new URL(pathname + baseUrl.search, baseUrl); if (search) { - const searchParams = ( + const searchParams = search instanceof URLSearchParams ? search - : new URLSearchParams(search) - ); + : new URLSearchParams(search); for (const [key, value] of searchParams) { url.searchParams.append(key, value); } @@ -114,8 +134,8 @@ function createHost(arangojsHostUrl: string, agentOptions?: any): Host { headers.set( "authorization", `Basic ${btoa( - `${baseUrl.username || "root"}:${baseUrl.password || ""}` - )}` + `${baseUrl.username || "root"}:${baseUrl.password || ""}`, + )}`, ); } const abortController = new AbortController(); @@ -147,14 +167,20 @@ function createHost(arangojsHostUrl: string, agentOptions?: any): Host { } let response: globalThis.Response & { request: globalThis.Request }; try { - response = Object.assign(await fetch(request), { request, arangojsHostUrl }); + response = Object.assign(await fetch(request), { + request, + arangojsHostUrl, + }); } catch (e: unknown) { const cause = e instanceof Error ? e : new Error(String(e)); let error: errors.NetworkError; if (signal.aborted) { - const reason = typeof signal.reason == 'string' ? signal.reason : undefined; + const reason = + typeof signal.reason == "string" ? signal.reason : undefined; if (reason === REASON_TIMEOUT) { - error = new errors.ResponseTimeoutError(undefined, request, { cause }); + error = new errors.ResponseTimeoutError(undefined, request, { + cause, + }); } else { error = new errors.RequestAbortedError(reason, request, { cause }); } @@ -249,9 +275,11 @@ const STATUS_CODE_DEFAULT_MESSAGES = { }; type KnownStatusCode = keyof typeof STATUS_CODE_DEFAULT_MESSAGES; -const KNOWN_STATUS_CODES = Object.keys(STATUS_CODE_DEFAULT_MESSAGES).map((k) => Number(k)) as KnownStatusCode[]; +const KNOWN_STATUS_CODES = Object.keys(STATUS_CODE_DEFAULT_MESSAGES).map((k) => + Number(k), +) as KnownStatusCode[]; const REDIRECT_CODES = [301, 302, 303, 307, 308] satisfies KnownStatusCode[]; -type RedirectStatusCode = typeof REDIRECT_CODES[number]; +type RedirectStatusCode = (typeof REDIRECT_CODES)[number]; /** * @internal @@ -340,7 +368,7 @@ export type ArangoErrorResponse = { * for more information. */ errorNum: number; -} +}; /** * Processed response object. @@ -360,7 +388,7 @@ export interface ProcessedResponse extends globalThis.Response { * Parsed response body. */ parsedBody?: T; -}; +} //#endregion //#region Request options @@ -374,7 +402,10 @@ export type CommonFetchOptions = { * Note that the `Authorization` header will be overridden if the `auth` * configuration option is set. */ - headers?: string[][] | Record> | Headers; + headers?: + | string[][] + | Record> + | Headers; /** * Controls whether the socket should be reused for subsequent requests. * @@ -390,7 +421,7 @@ export type CommonFetchOptions = { * * Default: `"follow"` */ - redirect?: 'error' | 'follow' | 'manual'; + redirect?: "error" | "follow" | "manual"; /** * Value to use for the `Referer` header. * @@ -424,7 +455,7 @@ export type CommonFetchOptions = { * * Default: `"same-origin"` */ - credentials?: 'omit' | 'include' | 'same-origin'; + credentials?: "omit" | "include" | "same-origin"; /** * (Node.js only.) Undici `Dispatcher` instance to use for the request. * @@ -450,7 +481,7 @@ export type CommonFetchOptions = { * * Default: `"auto"` */ - priority?: 'low' | 'high' | 'auto'; + priority?: "low" | "high" | "auto"; /** * (Browser only.) Policy to use for the `Referer` header, equivalent to the * semantics of the `Referrer-Policy` header. @@ -543,7 +574,10 @@ export type CommonRequestOptions = { * @param err - Error encountered when handling this request or `null`. * @param res - Response object for this request, if no error occurred. */ - afterResponse?: (err: errors.NetworkError | null, res?: globalThis.Response & { request: globalThis.Request; }) => void | Promise; + afterResponse?: ( + err: errors.NetworkError | null, + res?: globalThis.Response & { request: globalThis.Request }, + ) => void | Promise; }; /** @@ -576,7 +610,10 @@ export type RequestOptions = CommonRequestOptions & { * Note that the `Authorization` header will be overridden if the `auth` * configuration option is set. */ - headers?: string[][] | Record> | Headers; + headers?: + | string[][] + | Record> + | Headers; /** * Request body data. */ @@ -662,9 +699,10 @@ export class Connection { arangoVersion = 31100, loadBalancingStrategy = "NONE", maxRetries = 0, - poolSize = 3 * ( - loadBalancingStrategy === "ROUND_ROBIN" && Array.isArray(url) ? url.length : 1 - ), + poolSize = 3 * + (loadBalancingStrategy === "ROUND_ROBIN" && Array.isArray(url) + ? url.length + : 1), fetchOptions: { headers, ...commonFetchOptions } = {}, onError, precaptureStackTraces = false, @@ -674,9 +712,8 @@ export class Connection { const URLS = Array.isArray(url) ? url : [url]; this._loadBalancingStrategy = loadBalancingStrategy; this._precaptureStackTraces = precaptureStackTraces; - this._responseQueueTimeSamples = ( - responseQueueTimeSamples < 0 ? Infinity : responseQueueTimeSamples - ); + this._responseQueueTimeSamples = + responseQueueTimeSamples < 0 ? Infinity : responseQueueTimeSamples; this._arangoVersion = arangoVersion; this._taskPoolSize = poolSize; this._onError = onError; @@ -689,11 +726,11 @@ export class Connection { this._commonFetchOptions.headers.set( "x-arango-version", - String(arangoVersion) + String(arangoVersion), ); this._commonFetchOptions.headers.set( "x-arango-driver", - `arangojs/${process.env.ARANGOJS_VERSION} (cloud)` + `arangojs/${process.env.ARANGOJS_VERSION} (cloud)`, ); this.addToHostList(URLS); @@ -762,10 +799,9 @@ export class Connection { request: globalThis.Request; arangojsHostUrl: string; parsedBody?: any; - } = Object.assign( - await host.fetch(task.options), - { arangojsHostUrl: hostUrl } - ); + } = Object.assign(await host.fetch(task.options), { + arangojsHostUrl: hostUrl, + }); const leaderEndpoint = res.headers.get(LEADER_ENDPOINT_HEADER); if (res.status === 503 && leaderEndpoint) { const [cleanUrl] = this.addToHostList(leaderEndpoint); @@ -838,7 +874,8 @@ export class Connection { err.isSafeToRetry && task.options.hostUrl === undefined && this._commonRequestOptions.maxRetries !== false && - task.retries < (this._commonRequestOptions.maxRetries || this._hosts.length - 1) + task.retries < + (this._commonRequestOptions.maxRetries || this._hosts.length - 1) ) { task.retries += 1; this._queue.push(task); @@ -871,7 +908,7 @@ export class Connection { setBasicAuth(auth: configuration.BasicAuthCredentials) { this.setHeader( "authorization", - `Basic ${btoa(`${auth.username}:${auth.password}`)}` + `Basic ${btoa(`${auth.username}:${auth.password}`)}`, ); } @@ -903,7 +940,10 @@ export class Connection { * @param databaseName - Name of the database. * @param database - Database instance to add to the cache. */ - database(databaseName: string, database: databases.Database): databases.Database; + database( + databaseName: string, + database: databases.Database, + ): databases.Database; /** * @internal * @@ -916,7 +956,7 @@ export class Connection { database(databaseName: string, database: null): undefined; database( databaseName: string, - database?: databases.Database | null + database?: databases.Database | null, ): databases.Database | undefined { if (database === null) { this._databases.delete(databaseName); @@ -947,7 +987,7 @@ export class Connection { const i = this._hostUrls.indexOf(url); if (i !== -1) return this._hosts[i]; return createHost(url); - }) + }), ); this._hostUrls.splice(0, this._hostUrls.length, ...cleanUrls); } @@ -963,15 +1003,13 @@ export class Connection { */ addToHostList(urls: string | string[]): string[] { const cleanUrls = (Array.isArray(urls) ? urls : [urls]).map((url) => - util.normalizeUrl(url) + util.normalizeUrl(url), ); const newUrls = cleanUrls.filter( - (url) => this._hostUrls.indexOf(url) === -1 + (url) => this._hostUrls.indexOf(url) === -1, ); this._hostUrls.push(...newUrls); - this._hosts.push( - ...newUrls.map(url => createHost(url)) - ); + this._hosts.push(...newUrls.map((url) => createHost(url))); return cleanUrls; } @@ -1063,10 +1101,9 @@ export class Connection { }); } catch (e) { if (endOfTime < Date.now()) { - throw new errors.PropagationTimeoutError( - undefined, - { cause: e as Error } - ); + throw new errors.PropagationTimeoutError(undefined, { + cause: e as Error, + }); } await new Promise((resolve) => setTimeout(resolve, 1000)); continue; @@ -1082,9 +1119,16 @@ export class Connection { * * Performs a request using the arangojs connection pool. */ - async request( + async request< + T = globalThis.Response & { request: globalThis.Request; parsedBody?: any }, + >( requestOptions: RequestOptions & { isBinary?: boolean }, - transform?: (res: globalThis.Response & { request: globalThis.Request; parsedBody?: any }) => T + transform?: ( + res: globalThis.Response & { + request: globalThis.Request; + parsedBody?: any; + }, + ) => T, ): Promise { const { hostUrl, @@ -1102,7 +1146,7 @@ export class Connection { const headers = util.mergeHeaders( this._commonFetchOptions.headers, - requestHeaders + requestHeaders, ); let body = requestBody; @@ -1164,7 +1208,9 @@ export class Connection { task.stack = () => `\n${capture.stack.split("\n").slice(3).join("\n")}`; } else { - const capture = util.generateStackTrace() as { readonly stack: string }; + const capture = util.generateStackTrace() as { + readonly stack: string; + }; if (Object.prototype.hasOwnProperty.call(capture, "stack")) { task.stack = () => `\n${capture.stack.split("\n").slice(4).join("\n")}`; @@ -1177,4 +1223,4 @@ export class Connection { }); } } -//#endregion \ No newline at end of file +//#endregion diff --git a/src/cursors.ts b/src/cursors.ts index bff892b7..1e9c1adc 100644 --- a/src/cursors.ts +++ b/src/cursors.ts @@ -184,10 +184,10 @@ export class BatchCursor { count: number; }, hostUrl?: string, - allowDirtyRead?: boolean + allowDirtyRead?: boolean, ) { const batches = new LinkedList( - body.result.length ? [new LinkedList(body.result)] : [] + body.result.length ? [new LinkedList(body.result)] : [], ); this._db = db; this._batches = batches; @@ -319,7 +319,11 @@ export class BatchCursor { * } * ``` */ - async *[Symbol.asyncIterator](): AsyncGenerator { + async *[Symbol.asyncIterator](): AsyncGenerator< + ItemType[], + undefined, + undefined + > { while (this.hasNext) { yield this.next() as Promise; } @@ -457,7 +461,11 @@ export class BatchCursor { * ``` */ async forEach( - callback: (currentBatch: ItemType[], index: number, self: this) => false | void + callback: ( + currentBatch: ItemType[], + index: number, + self: this, + ) => false | void, ): Promise { let index = 0; while (this.hasNext) { @@ -500,7 +508,7 @@ export class BatchCursor { * ``` */ async map( - callback: (currentBatch: ItemType[], index: number, self: this) => R + callback: (currentBatch: ItemType[], index: number, self: this) => R, ): Promise { let index = 0; const result: any[] = []; @@ -557,7 +565,7 @@ export class BatchCursor { * ``` */ async flatMap( - callback: (currentBatch: ItemType[], index: number, self: this) => R | R[] + callback: (currentBatch: ItemType[], index: number, self: this) => R | R[], ): Promise { let index = 0; const result: any[] = []; @@ -648,9 +656,9 @@ export class BatchCursor { accumulator: R, currentBatch: ItemType[], index: number, - self: this + self: this, ) => R, - initialValue: R + initialValue: R, ): Promise; /** @@ -689,17 +697,17 @@ export class BatchCursor { accumulator: ItemType[] | R, currentBatch: ItemType[], index: number, - self: this - ) => R + self: this, + ) => R, ): Promise; async reduce( reducer: ( accumulator: R, currentBatch: ItemType[], index: number, - self: this + self: this, ) => R, - initialValue?: R + initialValue?: R, ): Promise { let index = 0; if (!this.hasNext) return initialValue; @@ -751,7 +759,7 @@ export class BatchCursor { () => { this._hasMore = false; return undefined; - } + }, ); } } @@ -792,7 +800,10 @@ export class Cursor { /** * @internal */ - constructor(batchedCursor: BatchCursor, view: BatchCursorItemsView) { + constructor( + batchedCursor: BatchCursor, + view: BatchCursorItemsView, + ) { this._batches = batchedCursor; this._view = view; } @@ -865,7 +876,11 @@ export class Cursor { * } * ``` */ - async *[Symbol.asyncIterator](): AsyncGenerator { + async *[Symbol.asyncIterator](): AsyncGenerator< + ItemType, + undefined, + undefined + > { while (this.hasNext) { yield this.next() as Promise; } @@ -953,7 +968,11 @@ export class Cursor { * ``` */ async forEach( - callback: (currentValue: ItemType, index: number, self: this) => false | void + callback: ( + currentValue: ItemType, + index: number, + self: this, + ) => false | void, ): Promise { let index = 0; while (this.hasNext) { @@ -992,7 +1011,7 @@ export class Cursor { * ``` */ async map( - callback: (currentValue: ItemType, index: number, self: this) => R + callback: (currentValue: ItemType, index: number, self: this) => R, ): Promise { let index = 0; const result: any[] = []; @@ -1043,7 +1062,7 @@ export class Cursor { * ``` */ async flatMap( - callback: (currentValue: ItemType, index: number, self: this) => R | R[] + callback: (currentValue: ItemType, index: number, self: this) => R | R[], ): Promise { let index = 0; const result: any[] = []; @@ -1123,8 +1142,13 @@ export class Cursor { * ``` */ async reduce( - reducer: (accumulator: R, currentValue: ItemType, index: number, self: this) => R, - initialValue: R + reducer: ( + accumulator: R, + currentValue: ItemType, + index: number, + self: this, + ) => R, + initialValue: R, ): Promise; /** * Depletes the cursor by applying the `reducer` function to each item in @@ -1160,12 +1184,17 @@ export class Cursor { accumulator: ItemType | R, currentValue: ItemType, index: number, - self: this - ) => R + self: this, + ) => R, ): Promise; async reduce( - reducer: (accumulator: R, currentValue: ItemType, index: number, self: this) => R, - initialValue?: R + reducer: ( + accumulator: R, + currentValue: ItemType, + index: number, + self: this, + ) => R, + initialValue?: R, ): Promise { let index = 0; if (!this.hasNext) return initialValue; diff --git a/src/databases.ts b/src/databases.ts index 62a7bc6d..930b262c 100644 --- a/src/databases.ts +++ b/src/databases.ts @@ -144,7 +144,7 @@ export class Database { protected _graphs = new Map(); protected _views = new Map(); protected _trapRequest?: ( - trapped: TrappedError | TrappedRequest + trapped: TrappedError | TrappedRequest, ) => void; /** @@ -184,8 +184,12 @@ export class Database { */ constructor(database: Database, name?: string); constructor( - configOrDatabase: string | string[] | configuration.ConfigOptions | Database = {}, - name?: string + configOrDatabase: + | string + | string[] + | configuration.ConfigOptions + | Database = {}, + name?: string, ) { if (isArangoDatabase(configOrDatabase)) { const connection = configOrDatabase._connection; @@ -244,7 +248,10 @@ export class Database { * // with JSON request body '{"username": "admin", "password": "hunter2"}' * ``` */ - route(path?: string, headers?: Headers | Record): routes.Route { + route( + path?: string, + headers?: Headers | Record, + ): routes.Route { return new routes.Route(this, path, headers); } @@ -261,7 +268,7 @@ export class Database { */ async request( options: connection.RequestOptions, - transform?: (res: connection.ProcessedResponse) => ReturnType + transform?: (res: connection.ProcessedResponse) => ReturnType, ): Promise; /** * @internal @@ -275,16 +282,16 @@ export class Database { */ async request( options: connection.RequestOptions, - transform: false + transform: false, ): Promise>; async request( - { - pathname, - ...opts - }: connection.RequestOptions, - transform: false | ((res: connection.ProcessedResponse) => ReturnType) = (res) => res.parsedBody as ReturnType + { pathname, ...opts }: connection.RequestOptions, + transform: + | false + | ((res: connection.ProcessedResponse) => ReturnType) = (res) => + res.parsedBody as ReturnType, ): Promise { - pathname = util.joinPath('_db', encodeURIComponent(this._name), pathname); + pathname = util.joinPath("_db", encodeURIComponent(this._name), pathname); if (this._trapRequest) { const trap = this._trapRequest; this._trapRequest = undefined; @@ -316,7 +323,7 @@ export class Database { } return this._connection.request( { pathname, ...opts }, - transform || undefined + transform || undefined, ); } @@ -350,7 +357,7 @@ export class Database { const urls: string[] = await this.request( { pathname: "/_api/cluster/endpoints" }, (res) => - res.parsedBody.endpoints.map((endpoint: any) => endpoint.endpoint) + res.parsedBody.endpoints.map((endpoint: any) => endpoint.endpoint), ); if (urls.length > 0) { if (overwrite) this._connection.setHostList(urls); @@ -414,18 +421,22 @@ export class Database { */ async waitForPropagation( request: connection.RequestOptions, - timeout?: number + timeout?: number, ): Promise; async waitForPropagation( { pathname, ...request }: connection.RequestOptions, - timeout?: number + timeout?: number, ): Promise { await this._connection.waitForPropagation( { ...request, - pathname: util.joinPath('_db', encodeURIComponent(this._name), pathname), + pathname: util.joinPath( + "_db", + encodeURIComponent(this._name), + pathname, + ), }, - timeout + timeout, ); } @@ -513,7 +524,7 @@ export class Database { (res) => { this.useBearerAuth(res.parsedBody.jwt); return res.parsedBody.jwt; - } + }, ); } @@ -541,7 +552,7 @@ export class Database { if (!res.parsedBody.jwt) return null; this.useBearerAuth(res.parsedBody.jwt); return res.parsedBody.jwt; - } + }, ); } //#endregion @@ -599,7 +610,7 @@ export class Database { method: "GET", pathname: "/_admin/time", }, - (res) => res.parsedBody.time * 1000 + (res) => res.parsedBody.time * 1000, ); } @@ -636,15 +647,23 @@ export class Database { * // availability is either "default", "readonly", or false * ``` */ - async availability(graceful = false): Promise { + async availability( + graceful = false, + ): Promise { try { - return this.request({ - method: "GET", - pathname: "/_admin/server/availability", - }, (res) => res.parsedBody.mode); + return this.request( + { + method: "GET", + pathname: "/_admin/server/availability", + }, + (res) => res.parsedBody.mode, + ); } catch (e) { if (graceful) return false; - if ((errors.isArangoError(e) || e instanceof errors.HttpError) && e.code === 503) { + if ( + (errors.isArangoError(e) || e instanceof errors.HttpError) && + e.code === 503 + ) { return false; } throw e; @@ -656,7 +675,9 @@ export class Database { * * Note that this API may reveal sensitive data about the deployment. */ - supportInfo(): Promise { + supportInfo(): Promise< + administration.SingleServerSupportInfo | administration.ClusterSupportInfo + > { return this.request({ method: "GET", pathname: "/_admin/support-info", @@ -672,7 +693,7 @@ export class Database { method: "DELETE", pathname: "/_admin/shutdown", }, - () => undefined + () => undefined, ); } //#endregion @@ -690,7 +711,7 @@ export class Database { getClusterImbalance(): Promise { return this.request( { pathname: "/_admin/cluster/rebalance" }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -710,7 +731,7 @@ export class Database { * ``` */ computeClusterRebalance( - options: cluster.ClusterRebalanceOptions + options: cluster.ClusterRebalanceOptions, ): Promise { return this.request( { @@ -721,7 +742,7 @@ export class Database { ...options, }, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -740,7 +761,9 @@ export class Database { * } * ``` */ - executeClusterRebalance(moves: cluster.ClusterRebalanceMove[]): Promise { + executeClusterRebalance( + moves: cluster.ClusterRebalanceMove[], + ): Promise { return this.request({ method: "POST", pathname: "/_admin/cluster/rebalance/execute", @@ -766,7 +789,7 @@ export class Database { * ``` */ rebalanceCluster( - opts: cluster.ClusterRebalanceOptions + opts: cluster.ClusterRebalanceOptions, ): Promise { return this.request({ method: "PUT", @@ -811,7 +834,7 @@ export class Database { get(): Promise { return this.request( { pathname: "/_api/database/current" }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -855,7 +878,7 @@ export class Database { */ createDatabase( databaseName: string, - options?: CreateDatabaseOptions + options?: CreateDatabaseOptions, ): Promise; /** * Creates a new database with the given `databaseName` with the given @@ -873,11 +896,13 @@ export class Database { */ createDatabase( databaseName: string, - users: users.CreateDatabaseUserOptions[] + users: users.CreateDatabaseUserOptions[], ): Promise; createDatabase( databaseName: string, - usersOrOptions: users.CreateDatabaseUserOptions[] | CreateDatabaseOptions = {} + usersOrOptions: + | users.CreateDatabaseUserOptions[] + | CreateDatabaseOptions = {}, ): Promise { const { users, ...options } = Array.isArray(usersOrOptions) ? { users: usersOrOptions } @@ -888,7 +913,7 @@ export class Database { pathname: "/_api/database", body: { name: databaseName, users, options }, }, - () => this.database(databaseName) + () => this.database(databaseName), ); } @@ -908,7 +933,7 @@ export class Database { listDatabases(): Promise { return this.request( { pathname: "/_api/database" }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -929,7 +954,7 @@ export class Database { listUserDatabases(): Promise { return this.request( { pathname: "/_api/database/user" }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -950,8 +975,8 @@ export class Database { databases(): Promise { return this.request({ pathname: "/_api/database" }, (res) => (res.parsedBody.result as string[]).map((databaseName) => - this.database(databaseName) - ) + this.database(databaseName), + ), ); } @@ -972,8 +997,8 @@ export class Database { userDatabases(): Promise { return this.request({ pathname: "/_api/database/user" }, (res) => (res.parsedBody.result as string[]).map((databaseName) => - this.database(databaseName) - ) + this.database(databaseName), + ), ); } @@ -995,7 +1020,7 @@ export class Database { method: "DELETE", pathname: `/_api/database/${encodeURIComponent(databaseName)}`, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } //#endregion @@ -1047,14 +1072,14 @@ export class Database { EntryResultType extends Record = any, EntryInputType extends Record = EntryResultType, >( - collectionName: string + collectionName: string, ): collections.DocumentCollection & collections.EdgeCollection { collectionName = collectionName; if (!this._collections.has(collectionName)) { this._collections.set( collectionName, - new collections.Collection(this, collectionName) + new collections.Collection(this, collectionName), ); } return this._collections.get(collectionName)!; @@ -1093,7 +1118,7 @@ export class Database { collectionName: string, options?: collections.CreateCollectionOptions & { type?: collections.CollectionType.DOCUMENT_COLLECTION; - } + }, ): Promise>; /** * Creates a new edge collection with the given `collectionName` and @@ -1134,7 +1159,7 @@ export class Database { collectionName: string, options: collections.CreateCollectionOptions & { type: collections.CollectionType.EDGE_COLLECTION; - } + }, ): Promise>; async createCollection< EntryResultType extends Record = any, @@ -1143,9 +1168,11 @@ export class Database { collectionName: string, options?: collections.CreateCollectionOptions & { type?: collections.CollectionType; - } - ): Promise & - collections.EdgeCollection> { + }, + ): Promise< + collections.DocumentCollection & + collections.EdgeCollection + > { const collection = this.collection(collectionName); await collection.create(options); return collection; @@ -1187,9 +1214,8 @@ export class Database { EntryInputType extends Record = EntryResultType, >( collectionName: string, - options?: collections.CreateCollectionOptions - ): Promise< - collections.EdgeCollection> { + options?: collections.CreateCollectionOptions, + ): Promise> { return this.createCollection(collectionName, { ...options, type: collections.CollectionType.EDGE_COLLECTION, @@ -1210,7 +1236,7 @@ export class Database { */ async renameCollection( collectionName: string, - newName: string + newName: string, ): Promise> { const result = await this.request({ method: "PUT", @@ -1246,14 +1272,14 @@ export class Database { * ``` */ listCollections( - excludeSystem: boolean = true + excludeSystem: boolean = true, ): Promise { return this.request( { pathname: "/_api/collection", search: { excludeSystem }, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -1286,8 +1312,10 @@ export class Database { * ``` */ async collections( - excludeSystem: boolean = true - ): Promise> { + excludeSystem: boolean = true, + ): Promise< + Array + > { const collections = await this.listCollections(excludeSystem); return collections.map((data) => this.collection(data.name)); } @@ -1324,7 +1352,7 @@ export class Database { async createGraph( graphName: string, edgeDefinitions: graphs.EdgeDefinitionOptions[], - options?: graphs.CreateGraphOptions + options?: graphs.CreateGraphOptions, ): Promise { const graph = this.graph(graphName); await graph.create(edgeDefinitions, options); @@ -1347,7 +1375,7 @@ export class Database { listGraphs(): Promise { return this.request( { pathname: "/_api/gharial" }, - (res) => res.parsedBody.graphs + (res) => res.parsedBody.graphs, ); } @@ -1405,7 +1433,7 @@ export class Database { */ async createView( viewName: string, - options: views.CreateViewOptions + options: views.CreateViewOptions, ): Promise { const view = this.view(viewName); await view.create(options); @@ -1426,7 +1454,7 @@ export class Database { */ async renameView( viewName: string, - newName: string + newName: string, ): Promise> { const result = await this.request({ method: "PUT", @@ -1452,7 +1480,10 @@ export class Database { * ``` */ listViews(): Promise { - return this.request({ pathname: "/_api/view" }, (res) => res.parsedBody.result); + return this.request( + { pathname: "/_api/view" }, + (res) => res.parsedBody.result, + ); } /** @@ -1491,7 +1522,7 @@ export class Database { if (!this._analyzers.has(analyzerName)) { this._analyzers.set( analyzerName, - new analyzers.Analyzer(this, analyzerName) + new analyzers.Analyzer(this, analyzerName), ); } return this._analyzers.get(analyzerName)!; @@ -1513,7 +1544,7 @@ export class Database { */ async createAnalyzer( analyzerName: string, - options: analyzers.CreateAnalyzerOptions + options: analyzers.CreateAnalyzerOptions, ): Promise { const analyzer = this.analyzer(analyzerName); await analyzer.create(options); @@ -1536,7 +1567,7 @@ export class Database { listAnalyzers(): Promise { return this.request( { pathname: "/_api/analyzer" }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -1576,7 +1607,7 @@ export class Database { { pathname: "/_api/user", }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -1592,7 +1623,9 @@ export class Database { * // user is the user object for the user named "steve" * ``` */ - getUser(username: string): Promise> { + getUser( + username: string, + ): Promise> { return this.request({ pathname: `/_api/user/${encodeURIComponent(username)}`, }); @@ -1613,7 +1646,7 @@ export class Database { */ createUser( username: string, - passwd: string + passwd: string, ): Promise>; /** * Creates a new ArangoDB user with the given options. @@ -1630,11 +1663,11 @@ export class Database { */ createUser( username: string, - options: users.UserOptions + options: users.UserOptions, ): Promise>; createUser( username: string, - options: string | users.UserOptions + options: string | users.UserOptions, ): Promise> { if (typeof options === "string") { options = { passwd: options }; @@ -1645,7 +1678,7 @@ export class Database { pathname: "/_api/user", body: { user: username, ...options }, }, - (res) => res.parsedBody + (res) => res.parsedBody, ); } @@ -1664,7 +1697,7 @@ export class Database { */ updateUser( username: string, - passwd: string + passwd: string, ): Promise>; /** * Updates the ArangoDB user with the new options. @@ -1681,11 +1714,11 @@ export class Database { */ updateUser( username: string, - options: Partial + options: Partial, ): Promise>; updateUser( username: string, - options: string | Partial + options: string | Partial, ): Promise> { if (typeof options === "string") { options = { passwd: options }; @@ -1696,7 +1729,7 @@ export class Database { pathname: `/_api/user/${encodeURIComponent(username)}`, body: options, }, - (res) => res.parsedBody + (res) => res.parsedBody, ); } @@ -1715,7 +1748,7 @@ export class Database { */ replaceUser( username: string, - options: users.UserOptions + options: users.UserOptions, ): Promise> { if (typeof options === "string") { options = { passwd: options }; @@ -1726,7 +1759,7 @@ export class Database { pathname: `/_api/user/${encodeURIComponent(username)}`, body: options, }, - (res) => res.parsedBody + (res) => res.parsedBody, ); } @@ -1742,9 +1775,7 @@ export class Database { * // The user "steve" has been removed * ``` */ - removeUser( - username: string - ): Promise { + removeUser(username: string): Promise { return this.request( { method: "DELETE", @@ -1825,26 +1856,28 @@ export class Database { */ getUserAccessLevel( username: string, - { database, collection }: users.UserAccessLevelOptions + { database, collection }: users.UserAccessLevelOptions, ): Promise { const databaseName = isArangoDatabase(database) ? database.name - : database ?? - (collection instanceof collections.Collection - ? collection.database.name - : this._name); + : (database ?? + (collection instanceof collections.Collection + ? collection.database.name + : this._name)); const suffix = collection ? `/${encodeURIComponent( - collections.isArangoCollection(collection) ? collection.name : collection - )}` + collections.isArangoCollection(collection) + ? collection.name + : collection, + )}` : ""; return this.request( { pathname: `/_api/user/${encodeURIComponent( - username + username, )}/database/${encodeURIComponent(databaseName)}${suffix}`, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -1926,28 +1959,30 @@ export class Database { database, collection, grant, - }: users.UserAccessLevelOptions & { grant: users.AccessLevel } + }: users.UserAccessLevelOptions & { grant: users.AccessLevel }, ): Promise>> { const databaseName = isArangoDatabase(database) ? database.name - : database ?? - (collection instanceof collections.Collection - ? collection.database.name - : this._name); + : (database ?? + (collection instanceof collections.Collection + ? collection.database.name + : this._name)); const suffix = collection ? `/${encodeURIComponent( - collections.isArangoCollection(collection) ? collection.name : collection - )}` + collections.isArangoCollection(collection) + ? collection.name + : collection, + )}` : ""; return this.request( { method: "PUT", pathname: `/_api/user/${encodeURIComponent( - username + username, )}/database/${encodeURIComponent(databaseName)}${suffix}`, body: { grant }, }, - (res) => res.parsedBody + (res) => res.parsedBody, ); } @@ -2016,27 +2051,29 @@ export class Database { */ clearUserAccessLevel( username: string, - { database, collection }: users.UserAccessLevelOptions + { database, collection }: users.UserAccessLevelOptions, ): Promise>> { const databaseName = isArangoDatabase(database) ? database.name - : database ?? - (collection instanceof collections.Collection - ? collection.database.name - : this._name); + : (database ?? + (collection instanceof collections.Collection + ? collection.database.name + : this._name)); const suffix = collection ? `/${encodeURIComponent( - collections.isArangoCollection(collection) ? collection.name : collection - )}` + collections.isArangoCollection(collection) + ? collection.name + : collection, + )}` : ""; return this.request( { method: "DELETE", pathname: `/_api/user/${encodeURIComponent( - username + username, )}/database/${encodeURIComponent(databaseName)}${suffix}`, }, - (res) => res.parsedBody + (res) => res.parsedBody, ); } @@ -2058,7 +2095,7 @@ export class Database { */ getUserDatabases( username: string, - full?: false + full?: false, ): Promise>; /** * Fetches an object mapping names of databases to the access level of the @@ -2082,7 +2119,7 @@ export class Database { */ getUserDatabases( username: string, - full: true + full: true, ): Promise< Record< string, @@ -2098,7 +2135,7 @@ export class Database { pathname: `/_api/user/${encodeURIComponent(username)}/database`, search: { full }, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } //#endregion @@ -2154,9 +2191,11 @@ export class Database { * ``` */ executeTransaction( - collections: transactions.TransactionCollectionOptions & { allowImplicit?: boolean }, + collections: transactions.TransactionCollectionOptions & { + allowImplicit?: boolean; + }, action: string, - options?: transactions.TransactionOptions & { params?: any } + options?: transactions.TransactionOptions & { params?: any }, ): Promise; /** * Performs a server-side transaction and returns its return value. @@ -2205,7 +2244,7 @@ export class Database { executeTransaction( collections: (string | collections.ArangoCollection)[], action: string, - options?: transactions.TransactionOptions & { params?: any } + options?: transactions.TransactionOptions & { params?: any }, ): Promise; /** * Performs a server-side transaction and returns its return value. @@ -2254,16 +2293,18 @@ export class Database { executeTransaction( collection: string | collections.ArangoCollection, action: string, - options?: transactions.TransactionOptions & { params?: any } + options?: transactions.TransactionOptions & { params?: any }, ): Promise; executeTransaction( collections: - | (transactions.TransactionCollectionOptions & { allowImplicit?: boolean }) + | (transactions.TransactionCollectionOptions & { + allowImplicit?: boolean; + }) | (string | collections.ArangoCollection)[] | string | collections.ArangoCollection, action: string, - options: transactions.TransactionOptions & { params?: any } = {} + options: transactions.TransactionOptions & { params?: any } = {}, ): Promise { const { allowDirtyRead = undefined, ...opts } = options; return this.request( @@ -2277,7 +2318,7 @@ export class Database { ...opts, }, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -2331,7 +2372,7 @@ export class Database { */ beginTransaction( collections: transactions.TransactionCollectionOptions, - options?: transactions.TransactionOptions + options?: transactions.TransactionOptions, ): Promise; /** * Begins a new streaming transaction for the given collections, then returns @@ -2362,7 +2403,7 @@ export class Database { */ beginTransaction( collections: (string | collections.ArangoCollection)[], - options?: transactions.TransactionOptions + options?: transactions.TransactionOptions, ): Promise; /** * Begins a new streaming transaction for the given collections, then returns @@ -2392,7 +2433,7 @@ export class Database { */ beginTransaction( collection: string | collections.ArangoCollection, - options?: transactions.TransactionOptions + options?: transactions.TransactionOptions, ): Promise; beginTransaction( collections: @@ -2400,7 +2441,7 @@ export class Database { | (string | collections.ArangoCollection)[] | string | collections.ArangoCollection, - options: transactions.TransactionOptions = {} + options: transactions.TransactionOptions = {}, ): Promise { const { allowDirtyRead = undefined, ...opts } = options; return this.request( @@ -2413,7 +2454,7 @@ export class Database { ...opts, }, }, - (res) => new transactions.Transaction(this, res.parsedBody.result.id) + (res) => new transactions.Transaction(this, res.parsedBody.result.id), ); } @@ -2453,7 +2494,7 @@ export class Database { withTransaction( collections: transactions.TransactionCollectionOptions, callback: (step: transactions.Transaction["step"]) => Promise, - options?: transactions.TransactionOptions + options?: transactions.TransactionOptions, ): Promise; /** * Begins and commits a transaction using the given callback. Individual @@ -2491,7 +2532,7 @@ export class Database { withTransaction( collections: (string | collections.ArangoCollection)[], callback: (step: transactions.Transaction["step"]) => Promise, - options?: transactions.TransactionOptions + options?: transactions.TransactionOptions, ): Promise; /** * Begins and commits a transaction using the given callback. Individual @@ -2526,7 +2567,7 @@ export class Database { withTransaction( collection: string | collections.ArangoCollection, callback: (step: transactions.Transaction["step"]) => Promise, - options?: transactions.TransactionOptions + options?: transactions.TransactionOptions, ): Promise; async withTransaction( collections: @@ -2535,11 +2576,11 @@ export class Database { | string | collections.ArangoCollection, callback: (step: transactions.Transaction["step"]) => Promise, - options: transactions.TransactionOptions = {} + options: transactions.TransactionOptions = {}, ): Promise { const trx = await this.beginTransaction( collections as transactions.TransactionCollectionOptions, - options + options, ); try { const result = await callback((fn) => trx.step(fn)); @@ -2548,7 +2589,7 @@ export class Database { } catch (e) { try { await trx.abort(); - } catch { } + } catch {} throw e; } } @@ -2569,7 +2610,7 @@ export class Database { listTransactions(): Promise { return this._connection.request( { pathname: "/_api/transaction" }, - (res) => res.parsedBody.transactions + (res) => res.parsedBody.transactions, ); } @@ -2645,7 +2686,7 @@ export class Database { */ query( query: aql.AqlQuery, - options?: queries.QueryOptions + options?: queries.QueryOptions, ): Promise>; /** * Performs a database query using the given `query` and `bindVars`, then @@ -2699,12 +2740,12 @@ export class Database { query( query: string | aql.AqlLiteral, bindVars?: Record, - options?: queries.QueryOptions + options?: queries.QueryOptions, ): Promise>; query( query: string | aql.AqlQuery | aql.AqlLiteral, bindVars?: Record, - options: queries.QueryOptions = {} + options: queries.QueryOptions = {}, ): Promise> { if (aql.isAqlQuery(query)) { options = bindVars ?? {}; @@ -2747,8 +2788,8 @@ export class Database { this, res.parsedBody, res.arangojsHostUrl, - allowDirtyRead - ).items + allowDirtyRead, + ).items, ); } @@ -2776,7 +2817,7 @@ export class Database { */ explain( query: aql.AqlQuery, - options?: queries.ExplainOptions & { allPlans?: false } + options?: queries.ExplainOptions & { allPlans?: false }, ): Promise>; /** * Explains a database query using the given `query`. @@ -2805,7 +2846,7 @@ export class Database { */ explain( query: aql.AqlQuery, - options?: queries.ExplainOptions & { allPlans: true } + options?: queries.ExplainOptions & { allPlans: true }, ): Promise>; /** * Explains a database query using the given `query` and `bindVars`. @@ -2834,7 +2875,7 @@ export class Database { explain( query: string | aql.AqlLiteral, bindVars?: Record, - options?: queries.ExplainOptions & { allPlans?: false } + options?: queries.ExplainOptions & { allPlans?: false }, ): Promise>; /** * Explains a database query using the given `query` and `bindVars`. @@ -2864,13 +2905,17 @@ export class Database { explain( query: string | aql.AqlLiteral, bindVars?: Record, - options?: queries.ExplainOptions & { allPlans: true } + options?: queries.ExplainOptions & { allPlans: true }, ): Promise>; explain( query: string | aql.AqlQuery | aql.AqlLiteral, bindVars?: Record, - options?: queries.ExplainOptions - ): Promise> { + options?: queries.ExplainOptions, + ): Promise< + connection.ArangoApiResponse< + queries.SingleExplainResult | queries.MultiExplainResult + > + > { if (aql.isAqlQuery(query)) { options = bindVars; bindVars = query.bindVars; @@ -2907,7 +2952,9 @@ export class Database { * `); * ``` aql.*/ - parse(query: string | aql.AqlQuery | aql.AqlLiteral): Promise { + parse( + query: string | aql.AqlQuery | aql.AqlLiteral, + ): Promise { if (aql.isAqlQuery(query)) { query = query.query; } else if (aql.isAqlLiteral(query)) { @@ -2966,19 +3013,23 @@ export class Database { * }); * ``` */ - queryTracking(options: queries.QueryTrackingOptions): Promise; - queryTracking(options?: queries.QueryTrackingOptions): Promise { + queryTracking( + options: queries.QueryTrackingOptions, + ): Promise; + queryTracking( + options?: queries.QueryTrackingOptions, + ): Promise { return this.request( options ? { - method: "PUT", - pathname: "/_api/query/properties", - body: options, - } + method: "PUT", + pathname: "/_api/query/properties", + body: options, + } : { - method: "GET", - pathname: "/_api/query/properties", - } + method: "GET", + pathname: "/_api/query/properties", + }, ); } @@ -3038,7 +3089,7 @@ export class Database { method: "DELETE", pathname: "/_api/query/slow", }, - () => undefined + () => undefined, ); } @@ -3068,7 +3119,7 @@ export class Database { method: "DELETE", pathname: `/_api/query/${encodeURIComponent(queryId)}`, }, - () => undefined + () => undefined, ); } //#endregion @@ -3087,7 +3138,7 @@ export class Database { listUserFunctions(): Promise { return this.request( { pathname: "/_api/aqlfunction" }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -3125,7 +3176,7 @@ export class Database { createUserFunction( name: string, code: string, - isDeterministic: boolean = false + isDeterministic: boolean = false, ): Promise> { return this.request({ method: "POST", @@ -3151,7 +3202,7 @@ export class Database { */ dropUserFunction( name: string, - group: boolean = false + group: boolean = false, ): Promise> { return this.request({ method: "DELETE", @@ -3179,7 +3230,9 @@ export class Database { * const services = await db.listServices(false); // all services * ``` */ - listServices(excludeSystem: boolean = true): Promise { + listServices( + excludeSystem: boolean = true, + ): Promise { return this.request({ pathname: "/_api/foxx", search: { excludeSystem }, @@ -3221,7 +3274,7 @@ export class Database { async installService( mount: string, source: File | Blob | string, - options: services.InstallServiceOptions = {} + options: services.InstallServiceOptions = {}, ): Promise { const { configuration, dependencies, ...search } = options; const form = new FormData(); @@ -3233,7 +3286,7 @@ export class Database { } form.append( "source", - typeof source === "string" ? JSON.stringify(source) : source + typeof source === "string" ? JSON.stringify(source) : source, ); return await this.request({ body: form, @@ -3279,7 +3332,7 @@ export class Database { async replaceService( mount: string, source: File | Blob | string, - options: services.ReplaceServiceOptions = {} + options: services.ReplaceServiceOptions = {}, ): Promise { const { configuration, dependencies, ...search } = options; const form = new FormData(); @@ -3291,7 +3344,7 @@ export class Database { } form.append( "source", - typeof source === "string" ? JSON.stringify(source) : source + typeof source === "string" ? JSON.stringify(source) : source, ); return await this.request({ body: form, @@ -3337,7 +3390,7 @@ export class Database { async upgradeService( mount: string, source: File | Blob | string, - options: services.UpgradeServiceOptions = {} + options: services.UpgradeServiceOptions = {}, ): Promise { const { configuration, dependencies, ...search } = options; const form = new FormData(); @@ -3349,7 +3402,7 @@ export class Database { } form.append( "source", - typeof source === "string" ? JSON.stringify(source) : source + typeof source === "string" ? JSON.stringify(source) : source, ); return await this.request({ body: form, @@ -3373,7 +3426,7 @@ export class Database { */ uninstallService( mount: string, - options?: services.UninstallServiceOptions + options?: services.UninstallServiceOptions, ): Promise { return this.request( { @@ -3381,7 +3434,7 @@ export class Database { pathname: "/_api/foxx/service", search: { ...options, mount }, }, - () => undefined + () => undefined, ); } @@ -3427,7 +3480,7 @@ export class Database { */ getServiceConfiguration( mount: string, - minimal?: false + minimal?: false, ): Promise>; /** * Retrieves information about the service's configuration options and their @@ -3452,7 +3505,7 @@ export class Database { */ getServiceConfiguration( mount: string, - minimal: true + minimal: true, ): Promise>; getServiceConfiguration(mount: string, minimal: boolean = false) { return this.request({ @@ -3488,8 +3541,10 @@ export class Database { replaceServiceConfiguration( mount: string, cfg: Record, - minimal?: false - ): Promise>; + minimal?: false, + ): Promise< + Record + >; /** * Replaces the configuration of the given service, discarding any existing * values for options not specified. @@ -3517,7 +3572,7 @@ export class Database { replaceServiceConfiguration( mount: string, cfg: Record, - minimal: true + minimal: true, ): Promise<{ values: Record; warnings: Record; @@ -3525,7 +3580,7 @@ export class Database { replaceServiceConfiguration( mount: string, cfg: Record, - minimal: boolean = false + minimal: boolean = false, ) { return this.request({ method: "PUT", @@ -3562,8 +3617,10 @@ export class Database { updateServiceConfiguration( mount: string, cfg: Record, - minimal?: false - ): Promise>; + minimal?: false, + ): Promise< + Record + >; /** * Updates the configuration of the given service while maintaining any * existing values for options not specified. @@ -3591,7 +3648,7 @@ export class Database { updateServiceConfiguration( mount: string, cfg: Record, - minimal: true + minimal: true, ): Promise<{ values: Record; warnings: Record; @@ -3599,7 +3656,7 @@ export class Database { updateServiceConfiguration( mount: string, cfg: Record, - minimal: boolean = false + minimal: boolean = false, ) { return this.request({ method: "PATCH", @@ -3632,8 +3689,13 @@ export class Database { */ getServiceDependencies( mount: string, - minimal?: false - ): Promise>; + minimal?: false, + ): Promise< + Record< + string, + services.SingleServiceDependency | services.MultiServiceDependency + > + >; /** * Retrieves information about the service's dependencies and their current * mount points. @@ -3657,7 +3719,7 @@ export class Database { */ getServiceDependencies( mount: string, - minimal: true + minimal: true, ): Promise>; getServiceDependencies(mount: string, minimal: boolean = false) { return this.request({ @@ -3693,11 +3755,13 @@ export class Database { replaceServiceDependencies( mount: string, deps: Record, - minimal?: false + minimal?: false, ): Promise< Record< string, - (services.SingleServiceDependency | services.MultiServiceDependency) & { warning?: string } + (services.SingleServiceDependency | services.MultiServiceDependency) & { + warning?: string; + } > >; /** @@ -3731,7 +3795,7 @@ export class Database { replaceServiceDependencies( mount: string, deps: Record, - minimal: true + minimal: true, ): Promise<{ values: Record; warnings: Record; @@ -3739,7 +3803,7 @@ export class Database { replaceServiceDependencies( mount: string, deps: Record, - minimal: boolean = false + minimal: boolean = false, ) { return this.request({ method: "PUT", @@ -3776,11 +3840,13 @@ export class Database { updateServiceDependencies( mount: string, deps: Record, - minimal?: false + minimal?: false, ): Promise< Record< string, - (services.SingleServiceDependency | services.MultiServiceDependency) & { warning?: string } + (services.SingleServiceDependency | services.MultiServiceDependency) & { + warning?: string; + } > >; /** @@ -3814,7 +3880,7 @@ export class Database { updateServiceDependencies( mount: string, deps: Record, - minimal: true + minimal: true, ): Promise<{ values: Record; warnings: Record; @@ -3822,7 +3888,7 @@ export class Database { updateServiceDependencies( mount: string, deps: Record, - minimal: boolean = false + minimal: boolean = false, ) { return this.request({ method: "PATCH", @@ -3849,7 +3915,7 @@ export class Database { */ setServiceDevelopmentMode( mount: string, - enabled: boolean = true + enabled: boolean = true, ): Promise { return this.request({ method: enabled ? "POST" : "DELETE", @@ -3940,7 +4006,7 @@ export class Database { * executed. */ filter?: string; - } + }, ): Promise; /** * Runs the tests of a given service and returns the results using the @@ -3972,7 +4038,7 @@ export class Database { * executed. */ filter?: string; - } + }, ): Promise; /** * Runs the tests of a given service and returns the results using the @@ -4005,7 +4071,7 @@ export class Database { * executed. */ filter?: string; - } + }, ): Promise; /** * Runs the tests of a given service and returns the results using the @@ -4038,7 +4104,7 @@ export class Database { * executed. */ filter?: string; - } + }, ): Promise; /** * Runs the tests of a given service and returns the results using the @@ -4071,7 +4137,7 @@ export class Database { * executed. */ filter?: string; - } + }, ): Promise; /** * Runs the tests of a given service and returns the results as a string @@ -4105,7 +4171,7 @@ export class Database { * executed. */ filter?: string; - } + }, ): Promise; /** * Runs the tests of a given service and returns the results as a string @@ -4139,7 +4205,7 @@ export class Database { * executed. */ filter?: string; - } + }, ): Promise; /** * Runs the tests of a given service and returns the results as a string @@ -4173,7 +4239,7 @@ export class Database { * executed. */ filter?: string; - } + }, ): Promise; runServiceTests( mount: string, @@ -4181,7 +4247,7 @@ export class Database { reporter?: string; idiomatic?: boolean; filter?: string; - } + }, ) { return this.request({ method: "POST", @@ -4284,7 +4350,7 @@ export class Database { pathname: "/_api/foxx/commit", search: { replace }, }, - () => undefined + () => undefined, ); } //#endregion @@ -4304,7 +4370,7 @@ export class Database { * ``` */ createHotBackup( - options: hotBackups.HotBackupOptions = {} + options: hotBackups.HotBackupOptions = {}, ): Promise { return this.request( { @@ -4312,7 +4378,7 @@ export class Database { pathname: "/_admin/backup/create", body: options, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -4338,7 +4404,7 @@ export class Database { pathname: "/_admin/backup/list", body: id ? { id } : undefined, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -4362,7 +4428,7 @@ export class Database { pathname: "/_admin/backup/restore", body: { id }, }, - (res) => res.parsedBody.result.previous + (res) => res.parsedBody.result.previous, ); } @@ -4384,7 +4450,7 @@ export class Database { pathname: "/_admin/backup/delete", body: { id }, }, - () => undefined + () => undefined, ); } //#endregion @@ -4410,7 +4476,7 @@ export class Database { pathname: "/_admin/log/entries", search: options, }, - (res) => res.parsedBody + (res) => res.parsedBody, ); } @@ -4431,14 +4497,14 @@ export class Database { * ``` */ listLogMessages( - options?: logs.LogEntriesOptions + options?: logs.LogEntriesOptions, ): Promise { return this.request( { pathname: "/_admin/log", search: options, }, - (res) => res.parsedBody.messages + (res) => res.parsedBody.messages, ); } @@ -4471,7 +4537,7 @@ export class Database { * ``` */ setLogLevel( - levels: Record + levels: Record, ): Promise> { return this.request({ method: "PUT", @@ -4504,9 +4570,11 @@ export class Database { * ``` */ async createJob(callback: () => Promise): Promise> { - const trap = new Promise>((resolveTrap) => { - this._trapRequest = (trapped) => resolveTrap(trapped); - }); + const trap = new Promise>( + (resolveTrap) => { + this._trapRequest = (trapped) => resolveTrap(trapped); + }, + ); const eventualResult = callback(); const trapped = await trap; if (trapped.error) return eventualResult as Promise; @@ -4521,7 +4589,7 @@ export class Database { (e) => { onReject(e); return eventualResult; - } + }, ); } @@ -4555,7 +4623,7 @@ export class Database { { pathname: "/_api/job/pending", }, - (res) => res.parsedBody + (res) => res.parsedBody, ); } @@ -4574,7 +4642,7 @@ export class Database { { pathname: "/_api/job/done", }, - (res) => res.parsedBody + (res) => res.parsedBody, ); } @@ -4599,7 +4667,7 @@ export class Database { pathname: `/_api/job/expired`, search: { stamp: threshold / 1000 }, }, - () => undefined + () => undefined, ); } @@ -4612,7 +4680,7 @@ export class Database { method: "DELETE", pathname: `/_api/job/all`, }, - () => undefined + () => undefined, ); } //#endregion diff --git a/src/documents.ts b/src/documents.ts index ca9acfaa..4f396e8d 100644 --- a/src/documents.ts +++ b/src/documents.ts @@ -542,7 +542,10 @@ export type DocumentEdgesResult = any> = { * * See {@link DocumentMetadata}. */ -export type DocumentSelector = ObjectWithDocumentId | ObjectWithDocumentKey | string; +export type DocumentSelector = + | ObjectWithDocumentId + | ObjectWithDocumentKey + | string; /** * An object with an ArangoDB document `_id` property. @@ -570,7 +573,7 @@ export type ObjectWithDocumentKey = { export function _documentHandle( selector: DocumentSelector, collectionName: string, - strict: boolean = true + strict: boolean = true, ): string { if (typeof selector !== "string") { if (selector._id) { @@ -580,18 +583,18 @@ export function _documentHandle( return _documentHandle(selector._key, collectionName); } throw new Error( - "Document handle must be a string or an object with a _key or _id attribute" + "Document handle must be a string or an object with a _key or _id attribute", ); } if (selector.includes("/")) { const [head] = selector.split("/"); if (strict && head !== collectionName) { throw new Error( - `Document ID "${selector}" does not match collection name "${collectionName}"` + `Document ID "${selector}" does not match collection name "${collectionName}"`, ); } return selector; } return `${collectionName}/${selector}`; } -//#endregion \ No newline at end of file +//#endregion diff --git a/src/errors.ts b/src/errors.ts index 2b38982f..eae50925 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -39,9 +39,9 @@ export function isSystemError(err: any): err is SystemError { if (!err || !(err instanceof Error)) return false; if (Object.getPrototypeOf(err) !== Error.prototype) return false; const error = err as SystemError; - if (typeof error.code !== 'string') return false; - if (typeof error.syscall !== 'string') return false; - return typeof error.errno === 'number' || typeof error.errno === 'string'; + if (typeof error.code !== "string") return false; + if (typeof error.syscall !== "string") return false; + return typeof error.errno === "number" || typeof error.errno === "string"; } /** @@ -52,8 +52,8 @@ export function isSystemError(err: any): err is SystemError { export function isUndiciError(err: any): err is UndiciError { if (!err || !(err instanceof Error)) return false; const error = err as UndiciError; - if (typeof error.code !== 'string') return false; - return error.code.startsWith('UND_'); + if (typeof error.code !== "string") return false; + return error.code.startsWith("UND_"); } /** @@ -67,10 +67,14 @@ function isSafeToRetryFailedFetch(error?: Error): boolean | null { if (isArangoError(cause) || isNetworkError(cause)) { return cause.isSafeToRetry; } - if (isSystemError(cause) && cause.syscall === 'connect' && cause.code === 'ECONNREFUSED') { + if ( + isSystemError(cause) && + cause.syscall === "connect" && + cause.code === "ECONNREFUSED" + ) { return true; } - if (isUndiciError(cause) && cause.code === 'UND_ERR_CONNECT_TIMEOUT') { + if (isUndiciError(cause) && cause.code === "UND_ERR_CONNECT_TIMEOUT") { return true; } return isSafeToRetryFailedFetch(cause); @@ -104,7 +108,7 @@ export class PropagationTimeoutError extends Error { name = "PropagationTimeoutError"; constructor(message?: string, options: { cause?: Error } = {}) { - super(message ?? 'Timed out while waiting for propagation', options); + super(message ?? "Timed out while waiting for propagation", options); } } @@ -124,7 +128,11 @@ export class NetworkError extends Error { */ request: globalThis.Request; - constructor(message: string, request: globalThis.Request, options: { cause?: Error, isSafeToRetry?: boolean | null } = {}) { + constructor( + message: string, + request: globalThis.Request, + options: { cause?: Error; isSafeToRetry?: boolean | null } = {}, + ) { const { isSafeToRetry = null, ...opts } = options; super(message, opts); this.request = request; @@ -147,8 +155,16 @@ export class NetworkError extends Error { export class ResponseTimeoutError extends NetworkError { name = "ResponseTimeoutError"; - constructor(message: string | undefined, request: globalThis.Request, options: { cause?: Error, isSafeToRetry?: boolean | null } = {}) { - super(message ?? 'Timed out while waiting for server response', request, options); + constructor( + message: string | undefined, + request: globalThis.Request, + options: { cause?: Error; isSafeToRetry?: boolean | null } = {}, + ) { + super( + message ?? "Timed out while waiting for server response", + request, + options, + ); } } @@ -158,8 +174,12 @@ export class ResponseTimeoutError extends NetworkError { export class RequestAbortedError extends NetworkError { name = "RequestAbortedError"; - constructor(message: string | undefined, request: globalThis.Request, options: { cause?: Error, isSafeToRetry?: boolean | null } = {}) { - super(message ?? 'Request aborted', request, options); + constructor( + message: string | undefined, + request: globalThis.Request, + options: { cause?: Error; isSafeToRetry?: boolean | null } = {}, + ) { + super(message ?? "Request aborted", request, options); } } @@ -171,12 +191,17 @@ export class RequestAbortedError extends NetworkError { export class FetchFailedError extends NetworkError { name = "FetchFailedError"; - constructor(message: string | undefined, request: globalThis.Request, options: { cause?: Error, isSafeToRetry?: boolean | null } = {}) { - let isSafeToRetry = options.isSafeToRetry ?? isSafeToRetryFailedFetch(options.cause); + constructor( + message: string | undefined, + request: globalThis.Request, + options: { cause?: Error; isSafeToRetry?: boolean | null } = {}, + ) { + let isSafeToRetry = + options.isSafeToRetry ?? isSafeToRetryFailedFetch(options.cause); if (options.cause?.cause instanceof Error && options.cause.cause.message) { message = `Fetch failed: ${options.cause.cause.message}`; } - super(message ?? 'Fetch failed', request, { ...options, isSafeToRetry }); + super(message ?? "Fetch failed", request, { ...options, isSafeToRetry }); } } @@ -199,7 +224,10 @@ export class HttpError extends NetworkError { /** * @internal */ - constructor(response: connection.ProcessedResponse, options: { cause?: Error, isSafeToRetry?: boolean | null } = {}) { + constructor( + response: connection.ProcessedResponse, + options: { cause?: Error; isSafeToRetry?: boolean | null } = {}, + ) { super(connection.getStatusMessage(response), response.request, options); this.response = response; this.code = response.status; @@ -262,9 +290,11 @@ export class ArangoError extends Error { * * Creates a new `ArangoError` from a response object. */ - static from(response: connection.ProcessedResponse): ArangoError { + static from( + response: connection.ProcessedResponse, + ): ArangoError { return new ArangoError(response.parsedBody!, { - cause: new HttpError(response) + cause: new HttpError(response), }); } @@ -291,7 +321,9 @@ export class ArangoError extends Error { /** * Server response object. */ - get response(): connection.ProcessedResponse | undefined { + get response(): + | connection.ProcessedResponse + | undefined { const cause = this.cause; if (cause instanceof HttpError) { return cause.response; @@ -331,4 +363,4 @@ export class ArangoError extends Error { toString() { return `${this.name} ${this.errorNum}: ${this.message}`; } -} \ No newline at end of file +} diff --git a/src/foxx-manifest.ts b/src/foxx-manifest.ts index f11a40d3..76a91afb 100644 --- a/src/foxx-manifest.ts +++ b/src/foxx-manifest.ts @@ -103,14 +103,14 @@ export type Configuration = { * The type of value expected for this option. */ type: - | "integer" - | "boolean" - | "number" - | "string" - | "json" - | "password" - | "int" - | "bool"; + | "integer" + | "boolean" + | "number" + | "string" + | "json" + | "password" + | "int" + | "bool"; /** * The default value for this option in plain JSON. Can be omitted to provide no default value. */ diff --git a/src/graphs.ts b/src/graphs.ts index 8ae1700a..f82eb937 100644 --- a/src/graphs.ts +++ b/src/graphs.ts @@ -31,7 +31,9 @@ function mungeGharialResponse(body: any, prop: "vertex" | "edge" | "removed") { */ function coerceEdgeDefinition(options: EdgeDefinitionOptions): EdgeDefinition { const edgeDefinition = {} as EdgeDefinition; - edgeDefinition.collection = collections.collectionToString(options.collection); + edgeDefinition.collection = collections.collectionToString( + options.collection, + ); edgeDefinition.from = Array.isArray(options.from) ? options.from.map(collections.collectionToString) : [collections.collectionToString(options.from)]; @@ -168,11 +170,17 @@ export type EdgeDefinitionOptions = { /** * Collection or collections containing the start vertices. */ - from: (string | collections.ArangoCollection)[] | string | collections.ArangoCollection; + from: + | (string | collections.ArangoCollection)[] + | string + | collections.ArangoCollection; /** * Collection or collections containing the end vertices. */ - to: (string | collections.ArangoCollection)[] | string | collections.ArangoCollection; + to: + | (string | collections.ArangoCollection)[] + | string + | collections.ArangoCollection; }; //#endregion @@ -290,7 +298,10 @@ export type CreateGraphOptions = { * Additional vertex collections. Documents within these collections do not * have edges within this graph. */ - orphanCollections?: (string | collections.ArangoCollection)[] | string | collections.ArangoCollection; + orphanCollections?: + | (string | collections.ArangoCollection)[] + | string + | collections.ArangoCollection; /** * (Cluster only.) Number of shards that is used for every collection @@ -386,12 +397,15 @@ export type ReplaceEdgeDefinitionOptions = { export class GraphVertexCollection< EntryResultType extends Record = any, EntryInputType extends Record = EntryResultType, -> - implements collections.ArangoCollection { +> implements collections.ArangoCollection +{ protected _db: databases.Database; protected _name: string; protected _graph: Graph; - protected _collection: collections.DocumentCollection; + protected _collection: collections.DocumentCollection< + EntryResultType, + EntryInputType + >; /** * @internal @@ -466,10 +480,10 @@ export class GraphVertexCollection< { method: "HEAD", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/vertex/${encodeURI(documents._documentHandle(selector, this._name))}`, }, - () => true + () => true, ); } catch (err: any) { if (err.code === 404) { @@ -515,7 +529,7 @@ export class GraphVertexCollection< */ async vertex( selector: documents.DocumentSelector, - options?: ReadGraphDocumentOptions + options?: ReadGraphDocumentOptions, ): Promise>; /** * Retrieves the vertex matching the given key or id. @@ -554,11 +568,11 @@ export class GraphVertexCollection< */ async vertex( selector: documents.DocumentSelector, - graceful: boolean + graceful: boolean, ): Promise>; async vertex( selector: documents.DocumentSelector, - options: boolean | ReadGraphDocumentOptions = {} + options: boolean | ReadGraphDocumentOptions = {}, ): Promise | null> { if (typeof options === "boolean") { options = { graceful: options }; @@ -574,13 +588,13 @@ export class GraphVertexCollection< const result = this._db.request( { pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/vertex/${encodeURI(documents._documentHandle(selector, this._name))}`, headers, search, allowDirtyRead, }, - (res) => res.parsedBody.vertex + (res) => res.parsedBody.vertex, ); if (!graceful) return result; try { @@ -612,19 +626,24 @@ export class GraphVertexCollection< */ save( data: documents.DocumentData, - options?: InsertGraphDocumentOptions - ): Promise }>; - save(data: documents.DocumentData, options?: InsertGraphDocumentOptions) { + options?: InsertGraphDocumentOptions, + ): Promise< + documents.DocumentMetadata & { new?: documents.Document } + >; + save( + data: documents.DocumentData, + options?: InsertGraphDocumentOptions, + ) { return this._db.request( { method: "POST", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/vertex/${encodeURIComponent(this._name)}`, body: data, search: options, }, - (res) => mungeGharialResponse(res.parsedBody, "vertex") + (res) => mungeGharialResponse(res.parsedBody, "vertex"), ); } @@ -655,12 +674,17 @@ export class GraphVertexCollection< replace( selector: documents.DocumentSelector, newValue: documents.DocumentData, - options?: ReplaceGraphDocumentOptions - ): Promise; old?: documents.Document }>; + options?: ReplaceGraphDocumentOptions, + ): Promise< + documents.DocumentMetadata & { + new?: documents.Document; + old?: documents.Document; + } + >; replace( selector: documents.DocumentSelector, newValue: documents.DocumentData, - options: ReplaceGraphDocumentOptions = {} + options: ReplaceGraphDocumentOptions = {}, ) { if (typeof options === "string") { options = { rev: options }; @@ -672,13 +696,13 @@ export class GraphVertexCollection< { method: "PUT", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/vertex/${encodeURI(documents._documentHandle(selector, this._name))}`, body: newValue, search, headers, }, - (res) => mungeGharialResponse(res.parsedBody, "vertex") + (res) => mungeGharialResponse(res.parsedBody, "vertex"), ); } @@ -709,12 +733,17 @@ export class GraphVertexCollection< update( selector: documents.DocumentSelector, newValue: documents.Patch>, - options?: ReplaceGraphDocumentOptions - ): Promise; old?: documents.Document }>; + options?: ReplaceGraphDocumentOptions, + ): Promise< + documents.DocumentMetadata & { + new?: documents.Document; + old?: documents.Document; + } + >; update( selector: documents.DocumentSelector, newValue: documents.Patch>, - options: ReplaceGraphDocumentOptions = {} + options: ReplaceGraphDocumentOptions = {}, ) { if (typeof options === "string") { options = { rev: options }; @@ -726,13 +755,13 @@ export class GraphVertexCollection< { method: "PATCH", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/vertex/${encodeURI(documents._documentHandle(selector, this._name))}`, body: newValue, search, headers, }, - (res) => mungeGharialResponse(res.parsedBody, "vertex") + (res) => mungeGharialResponse(res.parsedBody, "vertex"), ); } @@ -765,11 +794,13 @@ export class GraphVertexCollection< */ remove( selector: documents.DocumentSelector, - options?: RemoveGraphDocumentOptions - ): Promise }>; + options?: RemoveGraphDocumentOptions, + ): Promise< + documents.DocumentMetadata & { old?: documents.Document } + >; remove( selector: documents.DocumentSelector, - options: RemoveGraphDocumentOptions = {} + options: RemoveGraphDocumentOptions = {}, ) { if (typeof options === "string") { options = { rev: options }; @@ -781,12 +812,12 @@ export class GraphVertexCollection< { method: "DELETE", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/vertex/${encodeURI(documents._documentHandle(selector, this._name))}`, search, headers, }, - (res) => mungeGharialResponse(res.parsedBody, "removed") + (res) => mungeGharialResponse(res.parsedBody, "removed"), ); } } @@ -804,12 +835,15 @@ export class GraphVertexCollection< export class GraphEdgeCollection< EntryResultType extends Record = any, EntryInputType extends Record = EntryResultType, -> - implements collections.ArangoCollection { +> implements collections.ArangoCollection +{ protected _db: databases.Database; protected _name: string; protected _graph: Graph; - protected _collection: collections.EdgeCollection; + protected _collection: collections.EdgeCollection< + EntryResultType, + EntryInputType + >; /** * @internal @@ -884,10 +918,10 @@ export class GraphEdgeCollection< { method: "HEAD", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/edge/${encodeURI(documents._documentHandle(selector, this._name))}`, }, - () => true + () => true, ); } catch (err: any) { if (err.code === 404) { @@ -933,7 +967,7 @@ export class GraphEdgeCollection< */ async edge( selector: documents.DocumentSelector, - options?: ReadGraphDocumentOptions + options?: ReadGraphDocumentOptions, ): Promise>; /** * Retrieves the edge matching the given key or id. @@ -970,10 +1004,13 @@ export class GraphEdgeCollection< * } * ``` */ - async edge(selector: documents.DocumentSelector, graceful: boolean): Promise>; async edge( selector: documents.DocumentSelector, - options: boolean | ReadGraphDocumentOptions = {} + graceful: boolean, + ): Promise>; + async edge( + selector: documents.DocumentSelector, + options: boolean | ReadGraphDocumentOptions = {}, ): Promise | null> { if (typeof options === "boolean") { options = { graceful: options }; @@ -989,12 +1026,12 @@ export class GraphEdgeCollection< const result = this._db.request( { pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/edge/${encodeURI(documents._documentHandle(selector, this._name))}`, search, allowDirtyRead, }, - (res) => res.parsedBody.edge + (res) => res.parsedBody.edge, ); if (!graceful) return result; try { @@ -1025,19 +1062,24 @@ export class GraphEdgeCollection< */ save( data: documents.EdgeData, - options?: InsertGraphDocumentOptions - ): Promise }>; - save(data: documents.EdgeData, options?: InsertGraphDocumentOptions) { + options?: InsertGraphDocumentOptions, + ): Promise< + documents.DocumentMetadata & { new?: documents.Edge } + >; + save( + data: documents.EdgeData, + options?: InsertGraphDocumentOptions, + ) { return this._db.request( { method: "POST", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/edge/${encodeURIComponent(this._name)}`, body: data, search: options, }, - (res) => mungeGharialResponse(res.parsedBody, "edge") + (res) => mungeGharialResponse(res.parsedBody, "edge"), ); } @@ -1076,12 +1118,17 @@ export class GraphEdgeCollection< replace( selector: documents.DocumentSelector, newValue: documents.EdgeData, - options?: ReplaceGraphDocumentOptions - ): Promise; old?: documents.Edge }>; + options?: ReplaceGraphDocumentOptions, + ): Promise< + documents.DocumentMetadata & { + new?: documents.Edge; + old?: documents.Edge; + } + >; replace( selector: documents.DocumentSelector, newValue: documents.EdgeData, - options: ReplaceGraphDocumentOptions = {} + options: ReplaceGraphDocumentOptions = {}, ) { if (typeof options === "string") { options = { rev: options }; @@ -1093,13 +1140,13 @@ export class GraphEdgeCollection< { method: "PUT", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/edge/${encodeURI(documents._documentHandle(selector, this._name))}`, body: newValue, search, headers, }, - (res) => mungeGharialResponse(res.parsedBody, "edge") + (res) => mungeGharialResponse(res.parsedBody, "edge"), ); } @@ -1138,12 +1185,17 @@ export class GraphEdgeCollection< update( selector: documents.DocumentSelector, newValue: documents.Patch>, - options?: ReplaceGraphDocumentOptions - ): Promise; old?: documents.Edge }>; + options?: ReplaceGraphDocumentOptions, + ): Promise< + documents.DocumentMetadata & { + new?: documents.Edge; + old?: documents.Edge; + } + >; update( selector: documents.DocumentSelector, newValue: documents.Patch>, - options: ReplaceGraphDocumentOptions = {} + options: ReplaceGraphDocumentOptions = {}, ) { if (typeof options === "string") { options = { rev: options }; @@ -1155,13 +1207,13 @@ export class GraphEdgeCollection< { method: "PATCH", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/edge/${encodeURI(documents._documentHandle(selector, this._name))}`, body: newValue, search, headers, }, - (res) => mungeGharialResponse(res.parsedBody, "edge") + (res) => mungeGharialResponse(res.parsedBody, "edge"), ); } @@ -1186,11 +1238,13 @@ export class GraphEdgeCollection< */ remove( selector: documents.DocumentSelector, - options?: RemoveGraphDocumentOptions - ): Promise }>; + options?: RemoveGraphDocumentOptions, + ): Promise< + documents.DocumentMetadata & { old?: documents.Edge } + >; remove( selector: documents.DocumentSelector, - options: RemoveGraphDocumentOptions = {} + options: RemoveGraphDocumentOptions = {}, ) { if (typeof options === "string") { options = { rev: options }; @@ -1202,12 +1256,12 @@ export class GraphEdgeCollection< { method: "DELETE", pathname: `/_api/gharial/${encodeURIComponent( - this.graph.name + this.graph.name, )}/edge/${encodeURI(documents._documentHandle(selector, this._name))}`, search, headers, }, - (res) => mungeGharialResponse(res.parsedBody, "removed") + (res) => mungeGharialResponse(res.parsedBody, "removed"), ); } } @@ -1297,7 +1351,7 @@ export class Graph { get(): Promise { return this._db.request( { pathname: `/_api/gharial/${encodeURIComponent(this._name)}` }, - (res) => res.parsedBody.graph + (res) => res.parsedBody.graph, ); } @@ -1324,7 +1378,7 @@ export class Graph { */ create( edgeDefinitions: EdgeDefinitionOptions[], - options: CreateGraphOptions = {} + options: CreateGraphOptions = {}, ): Promise { const { orphanCollections, satellites, waitForSync, isSmart, ...opts } = options; @@ -1341,11 +1395,14 @@ export class Graph { edgeDefinitions: edgeDefinitions.map(coerceEdgeDefinition), isSmart, name: this._name, - options: { ...opts, satellites: satellites?.map(collections.collectionToString) }, + options: { + ...opts, + satellites: satellites?.map(collections.collectionToString), + }, }, search: { waitForSync }, }, - (res) => res.parsedBody.graph + (res) => res.parsedBody.graph, ); } @@ -1370,7 +1427,7 @@ export class Graph { pathname: `/_api/gharial/${encodeURIComponent(this._name)}`, search: { dropCollections }, }, - (res) => res.parsedBody.removed + (res) => res.parsedBody.removed, ); } @@ -1382,12 +1439,12 @@ export class Graph { * @param collection - Name of the vertex collection. */ vertexCollection = any>( - collection: string | collections.ArangoCollection + collection: string | collections.ArangoCollection, ): GraphVertexCollection { return new GraphVertexCollection( this._db, collections.collectionToString(collection), - this + this, ); } @@ -1415,7 +1472,7 @@ export class Graph { listVertexCollections(): Promise { return this._db.request( { pathname: `/_api/gharial/${encodeURIComponent(this._name)}/vertex` }, - (res) => res.parsedBody.collections + (res) => res.parsedBody.collections, ); } @@ -1467,7 +1524,7 @@ export class Graph { */ addVertexCollection( collection: string | collections.ArangoCollection, - options: AddVertexCollectionOptions = {} + options: AddVertexCollectionOptions = {}, ): Promise { const { satellites, ...opts } = options; return this._db.request( @@ -1476,10 +1533,13 @@ export class Graph { pathname: `/_api/gharial/${encodeURIComponent(this._name)}/vertex`, body: { collection: collections.collectionToString(collection), - options: { ...opts, satellites: satellites?.map(collections.collectionToString) }, + options: { + ...opts, + satellites: satellites?.map(collections.collectionToString), + }, }, }, - (res) => res.parsedBody.graph + (res) => res.parsedBody.graph, ); } @@ -1507,19 +1567,19 @@ export class Graph { */ removeVertexCollection( collection: string | collections.ArangoCollection, - dropCollection: boolean = false + dropCollection: boolean = false, ): Promise { return this._db.request( { method: "DELETE", pathname: `/_api/gharial/${encodeURIComponent( - this._name + this._name, )}/vertex/${encodeURIComponent(collections.collectionToString(collection))}`, search: { dropCollection, }, }, - (res) => res.parsedBody.graph + (res) => res.parsedBody.graph, ); } @@ -1547,12 +1607,12 @@ export class Graph { * ``` */ edgeCollection = any>( - collection: string | collections.ArangoCollection + collection: string | collections.ArangoCollection, ): GraphEdgeCollection { return new GraphEdgeCollection( this._db, collections.collectionToString(collection), - this + this, ); } @@ -1580,7 +1640,7 @@ export class Graph { listEdgeCollections(): Promise { return this._db.request( { pathname: `/_api/gharial/${encodeURIComponent(this._name)}/edge` }, - (res) => res.parsedBody.collections + (res) => res.parsedBody.collections, ); } @@ -1632,7 +1692,7 @@ export class Graph { */ addEdgeDefinition( edgeDefinition: EdgeDefinitionOptions, - options: AddEdgeDefinitionOptions = {} + options: AddEdgeDefinitionOptions = {}, ): Promise { const { satellites, ...opts } = options; return this._db.request( @@ -1641,10 +1701,13 @@ export class Graph { pathname: `/_api/gharial/${encodeURIComponent(this._name)}/edge`, body: { ...coerceEdgeDefinition(edgeDefinition), - options: { ...opts, satellites: satellites?.map(collections.collectionToString) }, + options: { + ...opts, + satellites: satellites?.map(collections.collectionToString), + }, }, }, - (res) => res.parsedBody.graph + (res) => res.parsedBody.graph, ); } @@ -1675,7 +1738,7 @@ export class Graph { */ replaceEdgeDefinition( edgeDefinition: EdgeDefinitionOptions, - options?: ReplaceEdgeDefinitionOptions + options?: ReplaceEdgeDefinitionOptions, ): Promise; /** * Replaces an edge definition in this graph. The existing edge definition @@ -1706,7 +1769,7 @@ export class Graph { replaceEdgeDefinition( collection: string | collections.ArangoCollection, edgeDefinition: EdgeDefinitionOptions, - options?: ReplaceEdgeDefinitionOptions + options?: ReplaceEdgeDefinitionOptions, ): Promise; replaceEdgeDefinition( collectionOrEdgeDefinitionOptions: @@ -1716,7 +1779,7 @@ export class Graph { edgeDefinitionOrOptions?: | EdgeDefinitionOptions | ReplaceEdgeDefinitionOptions, - options: ReplaceEdgeDefinitionOptions = {} + options: ReplaceEdgeDefinitionOptions = {}, ) { let collection = collectionOrEdgeDefinitionOptions as | string @@ -1739,14 +1802,17 @@ export class Graph { { method: "PUT", pathname: `/_api/gharial/${encodeURIComponent( - this._name + this._name, )}/edge/${encodeURIComponent(collections.collectionToString(collection))}`, body: { ...coerceEdgeDefinition(edgeDefinition), - options: { ...opts, satellites: satellites?.map(collections.collectionToString) }, + options: { + ...opts, + satellites: satellites?.map(collections.collectionToString), + }, }, }, - (res) => res.parsedBody.graph + (res) => res.parsedBody.graph, ); } @@ -1774,20 +1840,20 @@ export class Graph { */ removeEdgeDefinition( collection: string | collections.ArangoCollection, - dropCollection: boolean = false + dropCollection: boolean = false, ): Promise { return this._db.request( { method: "DELETE", pathname: `/_api/gharial/${encodeURIComponent( - this._name + this._name, )}/edge/${encodeURIComponent(collections.collectionToString(collection))}`, search: { dropCollection, }, }, - (res) => res.parsedBody.graph + (res) => res.parsedBody.graph, ); } } -//#endregion \ No newline at end of file +//#endregion diff --git a/src/index.ts b/src/index.ts index e29f74c4..af5e3c1a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -34,7 +34,9 @@ if (typeof module !== "undefined" && typeof exports !== "undefined") { * }); * ``` */ -export function arangojs(config?: configuration.ConfigOptions): databases.Database; +export function arangojs( + config?: configuration.ConfigOptions, +): databases.Database; /** * Creates a new `Database` instance with its own connection pool. * @@ -49,8 +51,14 @@ export function arangojs(config?: configuration.ConfigOptions): databases.Databa * db.useBasicAuth("admin", "hunter2"); * ``` */ -export function arangojs(url: string | string[], name?: string): databases.Database; -export function arangojs(config?: string | string[] | configuration.ConfigOptions, name?: string) { +export function arangojs( + url: string | string[], + name?: string, +): databases.Database; +export function arangojs( + config?: string | string[] | configuration.ConfigOptions, + name?: string, +) { if (typeof config === "string" || Array.isArray(config)) { const url = config; return new databases.Database(url, name); diff --git a/src/indexes.ts b/src/indexes.ts index 2d63f655..e360ee00 100644 --- a/src/indexes.ts +++ b/src/indexes.ts @@ -66,7 +66,7 @@ export type EnsureIndexOptions = type EnsureIndexOptionsType< Type extends IndexType, Fields extends any[], - Extra extends {} = {} + Extra extends {} = {}, > = { /** * A unique name for this index. @@ -93,7 +93,8 @@ type EnsureIndexOptionsType< * Options for creating a persistent index. */ export type EnsurePersistentIndexOptions = EnsureIndexOptionsType< - "persistent", string[], + "persistent", + string[], { /** * If set to `true`, a unique index will be created. @@ -142,7 +143,8 @@ export type EnsurePersistentIndexOptions = EnsureIndexOptionsType< * Options for creating a geo index. */ export type EnsureGeoIndexOptions = EnsureIndexOptionsType< - "geo", [string, string] | [string], + "geo", + [string, string] | [string], { /** * If set to `true`, `fields` must be an array containing a single attribute @@ -172,7 +174,8 @@ export type EnsureGeoIndexOptions = EnsureIndexOptionsType< * Options for creating a TTL index. */ export type EnsureTtlIndexOptions = EnsureIndexOptionsType< - "ttl", [string], + "ttl", + [string], { /** * Duration in seconds after the attribute value at which the document will @@ -186,7 +189,8 @@ export type EnsureTtlIndexOptions = EnsureIndexOptionsType< * Options for creating a MDI index. */ export type EnsureMdiIndexOptions = EnsureIndexOptionsType< - "mdi", string[], + "mdi", + string[], { /** * Data type of the dimension attributes. @@ -205,7 +209,8 @@ export type EnsureMdiIndexOptions = EnsureIndexOptionsType< * Options for creating an inverted index. */ export type EnsureInvertedIndexOptions = EnsureIndexOptionsType< - "inverted", (string | InvertedIndexFieldOptions)[], + "inverted", + (string | InvertedIndexFieldOptions)[], { /** * If set to `true` array values will by default be indexed using the same @@ -502,13 +507,16 @@ export type IndexDescription = /** * An object representing a system index. */ -export type SystemIndexDescription = - | PrimaryIndexDescription; +export type SystemIndexDescription = PrimaryIndexDescription; /** * Shared attributes of all index types. */ -export type IndexDescriptionType = { +export type IndexDescriptionType< + Type extends string, + Fields extends any[], + Extra extends {} = {}, +> = { /** * A unique name for this index. */ @@ -518,12 +526,12 @@ export type IndexDescriptionType { protected _id: string; protected _db: databases.Database; - protected _transformResponse?: (res: connection.ProcessedResponse) => Promise; + protected _transformResponse?: ( + res: connection.ProcessedResponse, + ) => Promise; protected _transformError?: (error: any) => Promise; protected _loaded: boolean = false; protected _result: ResultType | undefined; @@ -29,8 +31,10 @@ export class Job { constructor( db: databases.Database, id: string, - transformResponse?: (res: connection.ProcessedResponse) => Promise, - transformError?: (error: any) => Promise + transformResponse?: ( + res: connection.ProcessedResponse, + ) => Promise, + transformError?: (error: any) => Promise, ) { this._db = db; this._id = id; @@ -91,7 +95,7 @@ export class Job { method: "PUT", pathname: `/_api/job/${this._id}`, }, - false + false, ); } catch (e) { if (this._transformError) { @@ -121,7 +125,7 @@ export class Job { method: "PUT", pathname: `/_api/job/${this._id}/cancel`, }, - () => undefined + () => undefined, ); } @@ -134,7 +138,7 @@ export class Job { method: "DELETE", pathname: `/_api/job/${this._id}`, }, - () => undefined + () => undefined, ); } @@ -159,7 +163,7 @@ export class Job { { pathname: `/_api/job/${this._id}`, }, - (res) => res.status !== 204 + (res) => res.status !== 204, ); } } diff --git a/src/lib/util.ts b/src/lib/util.ts index 357215ab..3f6fa71a 100644 --- a/src/lib/util.ts +++ b/src/lib/util.ts @@ -12,19 +12,19 @@ const THIRTY_MINUTES = 30 * 60_000; * * Helper to merge path segments. */ -export function joinPath( - ...pathList: (string | undefined)[] -): string { +export function joinPath(...pathList: (string | undefined)[]): string { if (!pathList.length) return ""; - return pathList.flatMap((path, i) => { - if (!path) return []; - if (i === pathList.length - 1) { - if (i === 0) return [path]; - return [path.replace(/^\/+/, "")]; - } - if (i === 0) return [path.replace(/\/+$/, "")]; - return [path.replace(/^\/+|\/+$/, "")]; - }).join("/"); + return pathList + .flatMap((path, i) => { + if (!path) return []; + if (i === pathList.length - 1) { + if (i === 0) return [path]; + return [path.replace(/^\/+/, "")]; + } + if (i === 0) return [path.replace(/\/+$/, "")]; + return [path.replace(/^\/+|\/+$/, "")]; + }) + .join("/"); } /** @@ -33,13 +33,24 @@ export function joinPath( * Utility function for merging headers. */ export function mergeHeaders( - ...headersList: (Headers | string[][] | Record> | undefined)[] + ...headersList: ( + | Headers + | string[][] + | Record> + | undefined + )[] ) { if (!headersList.length) return new Headers(); return new Headers([ - ...headersList.flatMap(headers => headers ? [ - ...((headers instanceof Headers || Array.isArray(headers)) ? headers : new Headers(headers)) - ] : []), + ...headersList.flatMap((headers) => + headers + ? [ + ...(headers instanceof Headers || Array.isArray(headers) + ? headers + : new Headers(headers)), + ] + : [], + ), ]); } @@ -53,7 +64,7 @@ export function normalizeUrl(url: string): string { if (raw) url = (raw[1] === "tcp" ? "http" : "https") + raw[2]; const unix = url.match(/^(?:(http|https)\+)?unix:\/\/(\/.+)/); if (unix) url = `${unix[1] || "http"}://unix:${unix[2]}`; - else if (!url.endsWith('/')) url += '/'; + else if (!url.endsWith("/")) url += "/"; return url; } diff --git a/src/lib/x3-linkedlist.ts b/src/lib/x3-linkedlist.ts index 7678bdb0..66a1cdd7 100644 --- a/src/lib/x3-linkedlist.ts +++ b/src/lib/x3-linkedlist.ts @@ -51,7 +51,7 @@ export class LinkedListItem { /** *Function to run on unlink() call. Usually used by LinkedList to fix first and last pointers and reduce length. */ - protected unlinkCleanup?: (item: LinkedListItem) => void + protected unlinkCleanup?: (item: LinkedListItem) => void, ) {} /** @@ -60,7 +60,7 @@ export class LinkedListItem { */ public insertBehind( /** LinkListItem to be inserted behind this one */ - item: LinkedListItem + item: LinkedListItem, ): void { item.insertBefore(this); @@ -80,7 +80,7 @@ export class LinkedListItem { */ public unlink( /** If true, additionally removes the reference to the item before and behind */ - unchain = false + unchain = false, ): void { if (this.before) this.before.behind = this.behind; @@ -105,7 +105,7 @@ export class LinkedListItem { */ protected insertBefore( /** LinkListItem to be inserted before this one */ - before: LinkedListItem + before: LinkedListItem, ): void { this.before = before; if (!this.unlinkCleanup) { @@ -137,7 +137,7 @@ export class LinkedList { constructor( /** Values to be added initially into list */ - values?: Iterable | LinkedList + values?: Iterable | LinkedList, ) { if (values) { if (values instanceof LinkedList) values = values.values(); @@ -160,7 +160,7 @@ export class LinkedList { */ public clear( /** If `true`, remove link info from every item. Changes complexity to O(n)! */ - unchain = false + unchain = false, ): void { if (unchain) { while (this.first) { @@ -181,7 +181,7 @@ export class LinkedList { /** Runs for every item in the LinkedList */ callback: (value: T, item: LinkedListItem, list: this) => boolean, /** If given, callback function will be bound to thisArg */ - thisArg?: C + thisArg?: C, ): boolean { if (thisArg) { callback = callback.bind(thisArg); @@ -203,7 +203,7 @@ export class LinkedList { /** decides wether given element should be part of new LinkedList */ callback: (value: T, item: LinkedListItem, list: this) => boolean, /** If given, callback function will be bound to thisArg */ - thisArg?: C + thisArg?: C, ): LinkedList { if (thisArg) { callback = callback.bind(thisArg); @@ -226,7 +226,7 @@ export class LinkedList { /** runs for every value in LinkedList. If it returns truthy, current value is returned. */ callback: (value: T, item: LinkedListItem, list: this) => boolean, /** If given, callback function will be bound to thisArg */ - thisArg?: C + thisArg?: C, ): T | undefined { if (thisArg) { callback = callback.bind(thisArg); @@ -249,7 +249,7 @@ export class LinkedList { /** runs for every LinkedListItem in LinkedList. If it returns truthy, current LinkedListItem is returned. */ callback: (value: T, item: LinkedListItem, list: this) => boolean, /** If given, callback function will be bound to thisArg */ - thisArg?: C + thisArg?: C, ): LinkedListItem | undefined { if (thisArg) { callback = callback.bind(thisArg); @@ -272,7 +272,7 @@ export class LinkedList { /** Gets every value in LinkedList once with corresponding LinkedListItem and LinkedList */ callback: (value: T, item: LinkedListItem, list: this) => void, /** If given, callback function will be bound to thisArg */ - thisArg?: C + thisArg?: C, ): void { if (thisArg) { callback = callback.bind(thisArg); @@ -291,7 +291,7 @@ export class LinkedList { /** value to be found in this */ value: T, /** Starting index. Supports negative values for which `this.size - 1 + fromIndex` will be used as starting point. */ - fromIndex = 0 + fromIndex = 0, ): boolean { let current = this.getItemByIndex(fromIndex); while (current) { @@ -311,7 +311,7 @@ export class LinkedList { /** Value to be found */ searchedValue: T, /** Index to start from */ - fromIndex = 0 + fromIndex = 0, ): LinkedListItem | undefined { let current = this.getItemByIndex(fromIndex); while (current) { @@ -331,7 +331,7 @@ export class LinkedList { /** Value to be found */ searchedValue: T, /** Index to start from */ - fromIndex = -1 + fromIndex = -1, ): LinkedListItem | undefined { let current = this.getItemByIndex(fromIndex); while (current) { @@ -351,7 +351,7 @@ export class LinkedList { /** Gets value, LinkedListeItem and LinkedList. The response will be used as value in the new LinkedList */ callback: (value: T, item: LinkedListItem, list: this) => V, /** If given, callback function will be bound to thisArg */ - thisArg?: C + thisArg?: C, ): LinkedList { if (thisArg) { callback = callback.bind(thisArg); @@ -378,8 +378,8 @@ export class LinkedList { accumulator: T, currentValue: T, currentItem: LinkedListItem, - list: this - ) => V + list: this, + ) => V, ): V; public reduce( /** @@ -390,25 +390,25 @@ export class LinkedList { accumulator: V, currentValue: T, currentItem: LinkedListItem, - list: this + list: this, ) => V, /** Value for the first call of callback */ - initialValue: V + initialValue: V, ): V; public reduce( callback: ( accumulator: V | T, currentValue: T, currentItem: LinkedListItem, - list: this + list: this, ) => V, - initialValue?: V | T + initialValue?: V | T, ): V | T { let current = this.first; if (!current) { if (!initialValue) { throw new TypeError( - "Empty accumulator on empty LinkedList is not allowed." + "Empty accumulator on empty LinkedList is not allowed.", ); } return initialValue; @@ -445,8 +445,8 @@ export class LinkedList { accumulator: T, currentValue: T, currentItem: LinkedListItem, - list: this - ) => V + list: this, + ) => V, ): V; public reduceRight( /** @@ -457,25 +457,25 @@ export class LinkedList { accumulator: V, currentValue: T, currentItem: LinkedListItem, - list: this + list: this, ) => V, /** Value for the first call of callback */ - initialValue: V + initialValue: V, ): V; public reduceRight( callback: ( accumulator: V | T, currentValue: T, currentItem: LinkedListItem, - list: this + list: this, ) => V, - initialValue?: V | T + initialValue?: V | T, ): V | T { let current = this.last; if (!current) { if (!initialValue) { throw new TypeError( - "Empty accumulator on empty LinkedList is not allowed." + "Empty accumulator on empty LinkedList is not allowed.", ); } return initialValue; @@ -503,7 +503,7 @@ export class LinkedList { /** called for every element. If response is truthy, this currentvalue will be returned by `.some()`. */ callback: (currentValue: T, item: LinkedListItem, list: this) => boolean, /** If given, callback function will be bound to thisArg */ - thisArg?: C + thisArg?: C, ): boolean { if (thisArg) { callback = callback.bind(thisArg); @@ -522,7 +522,7 @@ export class LinkedList { */ public join( /** separator between items in the resulting string */ - separator?: string + separator?: string, ): string { return [...this.values()].join(separator); } @@ -604,7 +604,7 @@ export class LinkedList { */ public remove( /** value to remove once */ - value: T + value: T, ): boolean { for (const item of this.keys()) { if (item.value === value) { @@ -621,7 +621,7 @@ export class LinkedList { */ public removeAllOccurrences( /** value to remove completely */ - value: T + value: T, ): boolean { let foundSomethingToDelete = false; @@ -704,7 +704,7 @@ export class LinkedList { */ private getItemByIndex( /** Index of item to get from list */ - index: number + index: number, ): LinkedListItem | undefined { if (index === undefined) { throw new Error("index must be a number!"); @@ -738,7 +738,7 @@ export class LinkedList { */ private unlinkCleanup = ( /** Item that has been unlinked */ - item: LinkedListItem + item: LinkedListItem, ): void => { if (this.first === item) { this.first = this.first.behind; diff --git a/src/logs.ts b/src/logs.ts index ea2bbca0..f4f65419 100644 --- a/src/logs.ts +++ b/src/logs.ts @@ -101,4 +101,4 @@ export type LogEntries = { timestamp: number[]; text: string[]; }; -//#endregion \ No newline at end of file +//#endregion diff --git a/src/queries.ts b/src/queries.ts index b0769424..04fe41a0 100644 --- a/src/queries.ts +++ b/src/queries.ts @@ -510,4 +510,4 @@ export type UserFunctionDescription = { */ isDeterministic: boolean; }; -//#endregion \ No newline at end of file +//#endregion diff --git a/src/routes.ts b/src/routes.ts index 97c7c1f3..c63f62c4 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -26,7 +26,7 @@ export class Route { constructor( db: databases.Database, pathname: string = "", - headers: Headers | Record = {} + headers: Headers | Record = {}, ) { if (!pathname) pathname = ""; else if (pathname.charAt(0) !== "/") pathname = `/${pathname}`; @@ -74,7 +74,7 @@ export class Route { return new Route( this._db, util.joinPath(this._pathname, pathname), - util.mergeHeaders(this._headers, headers) + util.mergeHeaders(this._headers, headers), ); } @@ -100,12 +100,15 @@ export class Route { */ request(options: connections.RequestOptions = {}) { const { method = "GET", pathname, headers, ...opts } = options; - return this._db.request({ - ...opts, - method: method.toUpperCase(), - pathname: util.joinPath(this._pathname, pathname), - headers: util.mergeHeaders(this._headers, headers), - }, false); + return this._db.request( + { + ...opts, + method: method.toUpperCase(), + pathname: util.joinPath(this._pathname, pathname), + headers: util.mergeHeaders(this._headers, headers), + }, + false, + ); } /** @@ -126,7 +129,7 @@ export class Route { delete( pathname: string, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; /** * Performs a DELETE request against the given path relative to this route @@ -145,7 +148,7 @@ export class Route { */ delete( search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; delete(...args: any[]): Promise { const pathname = typeof args[0] === "string" ? args.shift() : undefined; @@ -171,7 +174,7 @@ export class Route { get( pathname: string, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; /** * Performs a GET request against the given path relative to this route @@ -190,7 +193,7 @@ export class Route { */ get( search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; get(...args: any[]): Promise { const pathname = typeof args[0] === "string" ? args.shift() : undefined; @@ -216,7 +219,7 @@ export class Route { head( pathname: string, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; /** * Performs a HEAD request against the given path relative to this route @@ -235,7 +238,7 @@ export class Route { */ head( search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; head(...args: any[]): Promise { const pathname = typeof args[0] === "string" ? args.shift() : undefined; @@ -263,7 +266,7 @@ export class Route { pathname: string, body?: any, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; /** * Performs a PATCH request against the given path relative to this route @@ -286,7 +289,7 @@ export class Route { patch( body?: any, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; patch(...args: any[]): Promise { const pathname = typeof args[0] === "string" ? args.shift() : undefined; @@ -317,7 +320,7 @@ export class Route { pathname: string, body?: any, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; /** * Performs a POST request against the given path relative to this route @@ -343,7 +346,7 @@ export class Route { post( body?: any, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; post(...args: any[]): Promise { const pathname = typeof args[0] === "string" ? args.shift() : undefined; @@ -371,7 +374,7 @@ export class Route { pathname: string, body?: any, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; /** * Performs a PUT request against the given path relative to this route @@ -394,7 +397,7 @@ export class Route { put( body?: any, search?: URLSearchParams | Record, - headers?: Headers | Record + headers?: Headers | Record, ): Promise; put(...args: any[]): Promise { const pathname = typeof args[0] === "string" ? args.shift() : undefined; diff --git a/src/services.ts b/src/services.ts index 6e14f0a4..0a646b33 100644 --- a/src/services.ts +++ b/src/services.ts @@ -232,14 +232,14 @@ export type ServiceConfiguration = { * by software when managing the service. */ type: - | "integer" - | "boolean" - | "string" - | "number" - | "json" - | "password" - | "int" - | "bool"; + | "integer" + | "boolean" + | "string" + | "number" + | "json" + | "password" + | "int" + | "bool"; /** * Current value of the configuration option as stored internally. */ @@ -436,10 +436,10 @@ export type ServiceTestXunitReport = [ export type ServiceTestXunitTest = | ["testcase", { classname: string; name: string; time: number }] | [ - "testcase", - { classname: string; name: string; time: number }, - ["failure", { message: string; type: string }, string], - ]; + "testcase", + { classname: string; name: string; time: number }, + ["failure", { message: string; type: string }, string], + ]; /** * Test results for a Foxx service's tests in TAP format. @@ -535,4 +535,4 @@ export type ServiceDescription = { dependencies: Record; }; }; -//#endregion \ No newline at end of file +//#endregion diff --git a/src/test/00-basics.ts b/src/test/00-basics.ts index 43de2a9b..cf7d4d69 100644 --- a/src/test/00-basics.ts +++ b/src/test/00-basics.ts @@ -39,7 +39,7 @@ describe("Configuring the driver", () => { "x-one": "1", "x-two": "2", }, - } + }, }); (db as any)._connection._hosts = [ { @@ -48,10 +48,10 @@ describe("Configuring the driver", () => { expect(headers.get("x-two")).to.equal("2"); done(); }, - close: () => { }, + close: () => {}, }, ]; - db.request({ headers: {} }, () => { }); + db.request({ headers: {} }, () => {}); }); }); describe("with an arangoVersion", () => { @@ -63,10 +63,10 @@ describe("Configuring the driver", () => { expect(headers.get("x-arango-version")).to.equal("99999"); done(); }, - close: () => { }, + close: () => {}, }, ]; - db.request({ headers: {} }, () => { }); + db.request({ headers: {} }, () => {}); }); }); }); diff --git a/src/test/01-manipulating-databases.ts b/src/test/01-manipulating-databases.ts index 93eccf81..fb3e8464 100644 --- a/src/test/01-manipulating-databases.ts +++ b/src/test/01-manipulating-databases.ts @@ -77,7 +77,7 @@ describe("Manipulating databases", function () { after(async () => { try { await system.dropDatabase(name); - } catch { } + } catch {} }); it("deletes the given database from the server", async () => { await system.dropDatabase(name); diff --git a/src/test/02-accessing-collections.ts b/src/test/02-accessing-collections.ts index 2217ff2f..b3b119ca 100644 --- a/src/test/02-accessing-collections.ts +++ b/src/test/02-accessing-collections.ts @@ -34,7 +34,7 @@ describe("Accessing collections", function () { }); describe("database.listCollections", () => { const nonSystemCollectionNames = range(4).map( - (i) => `c_${Date.now()}_${i}` + (i) => `c_${Date.now()}_${i}`, ); const systemCollectionNames = range(4).map((i) => `_c_${Date.now()}_${i}`); before(async () => { @@ -43,7 +43,7 @@ describe("Accessing collections", function () { const collection = await db.createCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ...systemCollectionNames.map(async (name) => { @@ -51,7 +51,7 @@ describe("Accessing collections", function () { await collection.create({ isSystem: true }); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ] as Promise[]); @@ -60,7 +60,7 @@ describe("Accessing collections", function () { await Promise.all([ ...nonSystemCollectionNames.map((name) => db.collection(name).drop()), ...systemCollectionNames.map((name) => - db.collection(name).drop({ isSystem: true }) + db.collection(name).drop({ isSystem: true }), ), ]); }); @@ -68,7 +68,7 @@ describe("Accessing collections", function () { const collections = await db.listCollections(); expect(collections.length).to.equal(nonSystemCollectionNames.length); expect(collections.map((c: any) => c.name).sort()).to.eql( - nonSystemCollectionNames + nonSystemCollectionNames, ); }); it("includes system collections if explicitly passed false", async () => { @@ -79,13 +79,13 @@ describe("Accessing collections", function () { .sort(); expect(collections.length).to.be.at.least(allCollectionNames.length); expect(collections.map((c: any) => c.name).sort()).to.eql( - allCollectionNames + allCollectionNames, ); }); }); describe("database.collections", () => { const documentCollectionNames = range(4).map( - (i) => `dc_${Date.now()}_${i}` + (i) => `dc_${Date.now()}_${i}`, ); const edgeCollectionNames = range(4).map((i) => `ec_${Date.now()}_${i}`); const systemCollectionNames = range(4).map((i) => `_c_${Date.now()}_${i}`); @@ -95,14 +95,14 @@ describe("Accessing collections", function () { const collection = await db.createCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ...edgeCollectionNames.map(async (name) => { const collection = await db.createEdgeCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ...systemCollectionNames.map(async (name) => { @@ -110,7 +110,7 @@ describe("Accessing collections", function () { await collection.create({ isSystem: true }); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ] as Promise[]); @@ -120,17 +120,17 @@ describe("Accessing collections", function () { ...documentCollectionNames.map((name) => db.collection(name).drop()), ...edgeCollectionNames.map((name) => db.collection(name).drop()), ...systemCollectionNames.map((name) => - db.collection(name).drop({ isSystem: true }) + db.collection(name).drop({ isSystem: true }), ), ]); }); it("creates Collection instances", async () => { const collections = await db.collections(); expect(collections.length).to.equal( - documentCollectionNames.length + edgeCollectionNames.length + documentCollectionNames.length + edgeCollectionNames.length, ); expect(collections.map((c) => c.name).sort()).to.eql( - [...documentCollectionNames, ...edgeCollectionNames].sort() + [...documentCollectionNames, ...edgeCollectionNames].sort(), ); }); it("includes system collections if explicitly passed false", async () => { @@ -142,7 +142,7 @@ describe("Accessing collections", function () { ...builtinSystemCollections, ].sort(); expect(collections.map((c: any) => c.name).sort()).to.eql( - allCollectionNames + allCollectionNames, ); }); }); diff --git a/src/test/03-accessing-graphs.ts b/src/test/03-accessing-graphs.ts index 249d78be..84901624 100644 --- a/src/test/03-accessing-graphs.ts +++ b/src/test/03-accessing-graphs.ts @@ -39,14 +39,14 @@ describe("Accessing graphs", function () { const collection = await db.createCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ...edgeCollectionNames.map(async (name) => { const collection = await db.createEdgeCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ] as Promise[]); @@ -58,11 +58,11 @@ describe("Accessing graphs", function () { collection: name, from: vertexCollectionNames, to: vertexCollectionNames, - })) + })), ); await db.waitForPropagation( { pathname: `/_api/gharial/${graph.name}` }, - 10000 + 10000, ); }), ]); @@ -72,7 +72,7 @@ describe("Accessing graphs", function () { await Promise.all( vertexCollectionNames .concat(edgeCollectionNames) - .map((name) => db.collection(name).drop()) + .map((name) => db.collection(name).drop()), ); }); it("fetches information about all graphs", async () => { @@ -91,14 +91,14 @@ describe("Accessing graphs", function () { const collection = await db.createCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ...edgeCollectionNames.map(async (name) => { const collection = await db.createEdgeCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ] as Promise[]); @@ -110,11 +110,11 @@ describe("Accessing graphs", function () { collection: name, from: vertexCollectionNames, to: vertexCollectionNames, - })) + })), ); await db.waitForPropagation( { pathname: `/_api/gharial/${graph.name}` }, - 10000 + 10000, ); }), ]); @@ -124,7 +124,7 @@ describe("Accessing graphs", function () { await Promise.all( vertexCollectionNames .concat(edgeCollectionNames) - .map((name) => db.collection(name).drop()) + .map((name) => db.collection(name).drop()), ); }); it("creates Graph instances", async () => { diff --git a/src/test/04-transactions.ts b/src/test/04-transactions.ts index d853e2af..f97bf313 100644 --- a/src/test/04-transactions.ts +++ b/src/test/04-transactions.ts @@ -27,7 +27,7 @@ describe("Transactions", () => { const result = await db.executeTransaction( [], "function (params) {return params;}", - { params: "test" } + { params: "test" }, ); expect(result).to.equal("test"); }); @@ -44,8 +44,8 @@ describe("Transactions", () => { after(async () => { await Promise.all( allTransactions.map((transaction) => - transaction.abort().catch(() => undefined) - ) + transaction.abort().catch(() => undefined), + ), ); await system.dropDatabase(name); }); @@ -53,7 +53,7 @@ describe("Transactions", () => { collection = await db.createCollection(`collection-${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); afterEach(async () => { @@ -127,7 +127,7 @@ describe("Transactions", () => { let doc: any; try { doc = await collection.document("test"); - } catch (e: any) { } + } catch (e: any) {} if (doc) expect.fail("Document should not exist yet."); const { id, status } = await trx.commit(); expect(id).to.equal(trx.id); @@ -142,11 +142,11 @@ describe("Transactions", () => { let doc: any; try { doc = await collection.document("test1"); - } catch (e: any) { } + } catch (e: any) {} if (doc) expect.fail("Document should not exist yet."); try { doc = await collection.document("test2"); - } catch (e: any) { } + } catch (e: any) {} if (doc) expect.fail("Document should not exist yet."); const { id, status } = await trx.commit(); expect(id).to.equal(trx.id); @@ -164,7 +164,7 @@ describe("Transactions", () => { let doc: any; try { doc = await collection.document("test"); - } catch (e: any) { } + } catch (e: any) {} if (doc) expect.fail("Document should not exist yet."); }); diff --git a/src/test/05-aql-helpers.ts b/src/test/05-aql-helpers.ts index f65ab3e3..8c2edc30 100644 --- a/src/test/05-aql-helpers.ts +++ b/src/test/05-aql-helpers.ts @@ -20,10 +20,10 @@ describe("AQL helpers", function () { ]; const query = aql`A ${values[0]} B ${values[1]} C ${values[2]} D ${values[3]} E ${values[4]} F ${values[5]} G ${values[6]} H ${values[7]} I ${values[8]} J ${values[9]} K EOF`; expect(query.query).to.equal( - `A @value0 B @value1 C @value2 D @value3 E @value4 F @value5 G @value6 H @value7 I @value8 J @value9 K EOF` + `A @value0 B @value1 C @value2 D @value3 E @value4 F @value5 G @value6 H @value7 I @value8 J @value9 K EOF`, ); const bindVarNames = Object.keys(query.bindVars).sort((a, b) => - +a.substr(5) > +b.substr(5) ? 1 : -1 + +a.substr(5) > +b.substr(5) ? 1 : -1, ); expect(bindVarNames).to.eql([ "value0", @@ -41,7 +41,7 @@ describe("AQL helpers", function () { }); it("omits undefined bindvars and empty queries", () => { const query = aql`A ${undefined} B ${aql``} C ${join([])} D ${literal( - "" + "", )} E`; expect(query.query).to.equal("A B C D E"); expect(query.bindVars).to.eql({}); @@ -111,20 +111,20 @@ describe("AQL helpers", function () { it("supports nesting simple queries", () => { const query = aql`FOR x IN (${aql`FOR a IN 1..3 RETURN a`}) RETURN x`; expect(query.query).to.equal( - "FOR x IN (FOR a IN 1..3 RETURN a) RETURN x" + "FOR x IN (FOR a IN 1..3 RETURN a) RETURN x", ); }); it("supports deeply nesting simple queries", () => { const query = aql`FOR x IN (${aql`FOR a IN (${aql`FOR b IN 1..3 RETURN b`}) RETURN a`}) RETURN x`; expect(query.query).to.equal( - "FOR x IN (FOR a IN (FOR b IN 1..3 RETURN b) RETURN a) RETURN x" + "FOR x IN (FOR a IN (FOR b IN 1..3 RETURN b) RETURN a) RETURN x", ); }); it("supports nesting with bindVars", () => { const collection = db.collection("paprika"); const query = aql`A ${collection} B ${aql`X ${collection} Y ${aql`J ${collection} K ${9} L`} Z`} C ${4}`; expect(query.query).to.equal( - "A @@value0 B X @@value0 Y J @@value0 K @value1 L Z C @value2" + "A @@value0 B X @@value0 Y J @@value0 K @value1 L Z C @value2", ); expect(query.bindVars).to.eql({ "@value0": "paprika", @@ -138,7 +138,7 @@ describe("AQL helpers", function () { const filter = aql`FILTER u.role == ${role}`; const query = aql`FOR u IN ${users} ${filter} RETURN u`; expect(query.query).to.equal( - "FOR u IN @@value0 FILTER u.role == @value1 RETURN u" + "FOR u IN @@value0 FILTER u.role == @value1 RETURN u", ); expect(query.bindVars).to.eql({ "@value0": users.name, @@ -153,7 +153,7 @@ describe("AQL helpers", function () { it("supports deep nesting", () => { const query = aql`A ${1} ${aql`a ${2} ${aql`X ${3} ${aql`x ${4} y`} ${5} Y`} ${6} b`} ${7} B`; expect(query.query).to.equal( - "A @value0 a @value1 X @value2 x @value3 y @value4 Y @value5 b @value6 B" + "A @value0 a @value1 X @value2 x @value3 y @value4 Y @value5 b @value6 B", ); expect(query.bindVars).to.eql({ value0: 1, @@ -185,7 +185,7 @@ describe("AQL helpers", function () { ]; for (const [value, result] of pairs) { it(`returns an AQL literal of "${result}" for ${String( - JSON.stringify(value) + JSON.stringify(value), )}`, () => { expect(literal(value).toAQL()).to.equal(result); }); diff --git a/src/test/06-managing-functions.ts b/src/test/06-managing-functions.ts index 19785aed..4e8f30dc 100644 --- a/src/test/06-managing-functions.ts +++ b/src/test/06-managing-functions.ts @@ -41,7 +41,7 @@ describe("Managing functions", function () { it("should create a function", async () => { const info = await db.createUserFunction( "myfunctions::temperature::celsiustofahrenheit2", - "function (celsius) { return celsius * 1.8 + 32; }" + "function (celsius) { return celsius * 1.8 + 32; }", ); expect(info).to.have.property("code", 201); expect(info).to.have.property("error", false); @@ -52,7 +52,7 @@ describe("Managing functions", function () { const name = "myfunctions::temperature::celsiustofahrenheit"; await db.createUserFunction( name, - "function (celsius) { return celsius * 1.8 + 32; }" + "function (celsius) { return celsius * 1.8 + 32; }", ); const info = await db.dropUserFunction(name); expect(info).to.have.property("deletedCount", 1); diff --git a/src/test/07-routes.ts b/src/test/07-routes.ts index ab12e49e..12853c77 100644 --- a/src/test/07-routes.ts +++ b/src/test/07-routes.ts @@ -39,7 +39,7 @@ describe("Route API", function () { collection = await db.createCollection(`c_${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); after(async () => { diff --git a/src/test/08-cursors.ts b/src/test/08-cursors.ts index dabdb016..6d1ccba3 100644 --- a/src/test/08-cursors.ts +++ b/src/test/08-cursors.ts @@ -28,7 +28,7 @@ describe("Item-wise Cursor API", () => { }); after(async () => { await Promise.all( - allCursors.map((cursor) => cursor.kill().catch(() => undefined)) + allCursors.map((cursor) => cursor.kill().catch(() => undefined)), ); try { await system.dropDatabase(name); @@ -199,7 +199,7 @@ describe("Item-wise Cursor API", () => { .reduce((acc, next) => { acc.push(...next); return acc; - }, [] as number[]) + }, [] as number[]), ); }); it("doesn't choke on non-arrays", async () => { @@ -252,7 +252,7 @@ describe("Batch-wise Cursor API", () => { }); after(async () => { await Promise.all( - allCursors.map((cursor) => cursor.kill().catch(() => undefined)) + allCursors.map((cursor) => cursor.kill().catch(() => undefined)), ); try { await system.dropDatabase(name); @@ -395,7 +395,7 @@ describe("Batch-wise Cursor API", () => { .reduce((acc, next) => { acc.push(...next); return acc; - }, [] as number[]) + }, [] as number[]), ); }); it("doesn't choke on non-arrays", async () => { diff --git a/src/test/09-collection-metadata.ts b/src/test/09-collection-metadata.ts index 3317ed73..bbbe7fe6 100644 --- a/src/test/09-collection-metadata.ts +++ b/src/test/09-collection-metadata.ts @@ -18,7 +18,7 @@ describe("Collection metadata", function () { collection = await db.createCollection(collectionName); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); after(async () => { diff --git a/src/test/10-manipulating-collections.ts b/src/test/10-manipulating-collections.ts index 3de70f40..f53908c8 100644 --- a/src/test/10-manipulating-collections.ts +++ b/src/test/10-manipulating-collections.ts @@ -24,7 +24,7 @@ describe("Manipulating collections", function () { collection = await db.createCollection(`collection-${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); afterEach(async () => { @@ -38,11 +38,11 @@ describe("Manipulating collections", function () { describe("collection.create", () => { it("creates a new document collection", async () => { const collection = await db.createCollection( - `document-collection-${Date.now()}` + `document-collection-${Date.now()}`, ); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); const info = await db.collection(collection.name).get(); expect(info).to.have.property("name", collection.name); @@ -52,11 +52,11 @@ describe("Manipulating collections", function () { }); it("creates a new edge collection", async () => { const collection = await db.createEdgeCollection( - `edge-collection-${Date.now()}` + `edge-collection-${Date.now()}`, ); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); const info = await db.collection(collection.name).get(); expect(info).to.have.property("name", collection.name); diff --git a/src/test/11-managing-indexes.ts b/src/test/11-managing-indexes.ts index 1ddeea9f..f3ca332d 100644 --- a/src/test/11-managing-indexes.ts +++ b/src/test/11-managing-indexes.ts @@ -19,7 +19,7 @@ describe("Managing indexes", function () { collection = await db.createCollection(collectionName); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); after(async () => { diff --git a/src/test/13-bulk-imports.ts b/src/test/13-bulk-imports.ts index fbed560d..31494d2b 100644 --- a/src/test/13-bulk-imports.ts +++ b/src/test/13-bulk-imports.ts @@ -17,7 +17,7 @@ describe("Bulk imports", function () { collection = await db.createCollection(collectionName); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); after(async () => { @@ -77,7 +77,7 @@ describe("Bulk imports", function () { }); it("should accept buffer of LDJSON arrays", async () => { const data = Buffer.from( - '["_key", "data"]\r\n["tb1", "banana"]\r\n["tb2", "peach"]\r\n["tb3", "apricot"]\r\n' + '["_key", "data"]\r\n["tb1", "banana"]\r\n["tb2", "peach"]\r\n["tb3", "apricot"]\r\n', ); const info = await collection.import(data); expect(info).to.eql({ @@ -106,7 +106,7 @@ describe("Bulk imports", function () { }); it("should accept buffer of LDJSON documents", async () => { const data = Buffer.from( - `{"_key": "db1-${type}", "data": "banana"}\r\n{"_key": "db2-${type}", "data": "peach"}\r\n{"_key": "db3-${type}", "data": "apricot"}\r\n` + `{"_key": "db1-${type}", "data": "banana"}\r\n{"_key": "db2-${type}", "data": "peach"}\r\n{"_key": "db3-${type}", "data": "apricot"}\r\n`, ); const info = await collection.import(data, { type }); expect(info).to.eql({ @@ -144,7 +144,7 @@ describe("Bulk imports", function () { { _key: `jb1-${String(type)}`, data: "banana" }, { _key: `jb2-${String(type)}`, data: "peach" }, { _key: `jb3-${String(type)}`, data: "apricot" }, - ]) + ]), ); const info = await collection.import(data, { type }); expect(info).to.eql({ diff --git a/src/test/14-document-collections.ts b/src/test/14-document-collections.ts index 4bd44bf0..9ebede18 100644 --- a/src/test/14-document-collections.ts +++ b/src/test/14-document-collections.ts @@ -25,7 +25,7 @@ describe("DocumentCollection API", function () { collection = await db.createCollection(`c_${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); afterEach(async () => { @@ -177,7 +177,7 @@ describe("DocumentCollection API", function () { await collection.update( doc, { sup: "dawg", empty: null }, - { keepNull: false } + { keepNull: false }, ); const newData = await collection.document(doc._key); expect(newData).to.have.property("potato").that.equals(doc.potato); diff --git a/src/test/15-edge-collections.ts b/src/test/15-edge-collections.ts index 2dd3c5f5..5a8811ed 100644 --- a/src/test/15-edge-collections.ts +++ b/src/test/15-edge-collections.ts @@ -29,7 +29,7 @@ describe("EdgeCollection API", function () { collection = await db.createEdgeCollection(`c_${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); afterEach(async () => { @@ -110,7 +110,7 @@ describe("EdgeCollection API", function () { "_id", "_rev", "_from", - "_to" + "_to", ); expect(doc._id).to.equal(meta._id); expect(doc._key).to.equal(meta._key); @@ -138,7 +138,7 @@ describe("EdgeCollection API", function () { "_id", "_rev", "_from", - "_to" + "_to", ); expect(doc._id).to.equal(meta._id); expect(doc._rev).to.equal(meta._rev); @@ -163,7 +163,7 @@ describe("EdgeCollection API", function () { "_id", "_rev", "_from", - "_to" + "_to", ); expect(doc.something).to.equal(data.something); expect(doc._id).to.equal(meta._id); @@ -216,7 +216,7 @@ describe("EdgeCollection API", function () { await collection.update( doc, { more: "peanuts", empty: null }, - { keepNull: false } + { keepNull: false }, ); const newData = await collection.document(doc._key); expect(newData).to.have.property("something", doc.something); diff --git a/src/test/16-graphs.ts b/src/test/16-graphs.ts index e60019ca..8cbba180 100644 --- a/src/test/16-graphs.ts +++ b/src/test/16-graphs.ts @@ -13,14 +13,14 @@ async function createCollections(db: Database) { const collection = await db.createCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ...edgeCollectionNames.map(async (name) => { const collection = await db.createEdgeCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ] as Promise[]); @@ -30,14 +30,14 @@ async function createCollections(db: Database) { async function createGraph( graph: Graph, vertexCollectionNames: string[], - edgeCollectionNames: string[] + edgeCollectionNames: string[], ) { return await graph.create( edgeCollectionNames.map((name) => ({ collection: name, from: vertexCollectionNames, to: vertexCollectionNames, - })) + })), ); } @@ -69,7 +69,7 @@ describe("Graph API", function () { after(async () => { await graph.drop(); await Promise.all( - collectionNames.map((name) => db.collection(name).drop()) + collectionNames.map((name) => db.collection(name).drop()), ); }); it("fetches information about the graph", async () => { @@ -90,12 +90,12 @@ describe("Graph API", function () { ...edgeCollectionNames.map(async (name) => { try { await graph.removeEdgeDefinition(name, true); - } catch { } + } catch {} }), ...vertexCollectionNames.map(async (name) => { try { await graph.removeVertexCollection(name, true); - } catch { } + } catch {} }), ]); }); @@ -106,11 +106,11 @@ describe("Graph API", function () { collection: name, from: vertexCollectionNames, to: vertexCollectionNames, - })) + })), ); await db.waitForPropagation( { pathname: `/_api/gharial/${graph.name}` }, - 10000 + 10000, ); const data = await graph.get(); expect(data).to.have.property("name", graph.name); @@ -132,8 +132,8 @@ describe("Graph API", function () { db .collection(name) .drop() - .catch(() => null) - ) + .catch(() => null), + ), ); }); it("destroys the graph if not passed true", async () => { diff --git a/src/test/17-graph-vertices.ts b/src/test/17-graph-vertices.ts index fa884e4c..f83c786a 100644 --- a/src/test/17-graph-vertices.ts +++ b/src/test/17-graph-vertices.ts @@ -15,14 +15,14 @@ async function createCollections(db: Database) { const collection = await db.createCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ...edgeCollectionNames.map(async (name) => { const collection = await db.createEdgeCollection(name); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }), ] as Promise[]); @@ -32,18 +32,18 @@ async function createCollections(db: Database) { async function createGraph( graph: Graph, vertexCollectionNames: string[], - edgeCollectionNames: string[] + edgeCollectionNames: string[], ) { const result = await graph.create( edgeCollectionNames.map((name) => ({ collection: name, from: vertexCollectionNames, to: vertexCollectionNames, - })) + })), ); await graph.database.waitForPropagation( { pathname: `/_api/gharial/${graph.name}` }, - 10000 + 10000, ); return result; } @@ -75,7 +75,7 @@ describe("Manipulating graph vertices", function () { afterEach(async () => { await graph.drop(); await Promise.all( - collectionNames.map((name) => db.collection(name).drop()) + collectionNames.map((name) => db.collection(name).drop()), ); }); describe("graph.vertexCollection", () => { @@ -92,7 +92,7 @@ describe("Manipulating graph vertices", function () { vertexCollection = await db.createCollection(`xc_${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${vertexCollection.name}` }, - 10000 + 10000, ); }); afterEach(async () => { @@ -109,7 +109,7 @@ describe("Manipulating graph vertices", function () { vertexCollection = await db.createCollection(`xc_${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${vertexCollection.name}` }, - 10000 + 10000, ); await graph.addVertexCollection(vertexCollection.name); }); @@ -121,7 +121,7 @@ describe("Manipulating graph vertices", function () { it("destroys the collection if explicitly passed true", async () => { const data = await graph.removeVertexCollection( vertexCollection.name, - true + true, ); expect(data.orphanCollections).not.to.contain(vertexCollection.name); try { diff --git a/src/test/18-graph-edges.ts b/src/test/18-graph-edges.ts index 1c412813..de99a535 100644 --- a/src/test/18-graph-edges.ts +++ b/src/test/18-graph-edges.ts @@ -31,7 +31,10 @@ describe("Manipulating graph edges", function () { to: ["person"], }, ]); - await db.waitForPropagation({ pathname: `/_api/gharial/${graph.name}` }, 10000); + await db.waitForPropagation( + { pathname: `/_api/gharial/${graph.name}` }, + 10000, + ); }); afterEach(async () => { await graph.drop(); @@ -45,13 +48,13 @@ describe("Manipulating graph edges", function () { expect(info.edgeDefinitions.map((e) => e.collection)).to.contain("knows"); expect(info.edgeDefinitions.length).to.equal(1); const edgeDefinition = info.edgeDefinitions.filter( - (e) => e.collection === "knows" + (e) => e.collection === "knows", ); expect( - edgeDefinition.reduce((arr, e) => [...arr, ...e.from], [] as string[]) + edgeDefinition.reduce((arr, e) => [...arr, ...e.from], [] as string[]), ).to.contain("person"); expect( - edgeDefinition.reduce((arr, e) => [...arr, ...e.to], [] as string[]) + edgeDefinition.reduce((arr, e) => [...arr, ...e.to], [] as string[]), ).to.contain("person"); }); }); @@ -90,17 +93,17 @@ describe("Manipulating graph edges", function () { expect(info).to.have.property("edgeDefinitions"); expect(info.edgeDefinitions).to.be.instanceOf(Array); expect(info.edgeDefinitions.map((e) => e.collection)).to.contain( - "works_in" + "works_in", ); expect(info.edgeDefinitions.length).to.equal(2); const edgeDefinition = info.edgeDefinitions.filter( - (e) => e.collection === "works_in" + (e) => e.collection === "works_in", ); expect( - edgeDefinition.reduce((arr, e) => [...arr, ...e.from], [] as string[]) + edgeDefinition.reduce((arr, e) => [...arr, ...e.from], [] as string[]), ).to.contain("person"); expect( - edgeDefinition.reduce((arr, e) => [...arr, ...e.to], [] as string[]) + edgeDefinition.reduce((arr, e) => [...arr, ...e.to], [] as string[]), ).to.contain("city"); }); }); @@ -117,13 +120,13 @@ describe("Manipulating graph edges", function () { expect(info.edgeDefinitions.map((e) => e.collection)).to.contain("knows"); expect(info.edgeDefinitions.length).to.equal(1); const edgeDefinition = info.edgeDefinitions.filter( - (e) => e.collection === "knows" + (e) => e.collection === "knows", ); expect( - edgeDefinition.reduce((arr, e) => [...arr, ...e.from], [] as string[]) + edgeDefinition.reduce((arr, e) => [...arr, ...e.from], [] as string[]), ).to.contain("person"); expect( - edgeDefinition.reduce((arr, e) => [...arr, ...e.to], [] as string[]) + edgeDefinition.reduce((arr, e) => [...arr, ...e.to], [] as string[]), ).to.contain("city"); }); }); diff --git a/src/test/19-graph-vertex-collections.ts b/src/test/19-graph-vertex-collections.ts index a7038623..1340d50e 100644 --- a/src/test/19-graph-vertex-collections.ts +++ b/src/test/19-graph-vertex-collections.ts @@ -22,7 +22,10 @@ describe("GraphVertexCollection API", function () { to: ["person"], }, ]); - await db.waitForPropagation({ pathname: `/_api/gharial/${graph.name}` }, 10000); + await db.waitForPropagation( + { pathname: `/_api/gharial/${graph.name}` }, + 10000, + ); collection = graph.vertexCollection("person"); }); after(async () => { @@ -132,7 +135,7 @@ describe("GraphVertexCollection API", function () { await collection.update( doc, { sup: "dawg", empty: null }, - { keepNull: false } + { keepNull: false }, ); const newData = await collection.vertex(doc._key); expect(newData).to.have.property("potato").that.equals(doc.potato); diff --git a/src/test/20-graph-edge-collections.ts b/src/test/20-graph-edge-collections.ts index 089f7e8f..71310f21 100644 --- a/src/test/20-graph-edge-collections.ts +++ b/src/test/20-graph-edge-collections.ts @@ -22,7 +22,10 @@ describe("GraphEdgeCollection API", function () { to: ["person"], }, ]); - await db.waitForPropagation({ pathname: `/_api/gharial/${graph.name}` }, 10000); + await db.waitForPropagation( + { pathname: `/_api/gharial/${graph.name}` }, + 10000, + ); collection = graph.edgeCollection("knows"); await graph .vertexCollection("person") @@ -163,7 +166,7 @@ describe("GraphEdgeCollection API", function () { await collection.update( doc, { sup: "dawg", empty: null }, - { keepNull: false } + { keepNull: false }, ); const newData = await collection.edge(doc._key); expect(newData).to.have.property("potato", doc.potato); diff --git a/src/test/22-foxx-api.ts b/src/test/22-foxx-api.ts index cd1f397c..51e9c060 100644 --- a/src/test/22-foxx-api.ts +++ b/src/test/22-foxx-api.ts @@ -23,9 +23,9 @@ describe("Foxx service", () => { serviceServiceMount, new Blob([ fs.readFileSync( - path.resolve("fixtures", "service-service-service.zip") + path.resolve("fixtures", "service-service-service.zip"), ), - ]) + ]), ); arangoPaths = (await db.route(serviceServiceMount).get()).parsedBody; }); @@ -33,7 +33,7 @@ describe("Foxx service", () => { after(async () => { try { await db.uninstallService(serviceServiceMount, { force: true }); - } catch (e: any) { } + } catch (e: any) {} try { await system.dropDatabase(name); } finally { @@ -44,7 +44,7 @@ describe("Foxx service", () => { afterEach(async () => { try { await db.uninstallService(mount, { force: true }); - } catch (e: any) { } + } catch (e: any) {} }); const cases = [ @@ -65,7 +65,7 @@ describe("Foxx service", () => { source: () => new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.js") + path.resolve(localAppsPath, "minimal-working-service.js"), ), ]), }, @@ -74,7 +74,7 @@ describe("Foxx service", () => { source: () => new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), ]), }, @@ -92,7 +92,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "itzpapalotl.zip")), - ]) + ]), ); await db.replaceService(mount, c.source(arangoPaths)); const resp = await db.route(mount).get(); @@ -104,7 +104,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "itzpapalotl.zip")), - ]) + ]), ); await db.upgradeService(mount, c.source(arangoPaths)); const resp = await db.route(mount).get(); @@ -117,15 +117,15 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); await db.uninstallService(mount); try { await db.route(mount).get(); expect.fail(); - } catch (e: any) { } + } catch (e: any) {} }); it("empty configuration should be available", async () => { @@ -133,9 +133,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const resp = await db.getServiceConfiguration(mount); expect(resp).to.eql({}); @@ -146,9 +146,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const resp = await db.getServiceConfiguration(mount, true); expect(resp).to.eql({}); @@ -159,7 +159,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); const resp = await db.getServiceConfiguration(mount); expect(resp).to.have.property("test1"); @@ -173,7 +173,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); const resp = await db.getServiceConfiguration(mount, true); expect(resp).to.have.eql({}); @@ -184,7 +184,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); const updateResp = await db.updateServiceConfiguration(mount, { test1: "test", @@ -207,14 +207,14 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); const updateResp = await db.updateServiceConfiguration( mount, { test1: "test", }, - true + true, ); expect(updateResp).to.have.property("values"); expect(updateResp.values).to.have.property("test1", "test"); @@ -230,7 +230,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); const replaceResp = await db.replaceServiceConfiguration(mount, { test1: "test", @@ -253,14 +253,14 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); const replaceResp = await db.replaceServiceConfiguration( mount, { test1: "test", }, - true + true, ); expect(replaceResp).to.have.property("values"); expect(replaceResp.values).to.have.property("test1", "test"); @@ -277,7 +277,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); await db.replaceServiceConfiguration(mount, { test2: "test2" }); await db.updateServiceConfiguration(mount, { test1: "test1" }); @@ -293,7 +293,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); await db.replaceServiceConfiguration(mount, { test2: "test2" }, true); await db.updateServiceConfiguration(mount, { test1: "test1" }, true); @@ -307,7 +307,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); await db.updateServiceConfiguration(mount, { test2: "test2" }); await db.replaceServiceConfiguration(mount, { test1: "test" }); @@ -323,7 +323,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-configuration.zip")), - ]) + ]), ); await db.updateServiceConfiguration(mount, { test2: "test2" }, true); await db.replaceServiceConfiguration(mount, { test1: "test" }, true); @@ -337,9 +337,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const resp = await db.getServiceDependencies(mount); expect(resp).to.eql({}); @@ -350,9 +350,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const resp = await db.getServiceDependencies(mount, true); expect(resp).to.eql({}); @@ -363,7 +363,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const resp = await db.getServiceDependencies(mount); expect(resp).to.have.property("test1"); @@ -377,7 +377,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const resp = await db.getServiceDependencies(mount, true); expect(resp).to.eql({}); @@ -388,7 +388,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const updateResp = await db.updateServiceDependencies(mount, { test1: "/test", @@ -411,14 +411,14 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const updateResp = await db.updateServiceDependencies( mount, { test1: "/test", }, - true + true, ); expect(updateResp).to.have.property("values"); expect(updateResp.values).to.have.property("test1", "/test"); @@ -434,7 +434,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const replaceResp = await db.replaceServiceDependencies(mount, { test1: "/test", @@ -457,14 +457,14 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const replaceResp = await db.replaceServiceDependencies( mount, { test1: "/test", }, - true + true, ); expect(replaceResp).to.have.property("values"); expect(replaceResp.values).to.have.property("test1", "/test"); @@ -481,7 +481,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const replaceResp = await db.replaceServiceDependencies(mount, { test2: "/test2", @@ -511,12 +511,12 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const replaceResp = await db.replaceServiceDependencies( mount, { test2: "/test2" }, - true + true, ); expect(replaceResp).to.have.property("values"); expect(replaceResp.values).to.have.property("test2", "/test2"); @@ -528,7 +528,7 @@ describe("Foxx service", () => { { test1: "/test1", }, - true + true, ); expect(updateResp).to.have.property("values"); expect(updateResp.values).to.have.property("test1", "/test1"); @@ -543,7 +543,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const updateResp = await db.updateServiceDependencies(mount, { test2: "/test2", @@ -575,14 +575,14 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-dependencies.zip")), - ]) + ]), ); const updateResp = await db.updateServiceDependencies( mount, { test2: "/test2", }, - true + true, ); expect(updateResp).to.have.property("values"); expect(updateResp.values).to.not.have.property("test1"); @@ -593,7 +593,7 @@ describe("Foxx service", () => { { test1: "/test1", }, - true + true, ); expect(replaceResp).to.have.property("values"); expect(replaceResp.values).to.have.property("test1", "/test1"); @@ -610,9 +610,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const resp = await db.downloadService(mount); expect(resp).to.be.instanceof(Blob); @@ -623,9 +623,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const services = await db.listServices(); expect(services).to.be.instanceOf(Array); @@ -637,9 +637,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const services = await db.listServices(); const service = services.find((service) => service.mount === mount)!; @@ -656,9 +656,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const service = await db.getService(mount); expect(service).to.have.property("mount", mount); @@ -679,9 +679,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-setup-teardown.zip") + path.resolve(localAppsPath, "minimal-working-setup-teardown.zip"), ), - ]) + ]), ); const scripts = await db.getServiceScripts(mount); expect(scripts).to.have.property("setup", "Setup"); @@ -693,9 +693,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-setup-teardown.zip") + path.resolve(localAppsPath, "minimal-working-setup-teardown.zip"), ), - ]) + ]), ); const col = `${mount}_setup_teardown`.replace(/\//, "").replace(/-/g, "_"); expect(await db.collection(col).get()).to.be.instanceOf(Object); @@ -714,7 +714,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "echo-script.zip")), - ]) + ]), ); try { await db.runServiceScript(mount, "no", {}); @@ -730,7 +730,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "echo-script.zip")), - ]) + ]), ); const argv = { hello: "world" }; const resp = await db.runServiceScript(mount, "echo", argv); @@ -742,7 +742,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "echo-script.zip")), - ]) + ]), ); const argv = ["yes", "please"]; const resp = await db.runServiceScript(mount, "echo", argv); @@ -754,9 +754,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const resp = await db.getService(mount); expect(resp.development).to.equal(false); @@ -771,10 +771,10 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), ]), - { development: true } + { development: true }, ); const resp = await db.getService(mount); expect(resp.development).to.equal(true); @@ -787,7 +787,9 @@ describe("Foxx service", () => { it("tests should run", async () => { await db.installService( mount, - new Blob([fs.readFileSync(path.resolve(localAppsPath, "with-tests.zip"))]) + new Blob([ + fs.readFileSync(path.resolve(localAppsPath, "with-tests.zip")), + ]), ); const resp = await db.runServiceTests(mount, {}); expect(resp).to.have.property("stats"); @@ -802,7 +804,7 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync(path.resolve(localAppsPath, "with-readme.zip")), - ]) + ]), ); const resp = await db.getServiceReadme(mount); expect(resp).to.equal("Please read this."); @@ -813,9 +815,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const resp = await db.getServiceReadme(mount); expect(resp).to.equal(undefined); @@ -826,9 +828,9 @@ describe("Foxx service", () => { mount, new Blob([ fs.readFileSync( - path.resolve(localAppsPath, "minimal-working-service.zip") + path.resolve(localAppsPath, "minimal-working-service.zip"), ), - ]) + ]), ); const resp = await db.getServiceDocumentation(mount); expect(resp).to.have.property("swagger", "2.0"); diff --git a/src/test/23-aql-queries-stream.ts b/src/test/23-aql-queries-stream.ts index 2f0dd8d7..55a39e5e 100644 --- a/src/test/23-aql-queries-stream.ts +++ b/src/test/23-aql-queries-stream.ts @@ -18,7 +18,7 @@ describe("AQL Stream queries", function () { }); after(async () => { await Promise.all( - allCursors.map((cursor) => cursor.kill().catch(() => undefined)) + allCursors.map((cursor) => cursor.kill().catch(() => undefined)), ); try { await system.dropDatabase(name); @@ -69,12 +69,12 @@ describe("AQL Stream queries", function () { const collection = await db.createCollection(cname); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); await Promise.all( Array.from(Array(1000).keys()).map((i: number) => - collection.save({ hallo: i }) - ) + collection.save({ hallo: i }), + ), ); }); /*after(async () => { @@ -87,15 +87,15 @@ describe("AQL Stream queries", function () { let count = 0; const cursors = await Promise.all( - Array.from(Array(25)).map(() => db.query(query, options)) + Array.from(Array(25)).map(() => db.query(query, options)), ); allCursors.push(...cursors); await Promise.all( cursors.map((c) => (c as Cursor).forEach(() => { count++; - }) - ) + }), + ), ); expect(count).to.equal(25 * 1000); }); diff --git a/src/test/24-accessing-views.ts b/src/test/24-accessing-views.ts index a1892fc3..0cdc063b 100644 --- a/src/test/24-accessing-views.ts +++ b/src/test/24-accessing-views.ts @@ -38,9 +38,9 @@ describe("Accessing views", function () { await view.create({ type: "arangosearch" }); await db.waitForPropagation( { pathname: `/_api/view/${view.name}` }, - 10000 + 10000, ); - }) + }), ); }); after(async () => { @@ -61,14 +61,14 @@ describe("Accessing views", function () { await view.create({ type: "arangosearch" }); await db.waitForPropagation( { pathname: `/_api/view/${view.name}` }, - 10000 + 10000, ); - }) + }), ); }); after(async () => { await Promise.all( - arangoSearchViewNames.map((name) => db.view(name).drop()) + arangoSearchViewNames.map((name) => db.view(name).drop()), ); }); it("creates View instances", async () => { @@ -76,7 +76,7 @@ describe("Accessing views", function () { const arangoSearchViews = views.filter((v) => v instanceof View).sort(); expect(arangoSearchViews.length).to.equal(arangoSearchViewNames.length); expect(arangoSearchViews.map((v) => v.name).sort()).to.eql( - arangoSearchViewNames + arangoSearchViewNames, ); }); }); diff --git a/src/test/26-manipulating-views.ts b/src/test/26-manipulating-views.ts index 027fa6b3..51234426 100644 --- a/src/test/26-manipulating-views.ts +++ b/src/test/26-manipulating-views.ts @@ -41,7 +41,10 @@ describe("Manipulating views", function () { it("creates a new arangosearch view", async () => { const view = db.view(`asv-${Date.now()}`); await view.create({ type: "arangosearch" }); - await db.waitForPropagation({ pathname: `/_api/view/${view.name}` }, 10000); + await db.waitForPropagation( + { pathname: `/_api/view/${view.name}` }, + 10000, + ); const info = await view.get(); expect(info).to.have.property("name", view.name); expect(info).to.have.property("type", "arangosearch"); @@ -76,7 +79,7 @@ describe("Manipulating views", function () { commitIntervalMsec: 30000, }); expect(properties.consolidationIntervalMsec).to.equal( - initial.consolidationIntervalMsec + initial.consolidationIntervalMsec, ); expect(properties.commitIntervalMsec).to.equal(30000); }); diff --git a/src/test/27-query-management.ts b/src/test/27-query-management.ts index 3b80c7c8..3e25cd5b 100644 --- a/src/test/27-query-management.ts +++ b/src/test/27-query-management.ts @@ -33,7 +33,7 @@ describe("Query Management API", function () { }); after(async () => { await Promise.all( - allCursors.map((cursor) => cursor.kill().catch(() => undefined)) + allCursors.map((cursor) => cursor.kill().catch(() => undefined)), ); try { await system.dropDatabase(dbName); @@ -200,7 +200,7 @@ describe("Query Management API", function () { // must filter the list here, as there could be other (system) queries // ongoing at the same time queries = (await db.listRunningQueries()).filter( - (i: any) => i.query === query + (i: any) => i.query === query, ); if (queries.length > 0) { break; @@ -237,7 +237,7 @@ describe("Query Management API", function () { allCursors.push(cursor); // must filter the list here, as there could have been other (system) queries const queries = (await db.listSlowQueries()).filter( - (i: any) => i.query === query + (i: any) => i.query === query, ); expect(queries).to.have.lengthOf(1); expect(queries[0]).to.have.property("query", query); @@ -266,12 +266,12 @@ describe("Query Management API", function () { allCursors.push(cursor); // must filter the list here, as there could have been other (system) queries const queries1 = (await db.listSlowQueries()).filter( - (i: any) => i.query === query + (i: any) => i.query === query, ); expect(queries1).to.have.lengthOf(1); await db.clearSlowQueries(); const queries2 = (await db.listSlowQueries()).filter( - (i: any) => i.query === query + (i: any) => i.query === query, ); expect(queries2).to.have.lengthOf(0); }); @@ -285,7 +285,7 @@ describe("Query Management API", function () { const p1 = db.query(query); p1.then((cursor) => allCursors.push(cursor)); const queries = (await db.listSlowQueries()).filter( - (i: any) => i.query === query + (i: any) => i.query === query, ); expect(queries).to.have.lengthOf(1); expect(queries[0]).to.have.property("bindVars"); diff --git a/src/test/28-accessing-analyzers.ts b/src/test/28-accessing-analyzers.ts index 760323da..f524cebf 100644 --- a/src/test/28-accessing-analyzers.ts +++ b/src/test/28-accessing-analyzers.ts @@ -43,16 +43,16 @@ describe("Accessing analyzers", function () { await analyzer.create({ type: "identity" }); await db.waitForPropagation( { pathname: `/_api/analyzer/${analyzer.name}` }, - 65000 + 65000, ); - }) + }), ); }); after(async () => { await Promise.all( analyzerNames.map((name) => - db.analyzer(name.replace(/^[^:]+::/, "")).drop() - ) + db.analyzer(name.replace(/^[^:]+::/, "")).drop(), + ), ); }); it("fetches information about all analyzers", async () => { @@ -71,16 +71,16 @@ describe("Accessing analyzers", function () { await analyzer.create({ type: "identity" }); await db.waitForPropagation( { pathname: `/_api/analyzer/${analyzer.name}` }, - 65000 + 65000, ); - }) + }), ); }); after(async () => { await Promise.all( analyzerNames.map((name) => - db.analyzer(name.replace(/^[^:]+::/, "")).drop() - ) + db.analyzer(name.replace(/^[^:]+::/, "")).drop(), + ), ); }); it("creates Analyzer instances", async () => { diff --git a/src/test/29-manipulating-analyzers.ts b/src/test/29-manipulating-analyzers.ts index 51fd3f43..f5726c14 100644 --- a/src/test/29-manipulating-analyzers.ts +++ b/src/test/29-manipulating-analyzers.ts @@ -42,7 +42,7 @@ describe("Manipulating analyzers", function () { after(async () => { try { await analyzer.drop(); - } catch { } + } catch {} }); it("fetches information about the analyzer", async () => { const data = await analyzer.get(); diff --git a/src/test/29-queue-time.ts b/src/test/29-queue-time.ts index e1cf72dc..06cc6d5f 100644 --- a/src/test/29-queue-time.ts +++ b/src/test/29-queue-time.ts @@ -19,7 +19,7 @@ describe("Queue time metrics", function () { collection = await db.createCollection(`c_${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); after(async () => { @@ -34,7 +34,7 @@ describe("Queue time metrics", function () { }); it("should trim existing queue times when set to a lower value", async () => { await Promise.all( - range(10).map(() => collection.save({ value: Math.random() })) + range(10).map(() => collection.save({ value: Math.random() })), ); expect(db.queueTime.getValues().length).to.equal(10); db.setResponseQueueTimeSamples(5); @@ -42,23 +42,23 @@ describe("Queue time metrics", function () { }); it("should allow more values when set to a higher value", async () => { await Promise.all( - range(10).map(() => collection.save({ value: Math.random() })) + range(10).map(() => collection.save({ value: Math.random() })), ); expect(db.queueTime.getValues().length).to.equal(10); db.setResponseQueueTimeSamples(20); await Promise.all( - range(10).map(() => collection.save({ value: Math.random() })) + range(10).map(() => collection.save({ value: Math.random() })), ); expect(db.queueTime.getValues().length).to.equal(20); }); it("should allow fewer values when set to a lower value", async () => { await Promise.all( - range(10).map(() => collection.save({ value: Math.random() })) + range(10).map(() => collection.save({ value: Math.random() })), ); expect(db.queueTime.getValues().length).to.equal(10); db.setResponseQueueTimeSamples(5); await Promise.all( - range(10).map(() => collection.save({ value: Math.random() })) + range(10).map(() => collection.save({ value: Math.random() })), ); expect(db.queueTime.getValues().length).to.equal(5); }); @@ -67,7 +67,7 @@ describe("Queue time metrics", function () { it("should return the latest value", async () => { expect(db.queueTime.getLatest()).to.equal(undefined); await Promise.all( - range(10).map(() => collection.save({ value: Math.random() })) + range(10).map(() => collection.save({ value: Math.random() })), ); const values = db.queueTime.getValues(); expect(values.length).to.be.greaterThan(0); @@ -79,7 +79,7 @@ describe("Queue time metrics", function () { const min = Date.now(); expect(db.queueTime.getValues()).to.eql([]); await Promise.all( - range(10).map(() => collection.save({ value: Math.random() })) + range(10).map(() => collection.save({ value: Math.random() })), ); const max = Date.now(); const values = db.queueTime.getValues(); @@ -96,7 +96,7 @@ describe("Queue time metrics", function () { it("should return the arithmetic average of all current values", async () => { expect(db.queueTime.getAvg()).to.equal(0); await Promise.all( - range(10).map(() => collection.save({ value: Math.random() })) + range(10).map(() => collection.save({ value: Math.random() })), ); const values = db.queueTime.getValues(); expect(values.length).to.be.greaterThan(0); diff --git a/src/test/30-concurrent-transactions.ts b/src/test/30-concurrent-transactions.ts index 38d33a80..0ded03b8 100644 --- a/src/test/30-concurrent-transactions.ts +++ b/src/test/30-concurrent-transactions.ts @@ -32,18 +32,18 @@ describe("Transactions", function () { after(async () => { await Promise.all( allTransactions.map((transaction) => - transaction.abort().catch(() => undefined) - ) + transaction.abort().catch(() => undefined), + ), ); try { await system.dropDatabase(name); - } catch { } + } catch {} }); beforeEach(async () => { collection = await db.createCollection(`collection-${Date.now()}`); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); afterEach(async () => { @@ -58,7 +58,7 @@ describe("Transactions", function () { it("can run concurrent transactions in parallel", async () => { const conn = (db as any)._connection as Connection; const range = Array.from(Array((conn as any)._taskPoolSize).keys()).map( - (i) => i + 1 + (i) => i + 1, ); let failed = 0; await Promise.all( @@ -73,7 +73,7 @@ describe("Transactions", function () { trx.id, "completed begin after", Date.now() - started, - "ms elapsed" + "ms elapsed", ); await trx.step(() => collection.save({ enabled: true })); console.log( @@ -82,7 +82,7 @@ describe("Transactions", function () { trx.id, "completed save after", Date.now() - started, - "ms elapsed" + "ms elapsed", ); await delay(Math.random() * 10); await trx.commit(); @@ -92,7 +92,7 @@ describe("Transactions", function () { trx.id, "completed commit after", Date.now() - started, - "ms elapsed" + "ms elapsed", ); } catch (e: any) { console.error( @@ -102,18 +102,18 @@ describe("Transactions", function () { "failed after", Date.now() - started, "ms elapsed:", - String(e) + String(e), ); failed++; } - }) + }), ); expect(failed).to.equal(0); }); it("respects transactional guarantees", async () => { const conn = (db as any)._connection as Connection; const range = Array.from(Array((conn as any)._taskPoolSize).keys()).map( - (i) => i + 1 + (i) => i + 1, ); const key = "test"; await collection.save({ _key: key, i: 0 }); @@ -134,7 +134,7 @@ describe("Transactions", function () { "adding", value, "=", - doc.i + value + doc.i + value, ); await trx.step(() => collection.update(key, { i: doc.i + value })); console.log(value, "committing"); @@ -144,7 +144,7 @@ describe("Transactions", function () { console.error(value, "failed:", String(e)); failed++; } - }) + }), ); const doc = await collection.document(key); expect(doc.i).to.equal(range.reduce((a, b) => a + b)); diff --git a/src/test/31-conflicts.ts b/src/test/31-conflicts.ts index 711faf46..6bd73a07 100644 --- a/src/test/31-conflicts.ts +++ b/src/test/31-conflicts.ts @@ -20,7 +20,7 @@ describe("config.maxRetries", () => { collection = await db.createCollection(collectionName); await db.waitForPropagation( { pathname: `/_api/collection/${collection.name}` }, - 10000 + 10000, ); }); after(async () => { @@ -45,12 +45,12 @@ describe("config.maxRetries", () => { LET doc = DOCUMENT(${collection}, ${docKey}) UPDATE doc WITH { data: doc.data + 1 } IN ${collection} `, - { retryOnConflict: 0 } - ) - ) + { retryOnConflict: 0 }, + ), + ), ); expect( - result.filter(({ status }) => status === "rejected") + result.filter(({ status }) => status === "rejected"), ).not.to.have.lengthOf(0); const { data } = await collection.document(docKey); expect(data).not.to.equal(1_000); @@ -65,9 +65,9 @@ describe("config.maxRetries", () => { LET doc = DOCUMENT(${collection}, ${docKey}) UPDATE doc WITH { data: doc.data + 1 } IN ${collection} `, - { retryOnConflict: 100 } - ) - ) + { retryOnConflict: 100 }, + ), + ), ); const { data } = await collection.document(docKey); expect(data).to.equal(1_000); diff --git a/src/test/_config.ts b/src/test/_config.ts index 71d0aa20..53419dcb 100644 --- a/src/test/_config.ts +++ b/src/test/_config.ts @@ -2,7 +2,7 @@ import { ConfigOptions, LoadBalancingStrategy } from "../configuration.js"; const ARANGO_URL = process.env.TEST_ARANGODB_URL || "http://127.0.0.1:8529"; const ARANGO_VERSION = Number( - process.env.ARANGO_VERSION || process.env.ARANGOJS_DEVEL_VERSION || 0 + process.env.ARANGO_VERSION || process.env.ARANGOJS_DEVEL_VERSION || 0, ); const ARANGO_RELEASE = process.env.ARANGO_RELEASE || ""; let arangoVersion: number = 39999; @@ -20,13 +20,13 @@ const ARANGO_LOAD_BALANCING_STRATEGY = process.env export const config: ConfigOptions & { arangoVersion: NonNullable; } = ARANGO_URL.includes(",") - ? { + ? { url: ARANGO_URL.split(",").filter((s) => Boolean(s)), arangoVersion, precaptureStackTraces: true, loadBalancingStrategy: ARANGO_LOAD_BALANCING_STRATEGY || "ROUND_ROBIN", } - : { + : { url: ARANGO_URL, arangoVersion, precaptureStackTraces: true, diff --git a/src/transactions.ts b/src/transactions.ts index 45107adc..1d97463c 100644 --- a/src/transactions.ts +++ b/src/transactions.ts @@ -24,17 +24,26 @@ export type TransactionCollectionOptions = { * written to during the transaction with no other writes being able to run * in parallel. */ - exclusive?: (string | collections.ArangoCollection)[] | string | collections.ArangoCollection; + exclusive?: + | (string | collections.ArangoCollection)[] + | string + | collections.ArangoCollection; /** * An array of collections or a single collection that will be read from or * written to during the transaction. */ - write?: (string | collections.ArangoCollection)[] | string | collections.ArangoCollection; + write?: + | (string | collections.ArangoCollection)[] + | string + | collections.ArangoCollection; /** * An array of collections or a single collection that will be read from * during the transaction. */ - read?: (string | collections.ArangoCollection)[] | string | collections.ArangoCollection; + read?: + | (string | collections.ArangoCollection)[] + | string + | collections.ArangoCollection; }; /** @@ -45,7 +54,7 @@ export function coerceTransactionCollections( | (TransactionCollectionOptions & { allowImplicit?: boolean }) | (string | collections.ArangoCollection)[] | string - | collections.ArangoCollection + | collections.ArangoCollection, ): CoercedTransactionCollections { if (typeof options === "string") { return { write: [options] }; @@ -196,7 +205,7 @@ export type TransactionInfo = { * @param transaction - A value that might be a transaction. */ export function isArangoTransaction( - transaction: any + transaction: any, ): transaction is Transaction { return Boolean(transaction && transaction.isArangoTransaction); } @@ -282,7 +291,7 @@ export class Transaction { { pathname: `/_api/transaction/${encodeURIComponent(this.id)}`, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -309,7 +318,7 @@ export class Transaction { pathname: `/_api/transaction/${encodeURIComponent(this.id)}`, allowDirtyRead, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -336,7 +345,7 @@ export class Transaction { pathname: `/_api/transaction/${encodeURIComponent(this.id)}`, allowDirtyRead, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } @@ -534,7 +543,7 @@ export class Transaction { const promise = callback(); if (!promise) { throw new Error( - "Transaction callback was not an async function or did not return a promise!" + "Transaction callback was not an async function or did not return a promise!", ); } return Promise.resolve(promise); @@ -543,4 +552,4 @@ export class Transaction { } } } -//#endregion \ No newline at end of file +//#endregion diff --git a/src/users.ts b/src/users.ts index a5996857..1baebea1 100644 --- a/src/users.ts +++ b/src/users.ts @@ -103,4 +103,4 @@ export type ArangoUser = { */ extra: Record; }; -//#endregion \ No newline at end of file +//#endregion diff --git a/src/views.ts b/src/views.ts index 82d4f62f..9b7f5fa6 100644 --- a/src/views.ts +++ b/src/views.ts @@ -166,7 +166,10 @@ export type CreateArangoSearchViewOptions = CreateViewOptionsType< * Attribute paths for which values should be stored in the view index * in addition to those used for sorting via `primarySort`. */ - storedValues?: CreateArangoSearchViewStoredValueOptions[] | string[] | string[][]; + storedValues?: + | CreateArangoSearchViewStoredValueOptions[] + | string[] + | string[][]; /** * An array of strings defining sort expressions to optimize. */ @@ -177,32 +180,31 @@ export type CreateArangoSearchViewOptions = CreateViewOptionsType< /** * Options for creating a primary sort in an ArangoSearch View. */ -export type CreateArangoSearchViewPrimarySortOptions = ( +export type CreateArangoSearchViewPrimarySortOptions = | { - /** - * Attribute path for the value of each document to use for - * sorting. - */ - field: string; - /** - * If set to `"asc"`, the primary sorting order will be ascending. - * If set to `"desc"`, the primary sorting order will be descending. - */ - direction: Direction; - } + /** + * Attribute path for the value of each document to use for + * sorting. + */ + field: string; + /** + * If set to `"asc"`, the primary sorting order will be ascending. + * If set to `"desc"`, the primary sorting order will be descending. + */ + direction: Direction; + } | { - /** - * Attribute path for the value of each document to use for - * sorting. - */ - field: string; - /** - * If set to `true`, the primary sorting order will be ascending. - * If set to `false`, the primary sorting order will be descending. - */ - asc: boolean; - } -); + /** + * Attribute path for the value of each document to use for + * sorting. + */ + field: string; + /** + * If set to `true`, the primary sorting order will be ascending. + * If set to `false`, the primary sorting order will be descending. + */ + asc: boolean; + }; /** * Options for creating a stored value in an ArangoSearch View. @@ -594,13 +596,13 @@ export class View { * ``` */ create( - options: CreateViewOptions + options: CreateViewOptions, ): Promise< typeof options extends CreateArangoSearchViewOptions - ? ArangoSearchViewDescription - : Options extends CreateSearchAliasViewOptions - ? SearchAliasViewDescription - : ViewDescription + ? ArangoSearchViewDescription + : Options extends CreateSearchAliasViewOptions + ? SearchAliasViewDescription + : ViewDescription > { return this._db.request({ method: "POST", @@ -634,7 +636,9 @@ export class View { * // view1 and view3 represent the same ArangoDB view! * ``` */ - async rename(newName: string): Promise> { + async rename( + newName: string, + ): Promise> { const result = this._db.renameView(this._name, newName); this._name = newName; return result; @@ -673,13 +677,13 @@ export class View { * ``` */ updateProperties( - properties?: Properties + properties?: Properties, ): Promise< Properties extends UpdateArangoSearchViewPropertiesOptions - ? ArangoSearchViewProperties - : Properties extends UpdateSearchAliasViewPropertiesOptions - ? SearchAliasViewProperties - : ViewProperties + ? ArangoSearchViewProperties + : Properties extends UpdateSearchAliasViewPropertiesOptions + ? SearchAliasViewProperties + : ViewProperties > { return this._db.request({ method: "PATCH", @@ -704,13 +708,13 @@ export class View { * ``` */ replaceProperties( - properties?: Properties + properties?: Properties, ): Promise< Properties extends ArangoSearchViewPropertiesOptions - ? ArangoSearchViewProperties - : Properties extends SearchAliasViewPropertiesOptions - ? SearchAliasViewProperties - : ViewProperties + ? ArangoSearchViewProperties + : Properties extends SearchAliasViewPropertiesOptions + ? SearchAliasViewProperties + : ViewProperties > { return this._db.request({ method: "PUT", @@ -737,8 +741,8 @@ export class View { method: "DELETE", pathname: `/_api/view/${encodeURIComponent(this._name)}`, }, - (res) => res.parsedBody.result + (res) => res.parsedBody.result, ); } } -//#endregion \ No newline at end of file +//#endregion