From 2da601316d9858fb7c27e608611307ab569803e8 Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Wed, 24 Nov 2021 16:36:33 +0100 Subject: [PATCH] fix: simplify model with types and simplify api --- .../client-search/searchApi.ts | 203 +----- .../model/batchObject.ts | 20 +- .../model/batchResponse.ts | 27 +- .../model/errorBase.ts | 21 +- .../model/highlightResult.ts | 47 +- .../model/models.ts | 209 ------- .../model/multipleQueries.ts | 52 +- .../model/multipleQueriesObject.ts | 31 +- .../model/multipleQueriesResponse.ts | 20 +- .../model/operation.ts | 41 +- .../model/rankingInfo.ts | 90 +-- .../model/rankingInfoMatchedGeoLocation.ts | 34 +- .../model/record.ts | 49 +- .../model/saveObjectResponse.ts | 34 +- .../model/searchParams.ts | 590 +++--------------- .../model/searchParamsString.ts | 20 +- .../model/searchResponse.ts | 188 +----- .../model/searchResponseFacetsStats.ts | 41 +- .../model/snippetResult.ts | 33 +- templates/javascript/api-single.mustache | 297 ++++----- templates/javascript/model.mustache | 33 +- templates/javascript/models.mustache | 189 ------ 22 files changed, 364 insertions(+), 1905 deletions(-) diff --git a/clients/algoliasearch-client-javascript/client-search/searchApi.ts b/clients/algoliasearch-client-javascript/client-search/searchApi.ts index c3649af66ce..b643e903b30 100644 --- a/clients/algoliasearch-client-javascript/client-search/searchApi.ts +++ b/clients/algoliasearch-client-javascript/client-search/searchApi.ts @@ -12,9 +12,7 @@ import { SaveObjectResponse } from '../model/saveObjectResponse'; import { SearchParams } from '../model/searchParams'; import { SearchParamsString } from '../model/searchParamsString'; import { SearchResponse } from '../model/searchResponse'; - -import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; -import { HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; +import { ApiKeyAuth } from '../model/models'; export enum SearchApiApiKeys { apiKey, @@ -25,13 +23,10 @@ export class SearchApi { private transporter: Transporter; protected authentications = { - default: new VoidAuth(), apiKey: new ApiKeyAuth('header', 'X-Algolia-API-Key'), appId: new ApiKeyAuth('header', 'X-Algolia-Application-Id'), }; - protected interceptors: Interceptor[] = []; - constructor(appId: string, apiKey: string, requester?: Requester) { this.setApiKey(SearchApiApiKeys.appId, appId); this.setApiKey(SearchApiApiKeys.apiKey, apiKey); @@ -61,16 +56,21 @@ export class SearchApi { }); } - public setDefaultAuthentication(auth: Authentication) { - this.authentications.default = auth; - } - public setApiKey(key: SearchApiApiKeys, value: string) { - (this.authentications as any)[SearchApiApiKeys[key]].apiKey = value; + this.authentications[SearchApiApiKeys[key]].apiKey = value; } - public addInterceptor(interceptor: Interceptor) { - this.interceptors.push(interceptor); + private async sendRequest( + request: Request, + requestOptions: RequestOptions + ): Promise { + if (this.authentications.apiKey.apiKey) { + this.authentications.apiKey.applyToRequest(requestOptions); + } + if (this.authentications.appId.apiKey) { + this.authentications.appId.applyToRequest(requestOptions); + } + return this.transporter.request(request, requestOptions); } /** @@ -79,42 +79,26 @@ export class SearchApi { * @param indexName The index in which to perform the request * @param batchObject */ - public async batch( - indexName: string, - batchObject: BatchObject, - options: { headers: { [name: string]: string } } = { headers: {} } - ): Promise { + public async batch(indexName: string, batchObject: BatchObject): Promise { const path = '/1/indexes/{indexName}/batch'.replace( '{' + 'indexName' + '}', encodeURIComponent(String(indexName)) ); - let headers: Headers = {}; + let headers: Headers = { Accept: 'application/json' }; let queryParameters: Record = {}; - const produces = ['application/json']; - // give precedence to 'application/json' - if (produces.indexOf('application/json') >= 0) { - headers.Accept = 'application/json'; - } else { - headers.Accept = produces.join(','); - } - let formParams: Record = {}; - // verify required parameter 'indexName' is not null or undefined if (indexName === null || indexName === undefined) { throw new Error('Required parameter indexName was null or undefined when calling batch.'); } - // verify required parameter 'batchObject' is not null or undefined if (batchObject === null || batchObject === undefined) { throw new Error('Required parameter batchObject was null or undefined when calling batch.'); } - headers = { ...headers, ...options.headers }; - const request: Request = { method: 'POST', path, - data: ObjectSerializer.serialize(batchObject, 'BatchObject'), + data: batchObject, }; const requestOptions: RequestOptions = { @@ -122,29 +106,7 @@ export class SearchApi { queryParameters, }; - let authenticationPromise = Promise.resolve(); - if (this.authentications.apiKey.apiKey) { - authenticationPromise = authenticationPromise.then(() => - this.authentications.apiKey.applyToRequest(requestOptions) - ); - } - if (this.authentications.appId.apiKey) { - authenticationPromise = authenticationPromise.then(() => - this.authentications.appId.applyToRequest(requestOptions) - ); - } - authenticationPromise = authenticationPromise.then(() => - this.authentications.default.applyToRequest(requestOptions) - ); - - let interceptorPromise = authenticationPromise; - for (const interceptor of this.interceptors) { - interceptorPromise = interceptorPromise.then(() => interceptor(requestOptions)); - } - - await interceptorPromise; - - return this.transporter.request(request, requestOptions); + return this.sendRequest(request, requestOptions); } /** * @@ -152,34 +114,22 @@ export class SearchApi { * @param multipleQueriesObject */ public async multipleQueries( - multipleQueriesObject: MultipleQueriesObject, - options: { headers: { [name: string]: string } } = { headers: {} } + multipleQueriesObject: MultipleQueriesObject ): Promise { const path = '/1/indexes/*/queries'; - let headers: Headers = {}; + let headers: Headers = { Accept: 'application/json' }; let queryParameters: Record = {}; - const produces = ['application/json']; - // give precedence to 'application/json' - if (produces.indexOf('application/json') >= 0) { - headers.Accept = 'application/json'; - } else { - headers.Accept = produces.join(','); - } - let formParams: Record = {}; - // verify required parameter 'multipleQueriesObject' is not null or undefined if (multipleQueriesObject === null || multipleQueriesObject === undefined) { throw new Error( 'Required parameter multipleQueriesObject was null or undefined when calling multipleQueries.' ); } - headers = { ...headers, ...options.headers }; - const request: Request = { method: 'POST', path, - data: ObjectSerializer.serialize(multipleQueriesObject, 'MultipleQueriesObject'), + data: multipleQueriesObject, }; const requestOptions: RequestOptions = { @@ -187,29 +137,7 @@ export class SearchApi { queryParameters, }; - let authenticationPromise = Promise.resolve(); - if (this.authentications.apiKey.apiKey) { - authenticationPromise = authenticationPromise.then(() => - this.authentications.apiKey.applyToRequest(requestOptions) - ); - } - if (this.authentications.appId.apiKey) { - authenticationPromise = authenticationPromise.then(() => - this.authentications.appId.applyToRequest(requestOptions) - ); - } - authenticationPromise = authenticationPromise.then(() => - this.authentications.default.applyToRequest(requestOptions) - ); - - let interceptorPromise = authenticationPromise; - for (const interceptor of this.interceptors) { - interceptorPromise = interceptorPromise.then(() => interceptor(requestOptions)); - } - - await interceptorPromise; - - return this.transporter.request(request, requestOptions); + return this.sendRequest(request, requestOptions); } /** * Add an object to the index, automatically assigning it an object ID @@ -219,44 +147,31 @@ export class SearchApi { */ public async saveObject( indexName: string, - requestBody: { [key: string]: object }, - options: { headers: { [name: string]: string } } = { headers: {} } + requestBody: { [key: string]: object } ): Promise { const path = '/1/indexes/{indexName}'.replace( '{' + 'indexName' + '}', encodeURIComponent(String(indexName)) ); - let headers: Headers = {}; + let headers: Headers = { Accept: 'application/json' }; let queryParameters: Record = {}; - const produces = ['application/json']; - // give precedence to 'application/json' - if (produces.indexOf('application/json') >= 0) { - headers.Accept = 'application/json'; - } else { - headers.Accept = produces.join(','); - } - let formParams: Record = {}; - // verify required parameter 'indexName' is not null or undefined if (indexName === null || indexName === undefined) { throw new Error( 'Required parameter indexName was null or undefined when calling saveObject.' ); } - // verify required parameter 'requestBody' is not null or undefined if (requestBody === null || requestBody === undefined) { throw new Error( 'Required parameter requestBody was null or undefined when calling saveObject.' ); } - headers = { ...headers, ...options.headers }; - const request: Request = { method: 'POST', path, - data: ObjectSerializer.serialize(requestBody, '{ [key: string]: object; }'), + data: requestBody, }; const requestOptions: RequestOptions = { @@ -264,29 +179,7 @@ export class SearchApi { queryParameters, }; - let authenticationPromise = Promise.resolve(); - if (this.authentications.apiKey.apiKey) { - authenticationPromise = authenticationPromise.then(() => - this.authentications.apiKey.applyToRequest(requestOptions) - ); - } - if (this.authentications.appId.apiKey) { - authenticationPromise = authenticationPromise.then(() => - this.authentications.appId.applyToRequest(requestOptions) - ); - } - authenticationPromise = authenticationPromise.then(() => - this.authentications.default.applyToRequest(requestOptions) - ); - - let interceptorPromise = authenticationPromise; - for (const interceptor of this.interceptors) { - interceptorPromise = interceptorPromise.then(() => interceptor(requestOptions)); - } - - await interceptorPromise; - - return this.transporter.request(request, requestOptions); + return this.sendRequest(request, requestOptions); } /** * @@ -296,45 +189,29 @@ export class SearchApi { */ public async search( indexName: string, - searchParamsSearchParamsString: SearchParams | SearchParamsString, - options: { headers: { [name: string]: string } } = { headers: {} } + searchParamsSearchParamsString: SearchParams | SearchParamsString ): Promise { const path = '/1/indexes/{indexName}/query'.replace( '{' + 'indexName' + '}', encodeURIComponent(String(indexName)) ); - let headers: Headers = {}; + let headers: Headers = { Accept: 'application/json' }; let queryParameters: Record = {}; - const produces = ['application/json']; - // give precedence to 'application/json' - if (produces.indexOf('application/json') >= 0) { - headers.Accept = 'application/json'; - } else { - headers.Accept = produces.join(','); - } - let formParams: Record = {}; - // verify required parameter 'indexName' is not null or undefined if (indexName === null || indexName === undefined) { throw new Error('Required parameter indexName was null or undefined when calling search.'); } - // verify required parameter 'searchParamsSearchParamsString' is not null or undefined if (searchParamsSearchParamsString === null || searchParamsSearchParamsString === undefined) { throw new Error( 'Required parameter searchParamsSearchParamsString was null or undefined when calling search.' ); } - headers = { ...headers, ...options.headers }; - const request: Request = { method: 'POST', path, - data: ObjectSerializer.serialize( - searchParamsSearchParamsString, - 'SearchParams | SearchParamsString' - ), + data: searchParamsSearchParamsString, }; const requestOptions: RequestOptions = { @@ -342,28 +219,6 @@ export class SearchApi { queryParameters, }; - let authenticationPromise = Promise.resolve(); - if (this.authentications.apiKey.apiKey) { - authenticationPromise = authenticationPromise.then(() => - this.authentications.apiKey.applyToRequest(requestOptions) - ); - } - if (this.authentications.appId.apiKey) { - authenticationPromise = authenticationPromise.then(() => - this.authentications.appId.applyToRequest(requestOptions) - ); - } - authenticationPromise = authenticationPromise.then(() => - this.authentications.default.applyToRequest(requestOptions) - ); - - let interceptorPromise = authenticationPromise; - for (const interceptor of this.interceptors) { - interceptorPromise = interceptorPromise.then(() => interceptor(requestOptions)); - } - - await interceptorPromise; - - return this.transporter.request(request, requestOptions); + return this.sendRequest(request, requestOptions); } } diff --git a/clients/algoliasearch-client-javascript/model/batchObject.ts b/clients/algoliasearch-client-javascript/model/batchObject.ts index 0a1428e699a..bd5a644bd13 100644 --- a/clients/algoliasearch-client-javascript/model/batchObject.ts +++ b/clients/algoliasearch-client-javascript/model/batchObject.ts @@ -1,19 +1,5 @@ import { Operation } from './operation'; -export class BatchObject { - 'requests'?: Array; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'requests', - baseName: 'requests', - type: 'Array', - }, - ]; - - static getAttributeTypeMap() { - return BatchObject.attributeTypeMap; - } -} +export type BatchObject = { + requests?: Array; +}; diff --git a/clients/algoliasearch-client-javascript/model/batchResponse.ts b/clients/algoliasearch-client-javascript/model/batchResponse.ts index c5eeb8d6197..6c1c5bff827 100644 --- a/clients/algoliasearch-client-javascript/model/batchResponse.ts +++ b/clients/algoliasearch-client-javascript/model/batchResponse.ts @@ -1,29 +1,10 @@ -export class BatchResponse { +export type BatchResponse = { /** * taskID of the indexing task to wait for. */ - 'taskID'?: number; + taskID?: number; /** * List of objectID */ - 'objectIDs'?: Array; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'taskID', - baseName: 'taskID', - type: 'number', - }, - { - name: 'objectIDs', - baseName: 'objectIDs', - type: 'Array', - }, - ]; - - static getAttributeTypeMap() { - return BatchResponse.attributeTypeMap; - } -} + objectIDs?: Array; +}; diff --git a/clients/algoliasearch-client-javascript/model/errorBase.ts b/clients/algoliasearch-client-javascript/model/errorBase.ts index ab910b0cef0..d5b7c95506d 100644 --- a/clients/algoliasearch-client-javascript/model/errorBase.ts +++ b/clients/algoliasearch-client-javascript/model/errorBase.ts @@ -1,21 +1,6 @@ /** * Error */ -// export class ErrorBase extends null -export class ErrorBase { - 'message'?: string; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'message', - baseName: 'message', - type: 'string', - }, - ]; - - static getAttributeTypeMap() { - return ErrorBase.attributeTypeMap; - } -} +export type ErrorBase = { + message?: string; +}; diff --git a/clients/algoliasearch-client-javascript/model/highlightResult.ts b/clients/algoliasearch-client-javascript/model/highlightResult.ts index d3101098fe7..7955038cba7 100644 --- a/clients/algoliasearch-client-javascript/model/highlightResult.ts +++ b/clients/algoliasearch-client-javascript/model/highlightResult.ts @@ -1,55 +1,26 @@ -export class HighlightResult { +export type HighlightResult = { /** * Markup text with occurrences highlighted. */ - 'value'?: string; + value?: string; /** * Indicates how well the attribute matched the search query. */ - 'matchLevel'?: HighlightResult.MatchLevelEnum; + matchLevel?: HighlightResult.MatchLevelEnum; /** * List of words from the query that matched the object. */ - 'matchedWords'?: Array; + matchedWords?: Array; /** * Whether the entire attribute value is highlighted. */ - 'fullyHighlighted'?: boolean; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'value', - baseName: 'value', - type: 'string', - }, - { - name: 'matchLevel', - baseName: 'matchLevel', - type: 'HighlightResult.MatchLevelEnum', - }, - { - name: 'matchedWords', - baseName: 'matchedWords', - type: 'Array', - }, - { - name: 'fullyHighlighted', - baseName: 'fullyHighlighted', - type: 'boolean', - }, - ]; - - static getAttributeTypeMap() { - return HighlightResult.attributeTypeMap; - } -} + fullyHighlighted?: boolean; +}; export namespace HighlightResult { export enum MatchLevelEnum { - None = 'none', - Partial = 'partial', - Full = 'full', + None = 'none', + Partial = 'partial', + Full = 'full', } } diff --git a/clients/algoliasearch-client-javascript/model/models.ts b/clients/algoliasearch-client-javascript/model/models.ts index edd74146def..f01a2e4f097 100644 --- a/clients/algoliasearch-client-javascript/model/models.ts +++ b/clients/algoliasearch-client-javascript/model/models.ts @@ -18,182 +18,6 @@ export * from './searchResponse'; export * from './searchResponseFacetsStats'; export * from './snippetResult'; -import { BatchObject } from './batchObject'; -import { BatchResponse } from './batchResponse'; -import { ErrorBase } from './errorBase'; -import { HighlightResult } from './highlightResult'; -import { MultipleQueries } from './multipleQueries'; -import { MultipleQueriesObject } from './multipleQueriesObject'; -import { MultipleQueriesResponse } from './multipleQueriesResponse'; -import { Operation } from './operation'; -import { RankingInfo } from './rankingInfo'; -import { RankingInfoMatchedGeoLocation } from './rankingInfoMatchedGeoLocation'; -import { Record } from './record'; -import { SaveObjectResponse } from './saveObjectResponse'; -import { SearchParams } from './searchParams'; -import { SearchParamsString } from './searchParamsString'; -import { SearchResponse } from './searchResponse'; -import { SearchResponseFacetsStats } from './searchResponseFacetsStats'; -import { SnippetResult } from './snippetResult'; - -let primitives = ['string', 'boolean', 'double', 'integer', 'long', 'float', 'number', 'any']; - -let enumsMap: { [index: string]: any } = { - 'HighlightResult.MatchLevelEnum': HighlightResult.MatchLevelEnum, - 'MultipleQueries.TypeEnum': MultipleQueries.TypeEnum, - 'MultipleQueriesObject.StrategyEnum': MultipleQueriesObject.StrategyEnum, - 'Operation.ActionEnum': Operation.ActionEnum, - 'SearchParams.TypoToleranceEnum': SearchParams.TypoToleranceEnum, - 'SearchParams.QueryTypeEnum': SearchParams.QueryTypeEnum, - 'SearchParams.RemoveWordsIfNoResultsEnum': SearchParams.RemoveWordsIfNoResultsEnum, - 'SearchParams.ExactOnSingleWordQueryEnum': SearchParams.ExactOnSingleWordQueryEnum, - 'SearchParams.AlternativesAsExactEnum': SearchParams.AlternativesAsExactEnum, - 'SearchParams.AdvancedSyntaxFeaturesEnum': SearchParams.AdvancedSyntaxFeaturesEnum, - 'SnippetResult.MatchLevelEnum': SnippetResult.MatchLevelEnum, -}; - -let typeMap: { [index: string]: any } = { - BatchObject: BatchObject, - BatchResponse: BatchResponse, - ErrorBase: ErrorBase, - HighlightResult: HighlightResult, - MultipleQueries: MultipleQueries, - MultipleQueriesObject: MultipleQueriesObject, - MultipleQueriesResponse: MultipleQueriesResponse, - Operation: Operation, - RankingInfo: RankingInfo, - RankingInfoMatchedGeoLocation: RankingInfoMatchedGeoLocation, - Record: Record, - SaveObjectResponse: SaveObjectResponse, - SearchParams: SearchParams, - SearchParamsString: SearchParamsString, - SearchResponse: SearchResponse, - SearchResponseFacetsStats: SearchResponseFacetsStats, - SnippetResult: SnippetResult, -}; - -export class ObjectSerializer { - public static findCorrectType(data: any, expectedType: string) { - if (data == undefined) { - return expectedType; - } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { - return expectedType; - } else if (expectedType === 'Date') { - return expectedType; - } else { - if (enumsMap[expectedType]) { - return expectedType; - } - - if (!typeMap[expectedType]) { - return expectedType; // w/e we don't know the type - } - - // Check the discriminator - let discriminatorProperty = typeMap[expectedType].discriminator; - if (discriminatorProperty == null) { - return expectedType; // the type does not have a discriminator. use it. - } else { - if (data[discriminatorProperty]) { - var discriminatorType = data[discriminatorProperty]; - if (typeMap[discriminatorType]) { - return discriminatorType; // use the type given in the discriminator - } else { - return expectedType; // discriminator did not map to a type - } - } else { - return expectedType; // discriminator was not present (or an empty string) - } - } - } - } - - public static serialize(data: any, type: string) { - if (data == undefined) { - return data; - } else if (primitives.indexOf(type.toLowerCase()) !== -1) { - return data; - } else if (type.lastIndexOf('Array<', 0) === 0) { - // string.startsWith pre es6 - let subType: string = type.replace('Array<', ''); // Array => Type> - subType = subType.substring(0, subType.length - 1); // Type> => Type - let transformedData: any[] = []; - for (let index = 0; index < data.length; index++) { - let datum = data[index]; - transformedData.push(ObjectSerializer.serialize(datum, subType)); - } - return transformedData; - } else if (type === 'Date') { - return data.toISOString(); - } else { - if (enumsMap[type]) { - return data; - } - if (!typeMap[type]) { - // in case we dont know the type - return data; - } - - // Get the actual type of this object - type = this.findCorrectType(data, type); - - // get the map for the correct type. - let attributeTypes = typeMap[type].getAttributeTypeMap(); - let instance: { [index: string]: any } = {}; - for (let index = 0; index < attributeTypes.length; index++) { - let attributeType = attributeTypes[index]; - instance[attributeType.baseName] = ObjectSerializer.serialize( - data[attributeType.name], - attributeType.type - ); - } - return instance; - } - } - - public static deserialize(data: any, type: string) { - // polymorphism may change the actual type. - type = ObjectSerializer.findCorrectType(data, type); - if (data == undefined) { - return data; - } else if (primitives.indexOf(type.toLowerCase()) !== -1) { - return data; - } else if (type.lastIndexOf('Array<', 0) === 0) { - // string.startsWith pre es6 - let subType: string = type.replace('Array<', ''); // Array => Type> - subType = subType.substring(0, subType.length - 1); // Type> => Type - let transformedData: any[] = []; - for (let index = 0; index < data.length; index++) { - let datum = data[index]; - transformedData.push(ObjectSerializer.deserialize(datum, subType)); - } - return transformedData; - } else if (type === 'Date') { - return new Date(data); - } else { - if (enumsMap[type]) { - // is Enum - return data; - } - - if (!typeMap[type]) { - // dont know the type - return data; - } - let instance = new typeMap[type](); - let attributeTypes = typeMap[type].getAttributeTypeMap(); - for (let index = 0; index < attributeTypes.length; index++) { - let attributeType = attributeTypes[index]; - instance[attributeType.name] = ObjectSerializer.deserialize( - data[attributeType.baseName], - attributeType.type - ); - } - return instance; - } - } -} - export interface Authentication { /** * Apply authentication settings to header and query params. @@ -201,18 +25,6 @@ export interface Authentication { applyToRequest(requestOptions: RequestOptions): Promise | void; } -export class HttpBearerAuth implements Authentication { - public accessToken: string | (() => string) = ''; - - applyToRequest(requestOptions: RequestOptions): void { - if (requestOptions && requestOptions.headers) { - const accessToken = - typeof this.accessToken === 'function' ? this.accessToken() : this.accessToken; - requestOptions.headers['Authorization'] = 'Bearer ' + accessToken; - } - } -} - export class ApiKeyAuth implements Authentication { public apiKey: string = ''; @@ -233,24 +45,3 @@ export class ApiKeyAuth implements Authentication { } } } - -export class OAuth implements Authentication { - public accessToken: string = ''; - - applyToRequest(requestOptions: RequestOptions): void { - if (requestOptions && requestOptions.headers) { - requestOptions.headers['Authorization'] = 'Bearer ' + this.accessToken; - } - } -} - -export class VoidAuth implements Authentication { - public username: string = ''; - public password: string = ''; - - applyToRequest(_: RequestOptions): void { - // Do nothing - } -} - -export type Interceptor = (requestOptions: RequestOptions) => Promise | void; diff --git a/clients/algoliasearch-client-javascript/model/multipleQueries.ts b/clients/algoliasearch-client-javascript/model/multipleQueries.ts index 9acaadac44f..3532f97ab78 100644 --- a/clients/algoliasearch-client-javascript/model/multipleQueries.ts +++ b/clients/algoliasearch-client-javascript/model/multipleQueries.ts @@ -1,63 +1,29 @@ -export class MultipleQueries { +export type MultipleQueries = { /** * The Algolia index name */ - 'indexName': string; + indexName: string; /** * The text to search in the index. */ - 'query'?: string; + query?: string; /** * Perform a search query with `default`, will search for facet values if `facet` is given */ - 'type'?: MultipleQueries.TypeEnum; + type?: MultipleQueries.TypeEnum; /** * The `facet` name */ - 'facet'?: string; + facet?: string; /** * A query string of search parameters */ - 'params'?: string; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'indexName', - baseName: 'indexName', - type: 'string', - }, - { - name: 'query', - baseName: 'query', - type: 'string', - }, - { - name: 'type', - baseName: 'type', - type: 'MultipleQueries.TypeEnum', - }, - { - name: 'facet', - baseName: 'facet', - type: 'string', - }, - { - name: 'params', - baseName: 'params', - type: 'string', - }, - ]; - - static getAttributeTypeMap() { - return MultipleQueries.attributeTypeMap; - } -} + params?: string; +}; export namespace MultipleQueries { export enum TypeEnum { - Default = 'default', - Facet = 'facet', + Default = 'default', + Facet = 'facet', } } diff --git a/clients/algoliasearch-client-javascript/model/multipleQueriesObject.ts b/clients/algoliasearch-client-javascript/model/multipleQueriesObject.ts index c0936841330..585892b6806 100644 --- a/clients/algoliasearch-client-javascript/model/multipleQueriesObject.ts +++ b/clients/algoliasearch-client-javascript/model/multipleQueriesObject.ts @@ -1,32 +1,13 @@ import { MultipleQueries } from './multipleQueries'; -export class MultipleQueriesObject { - 'requests': Array; - 'strategy'?: MultipleQueriesObject.StrategyEnum; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'requests', - baseName: 'requests', - type: 'Array', - }, - { - name: 'strategy', - baseName: 'strategy', - type: 'MultipleQueriesObject.StrategyEnum', - }, - ]; - - static getAttributeTypeMap() { - return MultipleQueriesObject.attributeTypeMap; - } -} +export type MultipleQueriesObject = { + requests: Array; + strategy?: MultipleQueriesObject.StrategyEnum; +}; export namespace MultipleQueriesObject { export enum StrategyEnum { - None = 'none', - StopIfEnoughMatches = 'stopIfEnoughMatches', + None = 'none', + StopIfEnoughMatches = 'stopIfEnoughMatches', } } diff --git a/clients/algoliasearch-client-javascript/model/multipleQueriesResponse.ts b/clients/algoliasearch-client-javascript/model/multipleQueriesResponse.ts index 334774a50ec..c48347e626a 100644 --- a/clients/algoliasearch-client-javascript/model/multipleQueriesResponse.ts +++ b/clients/algoliasearch-client-javascript/model/multipleQueriesResponse.ts @@ -1,19 +1,5 @@ import { SearchResponse } from './searchResponse'; -export class MultipleQueriesResponse { - 'results'?: Array; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'results', - baseName: 'results', - type: 'Array', - }, - ]; - - static getAttributeTypeMap() { - return MultipleQueriesResponse.attributeTypeMap; - } -} +export type MultipleQueriesResponse = { + results?: Array; +}; diff --git a/clients/algoliasearch-client-javascript/model/operation.ts b/clients/algoliasearch-client-javascript/model/operation.ts index 2c008cdad59..ae46bc7178d 100644 --- a/clients/algoliasearch-client-javascript/model/operation.ts +++ b/clients/algoliasearch-client-javascript/model/operation.ts @@ -1,41 +1,22 @@ -export class Operation { +export type Operation = { /** * type of operation */ - 'action'?: Operation.ActionEnum; + action?: Operation.ActionEnum; /** * arguments to the operation (depends on the type of the operation) */ - 'body'?: { [key: string]: object }; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'action', - baseName: 'action', - type: 'Operation.ActionEnum', - }, - { - name: 'body', - baseName: 'body', - type: '{ [key: string]: object; }', - }, - ]; - - static getAttributeTypeMap() { - return Operation.attributeTypeMap; - } -} + body?: { [key: string]: object }; +}; export namespace Operation { export enum ActionEnum { - AddObject = 'addObject', - UpdateObject = 'updateObject', - PartialUpdateObject = 'partialUpdateObject', - PartialUpdateObjectNoCreate = 'partialUpdateObjectNoCreate', - DeleteObject = 'deleteObject', - Delete = 'delete', - Clear = 'clear', + AddObject = 'addObject', + UpdateObject = 'updateObject', + PartialUpdateObject = 'partialUpdateObject', + PartialUpdateObjectNoCreate = 'partialUpdateObjectNoCreate', + DeleteObject = 'deleteObject', + Delete = 'delete', + Clear = 'clear', } } diff --git a/clients/algoliasearch-client-javascript/model/rankingInfo.ts b/clients/algoliasearch-client-javascript/model/rankingInfo.ts index 7af75621603..0b163f33028 100644 --- a/clients/algoliasearch-client-javascript/model/rankingInfo.ts +++ b/clients/algoliasearch-client-javascript/model/rankingInfo.ts @@ -1,109 +1,45 @@ import { RankingInfoMatchedGeoLocation } from './rankingInfoMatchedGeoLocation'; -export class RankingInfo { +export type RankingInfo = { /** * This field is reserved for advanced usage. */ - 'filters'?: number; + filters?: number; /** * Position of the most important matched attribute in the attributes to index list. */ - 'firstMatchedWord'?: number; + firstMatchedWord?: number; /** * Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision (in meters). */ - 'geoDistance'?: number; + geoDistance?: number; /** * Precision used when computing the geo distance, in meters. */ - 'geoPrecision'?: number; - 'matchedGeoLocation'?: { [key: string]: RankingInfoMatchedGeoLocation }; + geoPrecision?: number; + matchedGeoLocation?: { [key: string]: RankingInfoMatchedGeoLocation }; /** * Number of exactly matched words. */ - 'nbExactWords'?: number; + nbExactWords?: number; /** * Number of typos encountered when matching the record. */ - 'nbTypos'?: number; + nbTypos?: number; /** * Present and set to true if a Rule promoted the hit. */ - 'promoted'?: boolean; + promoted?: boolean; /** * When the query contains more than one word, the sum of the distances between matched words (in meters). */ - 'proximityDistance'?: number; + proximityDistance?: number; /** * Custom ranking for the object, expressed as a single integer value. */ - 'userScore'?: number; + userScore?: number; /** * Number of matched words, including prefixes and typos. */ - 'word'?: number; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'filters', - baseName: 'filters', - type: 'number', - }, - { - name: 'firstMatchedWord', - baseName: 'firstMatchedWord', - type: 'number', - }, - { - name: 'geoDistance', - baseName: 'geoDistance', - type: 'number', - }, - { - name: 'geoPrecision', - baseName: 'geoPrecision', - type: 'number', - }, - { - name: 'matchedGeoLocation', - baseName: 'matchedGeoLocation', - type: '{ [key: string]: RankingInfoMatchedGeoLocation; }', - }, - { - name: 'nbExactWords', - baseName: 'nbExactWords', - type: 'number', - }, - { - name: 'nbTypos', - baseName: 'nbTypos', - type: 'number', - }, - { - name: 'promoted', - baseName: 'promoted', - type: 'boolean', - }, - { - name: 'proximityDistance', - baseName: 'proximityDistance', - type: 'number', - }, - { - name: 'userScore', - baseName: 'userScore', - type: 'number', - }, - { - name: 'word', - baseName: 'word', - type: 'number', - }, - ]; - - static getAttributeTypeMap() { - return RankingInfo.attributeTypeMap; - } -} + word?: number; +}; diff --git a/clients/algoliasearch-client-javascript/model/rankingInfoMatchedGeoLocation.ts b/clients/algoliasearch-client-javascript/model/rankingInfoMatchedGeoLocation.ts index 58aab4d485f..bc9ce847180 100644 --- a/clients/algoliasearch-client-javascript/model/rankingInfoMatchedGeoLocation.ts +++ b/clients/algoliasearch-client-javascript/model/rankingInfoMatchedGeoLocation.ts @@ -1,38 +1,14 @@ -export class RankingInfoMatchedGeoLocation { +export type RankingInfoMatchedGeoLocation = { /** * Latitude of the matched location. */ - 'lat'?: number; + lat?: number; /** * Longitude of the matched location. */ - 'lng'?: number; + lng?: number; /** * Distance between the matched location and the search location (in meters). */ - 'distance'?: number; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'lat', - baseName: 'lat', - type: 'number', - }, - { - name: 'lng', - baseName: 'lng', - type: 'number', - }, - { - name: 'distance', - baseName: 'distance', - type: 'number', - }, - ]; - - static getAttributeTypeMap() { - return RankingInfoMatchedGeoLocation.attributeTypeMap; - } -} + distance?: number; +}; diff --git a/clients/algoliasearch-client-javascript/model/record.ts b/clients/algoliasearch-client-javascript/model/record.ts index e833f3e2aa6..d0e79082fb9 100644 --- a/clients/algoliasearch-client-javascript/model/record.ts +++ b/clients/algoliasearch-client-javascript/model/record.ts @@ -5,48 +5,13 @@ import { SnippetResult } from './snippetResult'; /** * A single record */ -// export class Record extends null -export class Record { +export type Record = { /** * Unique identifier of the object */ - 'objectID': string; - '_highlightResult'?: HighlightResult; - '_snippetResult'?: SnippetResult; - '_rankingInfo'?: RankingInfo; - '_distinctSeqID'?: number; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'objectID', - baseName: 'objectID', - type: 'string', - }, - { - name: '_highlightResult', - baseName: '_highlightResult', - type: 'HighlightResult', - }, - { - name: '_snippetResult', - baseName: '_snippetResult', - type: 'SnippetResult', - }, - { - name: '_rankingInfo', - baseName: '_rankingInfo', - type: 'RankingInfo', - }, - { - name: '_distinctSeqID', - baseName: '_distinctSeqID', - type: 'number', - }, - ]; - - static getAttributeTypeMap() { - return Record.attributeTypeMap; - } -} + objectID: string; + _highlightResult?: HighlightResult; + _snippetResult?: SnippetResult; + _rankingInfo?: RankingInfo; + _distinctSeqID?: number; +}; diff --git a/clients/algoliasearch-client-javascript/model/saveObjectResponse.ts b/clients/algoliasearch-client-javascript/model/saveObjectResponse.ts index 4761e6f28c0..44a2bcc659f 100644 --- a/clients/algoliasearch-client-javascript/model/saveObjectResponse.ts +++ b/clients/algoliasearch-client-javascript/model/saveObjectResponse.ts @@ -1,35 +1,11 @@ -export class SaveObjectResponse { - 'createdAt'?: string; +export type SaveObjectResponse = { + createdAt?: string; /** * taskID of the indexing task to wait for. */ - 'taskID'?: number; + taskID?: number; /** * Unique identifier of the object */ - 'objectID'?: string; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'createdAt', - baseName: 'createdAt', - type: 'string', - }, - { - name: 'taskID', - baseName: 'taskID', - type: 'number', - }, - { - name: 'objectID', - baseName: 'objectID', - type: 'string', - }, - ]; - - static getAttributeTypeMap() { - return SaveObjectResponse.attributeTypeMap; - } -} + objectID?: string; +}; diff --git a/clients/algoliasearch-client-javascript/model/searchParams.ts b/clients/algoliasearch-client-javascript/model/searchParams.ts index 3728d484678..c6b8bfcf7ca 100644 --- a/clients/algoliasearch-client-javascript/model/searchParams.ts +++ b/clients/algoliasearch-client-javascript/model/searchParams.ts @@ -1,735 +1,341 @@ -export class SearchParams { +export type SearchParams = { /** * The text to search in the index. */ - 'query': string; + query: string; /** * Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ - 'similarQuery'?: string; + similarQuery?: string; /** * The complete list of attributes used for searching. */ - 'searchableAttributes'?: Array; + searchableAttributes?: Array; /** * The complete list of attributes that will be used for faceting. */ - 'attributesForFaceting'?: Array; + attributesForFaceting?: Array; /** * List of attributes that can’t be retrieved at query time. */ - 'unretrievableAttributes'?: Array; + unretrievableAttributes?: Array; /** * This parameter controls which attributes to retrieve and which not to retrieve. */ - 'attributesToRetrieve'?: Array; + attributesToRetrieve?: Array; /** * Restricts a given query to look in only a subset of your searchable attributes. */ - 'restrictSearchableAttributes'?: Array; + restrictSearchableAttributes?: Array; /** * Controls how Algolia should sort your results. */ - 'ranking'?: Array; + ranking?: Array; /** * Specifies the custom ranking criterion. */ - 'customRanking'?: Array; + customRanking?: Array; /** * Controls the relevancy threshold below which less relevant results aren’t included in the results. */ - 'relevancyStrictness'?: number; + relevancyStrictness?: number; /** * Filter the query with numeric, facet and/or tag filters. */ - 'filters'?: string; + filters?: string; /** * Filter hits by facet value. */ - 'facetFilters'?: Array; + facetFilters?: Array; /** * Create filters for ranking purposes, where records that match the filter are ranked higher, or lower in the case of a negative optional filter. */ - 'optionalFilters'?: Array; + optionalFilters?: Array; /** * Filter on numeric attributes. */ - 'numericFilters'?: Array; + numericFilters?: Array; /** * Filter hits by tags. */ - 'tagFilters'?: Array; + tagFilters?: Array; /** * Determines how to calculate the total score for filtering. */ - 'sumOrFiltersScores'?: boolean; + sumOrFiltersScores?: boolean; /** * Retrieve facets and their facet values. */ - 'facets'?: Array; + facets?: Array; /** * Maximum number of facet values to return for each facet during a regular search. */ - 'maxValuesPerFacet'?: number; + maxValuesPerFacet?: number; /** * Force faceting to be applied after de-duplication (via the Distinct setting). */ - 'facetingAfterDistinct'?: boolean; + facetingAfterDistinct?: boolean; /** * Controls how facet values are fetched. */ - 'sortFacetValuesBy'?: string; + sortFacetValuesBy?: string; /** * List of attributes to highlight. */ - 'attributesToHighlight'?: Array; + attributesToHighlight?: Array; /** * List of attributes to snippet, with an optional maximum number of words to snippet. */ - 'attributesToSnippet'?: Array; + attributesToSnippet?: Array; /** * The HTML string to insert before the highlighted parts in all highlight and snippet results. */ - 'highlightPreTag'?: string; + highlightPreTag?: string; /** * The HTML string to insert after the highlighted parts in all highlight and snippet results. */ - 'highlightPostTag'?: string; + highlightPostTag?: string; /** * String used as an ellipsis indicator when a snippet is truncated. */ - 'snippetEllipsisText'?: string; + snippetEllipsisText?: string; /** * Restrict highlighting and snippeting to items that matched the query. */ - 'restrictHighlightAndSnippetArrays'?: boolean; + restrictHighlightAndSnippetArrays?: boolean; /** * Specify the page to retrieve. */ - 'page'?: number; + page?: number; /** * Set the number of hits per page. */ - 'hitsPerPage'?: number; + hitsPerPage?: number; /** * Specify the offset of the first hit to return. */ - 'offset'?: number; + offset?: number; /** * Set the number of hits to retrieve (used only with offset). */ - 'length'?: number; + length?: number; /** * Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ - 'minWordSizefor1Typo'?: number; + minWordSizefor1Typo?: number; /** * Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ - 'minWordSizefor2Typos'?: number; + minWordSizefor2Typos?: number; /** * Controls whether typo tolerance is enabled and how it is applied. */ - 'typoTolerance'?: SearchParams.TypoToleranceEnum; + typoTolerance?: SearchParams.TypoToleranceEnum; /** * Whether to allow typos on numbers (“numeric tokens”) in the query string. */ - 'allowTyposOnNumericTokens'?: boolean; + allowTyposOnNumericTokens?: boolean; /** * List of attributes on which you want to disable typo tolerance. */ - 'disableTypoToleranceOnAttributes'?: Array; + disableTypoToleranceOnAttributes?: Array; /** * Control which separators are indexed. */ - 'separatorsToIndex'?: string; + separatorsToIndex?: string; /** * Search for entries around a central geolocation, enabling a geo search within a circular area. */ - 'aroundLatLng'?: string; + aroundLatLng?: string; /** * Search for entries around a given location automatically computed from the requester’s IP address. */ - 'aroundLatLngViaIP'?: boolean; - 'aroundRadius'?: number | string; + aroundLatLngViaIP?: boolean; + aroundRadius?: number | string; /** * Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ - 'aroundPrecision'?: number; + aroundPrecision?: number; /** * Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ - 'minimumAroundRadius'?: number; + minimumAroundRadius?: number; /** * Search inside a rectangular area (in geo coordinates). */ - 'insideBoundingBox'?: Array; + insideBoundingBox?: Array; /** * Search inside a polygon (in geo coordinates). */ - 'insidePolygon'?: Array; + insidePolygon?: Array; /** * Treats singular, plurals, and other forms of declensions as matching terms. */ - 'ignorePlurals'?: string; + ignorePlurals?: string; /** * Removes stop (common) words from the query before executing it. */ - 'removeStopWords'?: string; + removeStopWords?: string; /** * List of characters that the engine shouldn’t automatically normalize. */ - 'keepDiacriticsOnCharacters'?: string; + keepDiacriticsOnCharacters?: string; /** * Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ - 'queryLanguages'?: Array; + queryLanguages?: Array; /** * This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ - 'naturalLanguages'?: Array; + naturalLanguages?: Array; /** * Splits compound words into their composing atoms in the query. */ - 'decompoundQuery'?: boolean; + decompoundQuery?: boolean; /** * Whether Rules should be globally enabled. */ - 'enableRules'?: boolean; + enableRules?: boolean; /** * Enables contextual rules. */ - 'ruleContexts'?: Array; + ruleContexts?: Array; /** * Enable the Personalization feature. */ - 'enablePersonalization'?: boolean; + enablePersonalization?: boolean; /** * Define the impact of the Personalization feature. */ - 'personalizationImpact'?: number; + personalizationImpact?: number; /** * Associates a certain user token with the current search. */ - 'userToken'?: string; + userToken?: string; /** * Controls if and how query words are interpreted as prefixes. */ - 'queryType'?: SearchParams.QueryTypeEnum; + queryType?: SearchParams.QueryTypeEnum; /** * Selects a strategy to remove words from the query when it doesn’t match any hits. */ - 'removeWordsIfNoResults'?: SearchParams.RemoveWordsIfNoResultsEnum; + removeWordsIfNoResults?: SearchParams.RemoveWordsIfNoResultsEnum; /** * Enables the advanced query syntax. */ - 'advancedSyntax'?: boolean; + advancedSyntax?: boolean; /** * A list of words that should be considered as optional when found in the query. */ - 'optionalWords'?: Array; + optionalWords?: Array; /** * List of attributes on which you want to disable the exact ranking criterion. */ - 'disableExactOnAttributes'?: Array; + disableExactOnAttributes?: Array; /** * Controls how the exact ranking criterion is computed when the query contains only one word. */ - 'exactOnSingleWordQuery'?: SearchParams.ExactOnSingleWordQueryEnum; + exactOnSingleWordQuery?: SearchParams.ExactOnSingleWordQueryEnum; /** * List of alternatives that should be considered an exact match by the exact ranking criterion. */ - 'alternativesAsExact'?: Array; + alternativesAsExact?: Array; /** * Allows you to specify which advanced syntax features are active when ‘advancedSyntax’ is enabled. */ - 'advancedSyntaxFeatures'?: Array; + advancedSyntaxFeatures?: Array; /** * Enables de-duplication or grouping of results. */ - 'distinct'?: number; + distinct?: number; /** * Retrieve detailed ranking information. */ - 'getRankingInfo'?: boolean; + getRankingInfo?: boolean; /** * Enable the Click Analytics feature. */ - 'clickAnalytics'?: boolean; + clickAnalytics?: boolean; /** * Whether the current query will be taken into account in the Analytics. */ - 'analytics'?: boolean; + analytics?: boolean; /** * List of tags to apply to the query for analytics purposes. */ - 'analyticsTags'?: Array; + analyticsTags?: Array; /** * Whether to take into account an index’s synonyms for a particular search. */ - 'synonyms'?: boolean; + synonyms?: boolean; /** * Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ - 'replaceSynonymsInHighlight'?: boolean; + replaceSynonymsInHighlight?: boolean; /** * Precision of the proximity ranking criterion. */ - 'minProximity'?: number; + minProximity?: number; /** * Choose which fields to return in the API response. This parameters applies to search and browse queries. */ - 'responseFields'?: Array; + responseFields?: Array; /** * Maximum number of facet hits to return during a search for facet values. */ - 'maxFacetHits'?: number; + maxFacetHits?: number; /** * Whether to include or exclude a query from the processing-time percentile computation. */ - 'percentileComputation'?: boolean; + percentileComputation?: boolean; /** * When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ - 'attributeCriteriaComputedByMinProximity'?: boolean; + attributeCriteriaComputedByMinProximity?: boolean; /** * Whether this search should participate in running AB tests. */ - 'enableABTest'?: boolean; + enableABTest?: boolean; /** * Whether this search should use AI Re-Ranking. */ - 'enableReRanking'?: boolean; + enableReRanking?: boolean; /** * Content defining how the search interface should be rendered. Can be set via the settings for a default value and can be overridden via rules. */ - 'renderingContent'?: object; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'query', - baseName: 'query', - type: 'string', - }, - { - name: 'similarQuery', - baseName: 'similarQuery', - type: 'string', - }, - { - name: 'searchableAttributes', - baseName: 'searchableAttributes', - type: 'Array', - }, - { - name: 'attributesForFaceting', - baseName: 'attributesForFaceting', - type: 'Array', - }, - { - name: 'unretrievableAttributes', - baseName: 'unretrievableAttributes', - type: 'Array', - }, - { - name: 'attributesToRetrieve', - baseName: 'attributesToRetrieve', - type: 'Array', - }, - { - name: 'restrictSearchableAttributes', - baseName: 'restrictSearchableAttributes', - type: 'Array', - }, - { - name: 'ranking', - baseName: 'ranking', - type: 'Array', - }, - { - name: 'customRanking', - baseName: 'customRanking', - type: 'Array', - }, - { - name: 'relevancyStrictness', - baseName: 'relevancyStrictness', - type: 'number', - }, - { - name: 'filters', - baseName: 'filters', - type: 'string', - }, - { - name: 'facetFilters', - baseName: 'facetFilters', - type: 'Array', - }, - { - name: 'optionalFilters', - baseName: 'optionalFilters', - type: 'Array', - }, - { - name: 'numericFilters', - baseName: 'numericFilters', - type: 'Array', - }, - { - name: 'tagFilters', - baseName: 'tagFilters', - type: 'Array', - }, - { - name: 'sumOrFiltersScores', - baseName: 'sumOrFiltersScores', - type: 'boolean', - }, - { - name: 'facets', - baseName: 'facets', - type: 'Array', - }, - { - name: 'maxValuesPerFacet', - baseName: 'maxValuesPerFacet', - type: 'number', - }, - { - name: 'facetingAfterDistinct', - baseName: 'facetingAfterDistinct', - type: 'boolean', - }, - { - name: 'sortFacetValuesBy', - baseName: 'sortFacetValuesBy', - type: 'string', - }, - { - name: 'attributesToHighlight', - baseName: 'attributesToHighlight', - type: 'Array', - }, - { - name: 'attributesToSnippet', - baseName: 'attributesToSnippet', - type: 'Array', - }, - { - name: 'highlightPreTag', - baseName: 'highlightPreTag', - type: 'string', - }, - { - name: 'highlightPostTag', - baseName: 'highlightPostTag', - type: 'string', - }, - { - name: 'snippetEllipsisText', - baseName: 'snippetEllipsisText', - type: 'string', - }, - { - name: 'restrictHighlightAndSnippetArrays', - baseName: 'restrictHighlightAndSnippetArrays', - type: 'boolean', - }, - { - name: 'page', - baseName: 'page', - type: 'number', - }, - { - name: 'hitsPerPage', - baseName: 'hitsPerPage', - type: 'number', - }, - { - name: 'offset', - baseName: 'offset', - type: 'number', - }, - { - name: 'length', - baseName: 'length', - type: 'number', - }, - { - name: 'minWordSizefor1Typo', - baseName: 'minWordSizefor1Typo', - type: 'number', - }, - { - name: 'minWordSizefor2Typos', - baseName: 'minWordSizefor2Typos', - type: 'number', - }, - { - name: 'typoTolerance', - baseName: 'typoTolerance', - type: 'SearchParams.TypoToleranceEnum', - }, - { - name: 'allowTyposOnNumericTokens', - baseName: 'allowTyposOnNumericTokens', - type: 'boolean', - }, - { - name: 'disableTypoToleranceOnAttributes', - baseName: 'disableTypoToleranceOnAttributes', - type: 'Array', - }, - { - name: 'separatorsToIndex', - baseName: 'separatorsToIndex', - type: 'string', - }, - { - name: 'aroundLatLng', - baseName: 'aroundLatLng', - type: 'string', - }, - { - name: 'aroundLatLngViaIP', - baseName: 'aroundLatLngViaIP', - type: 'boolean', - }, - { - name: 'aroundRadius', - baseName: 'aroundRadius', - type: 'number | string', - }, - { - name: 'aroundPrecision', - baseName: 'aroundPrecision', - type: 'number', - }, - { - name: 'minimumAroundRadius', - baseName: 'minimumAroundRadius', - type: 'number', - }, - { - name: 'insideBoundingBox', - baseName: 'insideBoundingBox', - type: 'Array', - }, - { - name: 'insidePolygon', - baseName: 'insidePolygon', - type: 'Array', - }, - { - name: 'ignorePlurals', - baseName: 'ignorePlurals', - type: 'string', - }, - { - name: 'removeStopWords', - baseName: 'removeStopWords', - type: 'string', - }, - { - name: 'keepDiacriticsOnCharacters', - baseName: 'keepDiacriticsOnCharacters', - type: 'string', - }, - { - name: 'queryLanguages', - baseName: 'queryLanguages', - type: 'Array', - }, - { - name: 'naturalLanguages', - baseName: 'naturalLanguages', - type: 'Array', - }, - { - name: 'decompoundQuery', - baseName: 'decompoundQuery', - type: 'boolean', - }, - { - name: 'enableRules', - baseName: 'enableRules', - type: 'boolean', - }, - { - name: 'ruleContexts', - baseName: 'ruleContexts', - type: 'Array', - }, - { - name: 'enablePersonalization', - baseName: 'enablePersonalization', - type: 'boolean', - }, - { - name: 'personalizationImpact', - baseName: 'personalizationImpact', - type: 'number', - }, - { - name: 'userToken', - baseName: 'userToken', - type: 'string', - }, - { - name: 'queryType', - baseName: 'queryType', - type: 'SearchParams.QueryTypeEnum', - }, - { - name: 'removeWordsIfNoResults', - baseName: 'removeWordsIfNoResults', - type: 'SearchParams.RemoveWordsIfNoResultsEnum', - }, - { - name: 'advancedSyntax', - baseName: 'advancedSyntax', - type: 'boolean', - }, - { - name: 'optionalWords', - baseName: 'optionalWords', - type: 'Array', - }, - { - name: 'disableExactOnAttributes', - baseName: 'disableExactOnAttributes', - type: 'Array', - }, - { - name: 'exactOnSingleWordQuery', - baseName: 'exactOnSingleWordQuery', - type: 'SearchParams.ExactOnSingleWordQueryEnum', - }, - { - name: 'alternativesAsExact', - baseName: 'alternativesAsExact', - type: 'Array', - }, - { - name: 'advancedSyntaxFeatures', - baseName: 'advancedSyntaxFeatures', - type: 'Array', - }, - { - name: 'distinct', - baseName: 'distinct', - type: 'number', - }, - { - name: 'getRankingInfo', - baseName: 'getRankingInfo', - type: 'boolean', - }, - { - name: 'clickAnalytics', - baseName: 'clickAnalytics', - type: 'boolean', - }, - { - name: 'analytics', - baseName: 'analytics', - type: 'boolean', - }, - { - name: 'analyticsTags', - baseName: 'analyticsTags', - type: 'Array', - }, - { - name: 'synonyms', - baseName: 'synonyms', - type: 'boolean', - }, - { - name: 'replaceSynonymsInHighlight', - baseName: 'replaceSynonymsInHighlight', - type: 'boolean', - }, - { - name: 'minProximity', - baseName: 'minProximity', - type: 'number', - }, - { - name: 'responseFields', - baseName: 'responseFields', - type: 'Array', - }, - { - name: 'maxFacetHits', - baseName: 'maxFacetHits', - type: 'number', - }, - { - name: 'percentileComputation', - baseName: 'percentileComputation', - type: 'boolean', - }, - { - name: 'attributeCriteriaComputedByMinProximity', - baseName: 'attributeCriteriaComputedByMinProximity', - type: 'boolean', - }, - { - name: 'enableABTest', - baseName: 'enableABTest', - type: 'boolean', - }, - { - name: 'enableReRanking', - baseName: 'enableReRanking', - type: 'boolean', - }, - { - name: 'renderingContent', - baseName: 'renderingContent', - type: 'object', - }, - ]; - - static getAttributeTypeMap() { - return SearchParams.attributeTypeMap; - } -} + renderingContent?: object; +}; export namespace SearchParams { export enum TypoToleranceEnum { - True = 'true', - False = 'false', - Min = 'min', - Strict = 'strict', + True = 'true', + False = 'false', + Min = 'min', + Strict = 'strict', } export enum QueryTypeEnum { - PrefixLast = 'prefixLast', - PrefixAll = 'prefixAll', - PrefixNone = 'prefixNone', + PrefixLast = 'prefixLast', + PrefixAll = 'prefixAll', + PrefixNone = 'prefixNone', } export enum RemoveWordsIfNoResultsEnum { - None = 'none', - LastWords = 'lastWords', - FirstWords = 'firstWords', - AllOptional = 'allOptional', + None = 'none', + LastWords = 'lastWords', + FirstWords = 'firstWords', + AllOptional = 'allOptional', } export enum ExactOnSingleWordQueryEnum { - Attribute = 'attribute', - None = 'none', - Word = 'word', + Attribute = 'attribute', + None = 'none', + Word = 'word', } export enum AlternativesAsExactEnum { - IgnorePlurals = 'ignorePlurals', - SingleWordSynonym = 'singleWordSynonym', - MultiWordsSynonym = 'multiWordsSynonym', + IgnorePlurals = 'ignorePlurals', + SingleWordSynonym = 'singleWordSynonym', + MultiWordsSynonym = 'multiWordsSynonym', } export enum AdvancedSyntaxFeaturesEnum { - ExactPhrase = 'exactPhrase', - ExcludeWords = 'excludeWords', + ExactPhrase = 'exactPhrase', + ExcludeWords = 'excludeWords', } } diff --git a/clients/algoliasearch-client-javascript/model/searchParamsString.ts b/clients/algoliasearch-client-javascript/model/searchParamsString.ts index 968d23a198e..e0858af48a5 100644 --- a/clients/algoliasearch-client-javascript/model/searchParamsString.ts +++ b/clients/algoliasearch-client-javascript/model/searchParamsString.ts @@ -1,17 +1,3 @@ -export class SearchParamsString { - 'params'?: string; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'params', - baseName: 'params', - type: 'string', - }, - ]; - - static getAttributeTypeMap() { - return SearchParamsString.attributeTypeMap; - } -} +export type SearchParamsString = { + params?: string; +}; diff --git a/clients/algoliasearch-client-javascript/model/searchResponse.ts b/clients/algoliasearch-client-javascript/model/searchResponse.ts index 21e3c7853f4..8e848b306a2 100644 --- a/clients/algoliasearch-client-javascript/model/searchResponse.ts +++ b/clients/algoliasearch-client-javascript/model/searchResponse.ts @@ -1,236 +1,102 @@ import { Record } from './record'; import { SearchResponseFacetsStats } from './searchResponseFacetsStats'; -export class SearchResponse { +export type SearchResponse = { /** * If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. */ - 'abTestID'?: number; + abTestID?: number; /** * If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used. */ - 'abTestVariantID'?: number; + abTestVariantID?: number; /** * The computed geo location. */ - 'aroundLatLng'?: string; + aroundLatLng?: string; /** * The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. */ - 'automaticRadius'?: string; + automaticRadius?: string; /** * Whether the facet count is exhaustive or approximate. */ - 'exhaustiveFacetsCount'?: boolean; + exhaustiveFacetsCount?: boolean; /** * Indicate if the nbHits count was exhaustive or approximate */ - 'exhaustiveNbHits': boolean; + exhaustiveNbHits: boolean; /** * Indicate if the typo-tolerence search was exhaustive or approximate (only included when typo-tolerance is enabled) */ - 'exhaustiveTypo': boolean; + exhaustiveTypo: boolean; /** * A mapping of each facet name to the corresponding facet counts. */ - 'facets'?: { [key: string]: { [key: string]: string } }; + facets?: { [key: string]: { [key: string]: string } }; /** * Statistics for numerical facets. */ - 'facets_stats'?: { [key: string]: SearchResponseFacetsStats }; - 'hits': Array; + facets_stats?: { [key: string]: SearchResponseFacetsStats }; + hits: Array; /** * Set the number of hits per page. */ - 'hitsPerPage': number; + hitsPerPage: number; /** * Index name used for the query. */ - 'index'?: string; + index?: string; /** * Index name used for the query. In the case of an A/B test, the targeted index isn’t always the index used by the query. */ - 'indexUsed'?: string; + indexUsed?: string; /** * Used to return warnings about the query. */ - 'message'?: string; + message?: string; /** * Number of hits that the search query matched */ - 'nbHits': number; + nbHits: number; /** * Number of pages available for the current query */ - 'nbPages': number; + nbPages: number; /** * The number of hits selected and sorted by the relevant sort algorithm */ - 'nbSortedHits'?: number; + nbSortedHits?: number; /** * Specify the page to retrieve. */ - 'page': number; + page: number; /** * A url-encoded string of all search parameters. */ - 'params': string; + params: string; /** * The query string that will be searched, after normalization. */ - 'parsedQuery'?: string; + parsedQuery?: string; /** * Time the server took to process the request, in milliseconds. */ - 'processingTimeMS': number; + processingTimeMS: number; /** * The text to search in the index. */ - 'query': string; + query: string; /** * A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. */ - 'queryAfterRemoval'?: string; + queryAfterRemoval?: string; /** * Actual host name of the server that processed the request. */ - 'serverUsed'?: string; + serverUsed?: string; /** * Lets you store custom data in your indices. */ - 'userData'?: { [key: string]: object }; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'abTestID', - baseName: 'abTestID', - type: 'number', - }, - { - name: 'abTestVariantID', - baseName: 'abTestVariantID', - type: 'number', - }, - { - name: 'aroundLatLng', - baseName: 'aroundLatLng', - type: 'string', - }, - { - name: 'automaticRadius', - baseName: 'automaticRadius', - type: 'string', - }, - { - name: 'exhaustiveFacetsCount', - baseName: 'exhaustiveFacetsCount', - type: 'boolean', - }, - { - name: 'exhaustiveNbHits', - baseName: 'exhaustiveNbHits', - type: 'boolean', - }, - { - name: 'exhaustiveTypo', - baseName: 'exhaustiveTypo', - type: 'boolean', - }, - { - name: 'facets', - baseName: 'facets', - type: '{ [key: string]: { [key: string]: string; }; }', - }, - { - name: 'facets_stats', - baseName: 'facets_stats', - type: '{ [key: string]: SearchResponseFacetsStats; }', - }, - { - name: 'hits', - baseName: 'hits', - type: 'Array', - }, - { - name: 'hitsPerPage', - baseName: 'hitsPerPage', - type: 'number', - }, - { - name: 'index', - baseName: 'index', - type: 'string', - }, - { - name: 'indexUsed', - baseName: 'indexUsed', - type: 'string', - }, - { - name: 'message', - baseName: 'message', - type: 'string', - }, - { - name: 'nbHits', - baseName: 'nbHits', - type: 'number', - }, - { - name: 'nbPages', - baseName: 'nbPages', - type: 'number', - }, - { - name: 'nbSortedHits', - baseName: 'nbSortedHits', - type: 'number', - }, - { - name: 'page', - baseName: 'page', - type: 'number', - }, - { - name: 'params', - baseName: 'params', - type: 'string', - }, - { - name: 'parsedQuery', - baseName: 'parsedQuery', - type: 'string', - }, - { - name: 'processingTimeMS', - baseName: 'processingTimeMS', - type: 'number', - }, - { - name: 'query', - baseName: 'query', - type: 'string', - }, - { - name: 'queryAfterRemoval', - baseName: 'queryAfterRemoval', - type: 'string', - }, - { - name: 'serverUsed', - baseName: 'serverUsed', - type: 'string', - }, - { - name: 'userData', - baseName: 'userData', - type: '{ [key: string]: object; }', - }, - ]; - - static getAttributeTypeMap() { - return SearchResponse.attributeTypeMap; - } -} + userData?: { [key: string]: object }; +}; diff --git a/clients/algoliasearch-client-javascript/model/searchResponseFacetsStats.ts b/clients/algoliasearch-client-javascript/model/searchResponseFacetsStats.ts index ff2f3a37ef5..f72bd39467b 100644 --- a/clients/algoliasearch-client-javascript/model/searchResponseFacetsStats.ts +++ b/clients/algoliasearch-client-javascript/model/searchResponseFacetsStats.ts @@ -1,47 +1,18 @@ -export class SearchResponseFacetsStats { +export type SearchResponseFacetsStats = { /** * The minimum value in the result set. */ - 'min'?: number; + min?: number; /** * The maximum value in the result set. */ - 'max'?: number; + max?: number; /** * The average facet value in the result set. */ - 'avg'?: number; + avg?: number; /** * The sum of all values in the result set. */ - 'sum'?: number; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'min', - baseName: 'min', - type: 'number', - }, - { - name: 'max', - baseName: 'max', - type: 'number', - }, - { - name: 'avg', - baseName: 'avg', - type: 'number', - }, - { - name: 'sum', - baseName: 'sum', - type: 'number', - }, - ]; - - static getAttributeTypeMap() { - return SearchResponseFacetsStats.attributeTypeMap; - } -} + sum?: number; +}; diff --git a/clients/algoliasearch-client-javascript/model/snippetResult.ts b/clients/algoliasearch-client-javascript/model/snippetResult.ts index 8b5b5091816..d4fd65bce0d 100644 --- a/clients/algoliasearch-client-javascript/model/snippetResult.ts +++ b/clients/algoliasearch-client-javascript/model/snippetResult.ts @@ -1,37 +1,18 @@ -export class SnippetResult { +export type SnippetResult = { /** * Markup text with occurrences highlighted. */ - 'value'?: string; + value?: string; /** * Indicates how well the attribute matched the search query. */ - 'matchLevel'?: SnippetResult.MatchLevelEnum; - - static discriminator: string | undefined = undefined; - - static attributeTypeMap: Array<{ name: string; baseName: string; type: string }> = [ - { - name: 'value', - baseName: 'value', - type: 'string', - }, - { - name: 'matchLevel', - baseName: 'matchLevel', - type: 'SnippetResult.MatchLevelEnum', - }, - ]; - - static getAttributeTypeMap() { - return SnippetResult.attributeTypeMap; - } -} + matchLevel?: SnippetResult.MatchLevelEnum; +}; export namespace SnippetResult { export enum MatchLevelEnum { - None = 'none', - Partial = 'partial', - Full = 'full', + None = 'none', + Partial = 'partial', + Full = 'full', } } diff --git a/templates/javascript/api-single.mustache b/templates/javascript/api-single.mustache index 84cf316424d..9ebb11b699a 100644 --- a/templates/javascript/api-single.mustache +++ b/templates/javascript/api-single.mustache @@ -6,10 +6,8 @@ import { Requester } from '../utils/Requester'; {{#imports}} import { {{classname}} } from '{{filename}}'; {{/imports}} - -import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; {{#hasAuthMethods}} -import { HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; +import { ApiKeyAuth } from '../model/models'; {{/hasAuthMethods}} {{#operations}} @@ -19,196 +17,125 @@ import { HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; */ {{/description}} export enum {{classname}}ApiKeys { -{{#authMethods}} -{{#isApiKey}} - {{name}}, -{{/isApiKey}} -{{/authMethods}} + {{#authMethods}} + {{#isApiKey}} + {{name}}, + {{/isApiKey}} + {{/authMethods}} } export class {{classname}} { - private transporter: Transporter; - - protected authentications = { - 'default': new VoidAuth(), -{{#hasAuthMethods}} -{{#authMethods}} -{{#isBasicBasic}} - '{{name}}': new HttpBasicAuth(), -{{/isBasicBasic}} -{{#isBasicBearer}} - '{{name}}': new HttpBearerAuth(), -{{/isBasicBearer}} -{{#isApiKey}} - '{{name}}': new ApiKeyAuth({{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}{{#isKeyInCookie}}'cookie'{{/isKeyInCookie}}, '{{keyParamName}}'), -{{/isApiKey}} -{{#isOAuth}} - '{{name}}': new OAuth(), -{{/isOAuth}} -{{/authMethods}} -{{/hasAuthMethods}} - } - - protected interceptors: Interceptor[] = []; - - constructor(appId: string, apiKey: string, requester?: Requester) { - this.setApiKey(SearchApiApiKeys.appId, appId); - this.setApiKey(SearchApiApiKeys.apiKey, apiKey); - this.transporter = new Transporter({ - hosts: ([ - { url: `${appId}-dsn.algolia.net`, accept: 'read', protocol: 'https' }, - { url: `${appId}.algolia.net`, accept: 'write', protocol: 'https' }, - ] as Host[]).concat( - shuffle([ - { url: `${appId}-1.algolianet.com`, accept: 'readWrite', protocol: 'https' }, - { url: `${appId}-2.algolianet.com`, accept: 'readWrite', protocol: 'https' }, - { url: `${appId}-3.algolianet.com`, accept: 'readWrite', protocol: 'https' }, - ]) - ), - baseHeaders: { - 'content-type': 'application/x-www-form-urlencoded' - }, - userAgent: 'Algolia for Javascript', - timeouts: { - connect: 2, - read: 5, - write: 30, - }, - requester, - }); - } - - public setDefaultAuthentication(auth: Authentication) { - this.authentications.default = auth; - } + private transporter: Transporter; - public setApiKey(key: {{classname}}ApiKeys, value: string) { - (this.authentications as any)[{{classname}}ApiKeys[key]].apiKey = value; - } -{{#hasAuthMethods}} -{{#authMethods}} -{{#isBasicBasic}} - - set username(username: string) { - this.authentications.{{name}}.username = username; - } - - set password(password: string) { - this.authentications.{{name}}.password = password; - } -{{/isBasicBasic}} -{{#isBasicBearer}} - - set accessToken(accessToken: string | (() => string)) { - this.authentications.{{name}}.accessToken = accessToken; + protected authentications = { + {{#hasAuthMethods}} + {{#authMethods}} + {{#isApiKey}} + '{{name}}': new ApiKeyAuth({{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}{{#isKeyInCookie}}'cookie'{{/isKeyInCookie}}, '{{keyParamName}}'), + {{/isApiKey}} + {{/authMethods}} + {{/hasAuthMethods}} + } + + constructor(appId: string, apiKey: string, requester?: Requester) { + this.setApiKey(SearchApiApiKeys.appId, appId); + this.setApiKey(SearchApiApiKeys.apiKey, apiKey); + this.transporter = new Transporter({ + hosts: ( + [ + { url: `${appId}-dsn.algolia.net`, accept: 'read', protocol: 'https' }, + { url: `${appId}.algolia.net`, accept: 'write', protocol: 'https' }, + ] as Host[] + ).concat( + shuffle([ + { url: `${appId}-1.algolianet.com`, accept: 'readWrite', protocol: 'https' }, + { url: `${appId}-2.algolianet.com`, accept: 'readWrite', protocol: 'https' }, + { url: `${appId}-3.algolianet.com`, accept: 'readWrite', protocol: 'https' }, + ]) + ), + baseHeaders: { + 'content-type': 'application/x-www-form-urlencoded' + }, + userAgent: 'Algolia for Javascript', + timeouts: { + connect: 2, + read: 5, + write: 30, + }, + requester, + }); + } + + public setApiKey(key: {{classname}}ApiKeys, value: string) { + this.authentications[{{classname}}ApiKeys[key]].apiKey = value; + } + {{#hasAuthMethods}} + {{#authMethods}} + {{/authMethods}} + {{/hasAuthMethods}} + + private async sendRequest(request: Request, requestOptions: RequestOptions): Promise { + {{#authMethods}} + {{#isApiKey}} + if (this.authentications.{{name}}.apiKey) { + this.authentications.{{name}}.applyToRequest(requestOptions); } -{{/isBasicBearer}} -{{#isOAuth}} - - set accessToken(token: string) { - this.authentications.{{name}}.accessToken = token; + {{/isApiKey}} + {{/authMethods}} + return this.transporter.request(request, requestOptions); + } + + {{#operation}} + /** + * {{¬es}} + {{#summary}} + * @summary {{&summary}} + {{/summary}} + {{#allParams}} + * @param {{paramName}} {{description}} + {{/allParams}} + */ + public async {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}) : Promise<{{{returnType}}}> { + const path = '{{{path}}}'{{#pathParams}}.replace( + '{' + '{{baseName}}' + '}', + encodeURIComponent(String({{paramName}})) + ){{/pathParams}}; + let headers: Headers = { Accept: 'application/json' }; + let queryParameters: Record = {}; + + {{#allParams}} + {{#required}} + if ({{paramName}} === null || {{paramName}} === undefined) { + throw new Error('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); } -{{/isOAuth}} -{{/authMethods}} -{{/hasAuthMethods}} - public addInterceptor(interceptor: Interceptor) { - this.interceptors.push(interceptor); + {{/required}} + {{/allParams}} + {{#queryParams}} + if ({{paramName}} !== undefined) { + queryParameters['{{baseName}}'] = {{paramName}}; } -{{#operation}} - /** - * {{¬es}} - {{#summary}} - * @summary {{&summary}} - {{/summary}} - {{#allParams}} - * @param {{paramName}} {{description}} - {{/allParams}} - */ - public async {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{{{returnType}}}> { - const path = '{{{path}}}'{{#pathParams}} - .replace('{' + '{{baseName}}' + '}', encodeURIComponent(String({{paramName}}))){{/pathParams}}; - let headers: Headers = {}; - let queryParameters: Record = {}; -{{#hasProduces}} - const produces = [{{#produces}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/produces}}]; - // give precedence to 'application/json' - if (produces.indexOf('application/json') >= 0) { - headers.Accept = 'application/json'; - } else { - headers.Accept = produces.join(','); - } -{{/hasProduces}} - let formParams: Record = {}; - -{{#allParams}} -{{#required}} - // verify required parameter '{{paramName}}' is not null or undefined - if ({{paramName}} === null || {{paramName}} === undefined) { - throw new Error('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); - } - -{{/required}} -{{/allParams}} -{{#queryParams}} - if ({{paramName}} !== undefined) { - queryParameters['{{baseName}}'] = ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}"); - } - -{{/queryParams}} -{{#headerParams}} - headers['{{baseName}}'] = ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}"); -{{/headerParams}} - headers = {...headers, ...options.headers}; - - const request: Request = { - method: '{{httpMethod}}', - path, -{{#bodyParam}} - data: ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}") -{{/bodyParam}} - }; - - const requestOptions: RequestOptions = { - headers, - queryParameters - }; - - let authenticationPromise = Promise.resolve(); -{{#authMethods}} - {{#isApiKey}} - if (this.authentications.{{name}}.apiKey) { - authenticationPromise = authenticationPromise.then(() => this.authentications.{{name}}.applyToRequest(requestOptions)); - } - {{/isApiKey}} - {{#isBasicBasic}} - if (this.authentications.{{name}}.username && this.authentications.{{name}}.password) { - authenticationPromise = authenticationPromise.then(() => this.authentications.{{name}}.applyToRequest(requestOptions)); - } - {{/isBasicBasic}} - {{#isBasicBearer}} - if (this.authentications.{{name}}.accessToken) { - authenticationPromise = authenticationPromise.then(() => this.authentications.{{name}}.applyToRequest(requestOptions)); - } - {{/isBasicBearer}} - {{#isOAuth}} - if (this.authentications.{{name}}.accessToken) { - authenticationPromise = authenticationPromise.then(() => this.authentications.{{name}}.applyToRequest(requestOptions)); - } - {{/isOAuth}} -{{/authMethods}} - authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(requestOptions)); - - let interceptorPromise = authenticationPromise; - for (const interceptor of this.interceptors) { - interceptorPromise = interceptorPromise.then(() => interceptor(requestOptions)); - } - - await interceptorPromise; - - return this.transporter.request(request, requestOptions); - } -{{/operation}} + {{/queryParams}} + {{#headerParams}} + headers['{{baseName}}'] = {{paramName}}; + {{/headerParams}} + + const request: Request = { + method: '{{httpMethod}}', + path, + {{#bodyParam}} + data: {{paramName}}, + {{/bodyParam}} + }; + + const requestOptions: RequestOptions = { + headers, + queryParameters + }; + + return this.sendRequest(request, requestOptions); + } + {{/operation}} } {{/operations}} diff --git a/templates/javascript/model.mustache b/templates/javascript/model.mustache index bbb50e5cec9..9077f967167 100644 --- a/templates/javascript/model.mustache +++ b/templates/javascript/model.mustache @@ -11,10 +11,9 @@ import { {{classname}} } from '{{filename}}'; {{/description}} {{^isEnum}} {{#parent}} -{{! TODO: Add this line back when we understand where parent come from, but for now it's breaking the code}} -// export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}} +{{! TODO: Add back 'extends parent' when we understand where parent come from, but for now it's breaking the code}} {{/parent}} -export class {{classname}} { +export type {{classname}} = { {{#vars}} {{#description}} /** @@ -23,30 +22,6 @@ export class {{classname}} { {{/description}} '{{name}}'{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}; {{/vars}} - - {{#discriminator}} - static discriminator: string | undefined = "{{discriminatorName}}"; - {{/discriminator}} - {{^discriminator}} - static discriminator: string | undefined = undefined; - {{/discriminator}} - - {{^isArray}} - static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ - {{#vars}} - { - "name": "{{name}}", - "baseName": "{{baseName}}", - "type": "{{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}" - }{{^-last}}, - {{/-last}} - {{/vars}} - ]; - - static getAttributeTypeMap() { - return {{classname}}.attributeTypeMap; - } - {{/isArray}} } {{#hasEnums}} @@ -56,7 +31,7 @@ export namespace {{classname}} { export enum {{enumName}} { {{#allowableValues}} {{#enumVars}} - {{name}} = {{{value}}}{{^-last}},{{/-last}} + {{name}} = {{{value}}}{{^-last}},{{/-last}} {{/enumVars}} {{/allowableValues}} } @@ -69,7 +44,7 @@ export namespace {{classname}} { export enum {{classname}} { {{#allowableValues}} {{#enumVars}} - {{name}} = {{{value}}}{{^-last}},{{/-last}} + {{name}} = {{{value}}}{{^-last}},{{/-last}} {{/enumVars}} {{/allowableValues}} } diff --git a/templates/javascript/models.mustache b/templates/javascript/models.mustache index 90757fbd556..b6ccc5961db 100644 --- a/templates/javascript/models.mustache +++ b/templates/javascript/models.mustache @@ -11,161 +11,6 @@ export * from '{{{ classFilename }}}'; {{! Object serialization only relevant if generating APIs, too }} {{#generateApis}} -{{#models}} -{{#model}} -import { {{classname}} } from '{{{ classFilename }}}'; -{{/model}} -{{/models}} - -let primitives = [ - "string", - "boolean", - "double", - "integer", - "long", - "float", - "number", - "any" - ]; - -let enumsMap: {[index: string]: any} = { - {{#models}} - {{#model}} - {{#hasEnums}} - {{#vars}} - {{#isEnum}} - {{#isContainer}}"{{classname}}.{{enumName}}": {{classname}}.{{enumName}}{{/isContainer}}{{^isContainer}}"{{datatypeWithEnum}}": {{datatypeWithEnum}}{{/isContainer}}, - {{/isEnum}} - {{/vars}} - {{/hasEnums}} - {{#isEnum}} - "{{classname}}": {{classname}}, - {{/isEnum}} - {{/model}} - {{/models}} -} - -let typeMap: {[index: string]: any} = { - {{#models}} - {{#model}} - {{^isEnum}} - "{{classname}}": {{classname}}, - {{/isEnum}} - {{/model}} - {{/models}} -} - -export class ObjectSerializer { - public static findCorrectType(data: any, expectedType: string) { - if (data == undefined) { - return expectedType; - } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { - return expectedType; - } else if (expectedType === "Date") { - return expectedType; - } else { - if (enumsMap[expectedType]) { - return expectedType; - } - - if (!typeMap[expectedType]) { - return expectedType; // w/e we don't know the type - } - - // Check the discriminator - let discriminatorProperty = typeMap[expectedType].discriminator; - if (discriminatorProperty == null) { - return expectedType; // the type does not have a discriminator. use it. - } else { - if (data[discriminatorProperty]) { - var discriminatorType = data[discriminatorProperty]; - if(typeMap[discriminatorType]){ - return discriminatorType; // use the type given in the discriminator - } else { - return expectedType; // discriminator did not map to a type - } - } else { - return expectedType; // discriminator was not present (or an empty string) - } - } - } - } - - public static serialize(data: any, type: string) { - if (data == undefined) { - return data; - } else if (primitives.indexOf(type.toLowerCase()) !== -1) { - return data; - } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 - let subType: string = type.replace("Array<", ""); // Array => Type> - subType = subType.substring(0, subType.length - 1); // Type> => Type - let transformedData: any[] = []; - for (let index = 0; index < data.length; index++) { - let datum = data[index]; - transformedData.push(ObjectSerializer.serialize(datum, subType)); - } - return transformedData; - } else if (type === "Date") { - return data.toISOString(); - } else { - if (enumsMap[type]) { - return data; - } - if (!typeMap[type]) { // in case we dont know the type - return data; - } - - // Get the actual type of this object - type = this.findCorrectType(data, type); - - // get the map for the correct type. - let attributeTypes = typeMap[type].getAttributeTypeMap(); - let instance: {[index: string]: any} = {}; - for (let index = 0; index < attributeTypes.length; index++) { - let attributeType = attributeTypes[index]; - instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); - } - return instance; - } - } - - public static deserialize(data: any, type: string) { - // polymorphism may change the actual type. - type = ObjectSerializer.findCorrectType(data, type); - if (data == undefined) { - return data; - } else if (primitives.indexOf(type.toLowerCase()) !== -1) { - return data; - } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 - let subType: string = type.replace("Array<", ""); // Array => Type> - subType = subType.substring(0, subType.length - 1); // Type> => Type - let transformedData: any[] = []; - for (let index = 0; index < data.length; index++) { - let datum = data[index]; - transformedData.push(ObjectSerializer.deserialize(datum, subType)); - } - return transformedData; - } else if (type === "Date") { - return new Date(data); - } else { - if (enumsMap[type]) {// is Enum - return data; - } - - if (!typeMap[type]) { // dont know the type - return data; - } - let instance = new typeMap[type](); - let attributeTypes = typeMap[type].getAttributeTypeMap(); - for (let index = 0; index < attributeTypes.length; index++) { - let attributeType = attributeTypes[index]; - instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); - } - return instance; - } - } -} - export interface Authentication { /** * Apply authentication settings to header and query params. @@ -173,19 +18,6 @@ export interface Authentication { applyToRequest(requestOptions: RequestOptions): Promise | void; } -export class HttpBearerAuth implements Authentication { - public accessToken: string | (() => string) = ''; - - applyToRequest(requestOptions: RequestOptions): void { - if (requestOptions && requestOptions.headers) { - const accessToken = typeof this.accessToken === 'function' - ? this.accessToken() - : this.accessToken; - requestOptions.headers["Authorization"] = "Bearer " + accessToken; - } - } -} - export class ApiKeyAuth implements Authentication { public apiKey: string = ''; @@ -207,25 +39,4 @@ export class ApiKeyAuth implements Authentication { } } } - -export class OAuth implements Authentication { - public accessToken: string = ''; - - applyToRequest(requestOptions: RequestOptions): void { - if (requestOptions && requestOptions.headers) { - requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; - } - } -} - -export class VoidAuth implements Authentication { - public username: string = ''; - public password: string = ''; - - applyToRequest(_: RequestOptions): void { - // Do nothing - } -} - -export type Interceptor = (requestOptions: RequestOptions) => (Promise | void); {{/generateApis}}