Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve typing as required by tsc 5.3 or higher #186

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Typesense/Aliases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default class Aliases {
return this.apiCall.get<CollectionAliasesResponseSchema>(RESOURCEPATH);
}

private endpointPath(aliasName): string {
private endpointPath(aliasName: string): string {
return `${Aliases.RESOURCEPATH}/${aliasName}`;
}

Expand Down
11 changes: 6 additions & 5 deletions src/Typesense/ApiCall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const UNHEALTHY = false;
interface Node extends NodeConfiguration {
isHealthy: boolean;
index: string | number;
lastAccessTimestamp: number;
}

export default class ApiCall {
Expand Down Expand Up @@ -340,7 +341,7 @@ export default class ApiCall {
return candidateNode;
}

nodeDueForHealthcheck(node, requestNumber = 0): boolean {
nodeDueForHealthcheck(node: Node, requestNumber = 0): boolean {
const isDueForHealthcheck =
Date.now() - node.lastAccessTimestamp >
this.healthcheckIntervalSeconds * 1000;
Expand All @@ -364,28 +365,28 @@ export default class ApiCall {
});
}

setNodeHealthcheck(node, isHealthy): void {
setNodeHealthcheck(node: Node, isHealthy: boolean): void {
node.isHealthy = isHealthy;
node.lastAccessTimestamp = Date.now();
}

uriFor(endpoint: string, node): string {
uriFor(endpoint: string, node: NodeConfiguration): string {
if (node.url != null) {
return `${node.url}${endpoint}`;
}
return `${node.protocol}://${node.host}:${node.port}${node.path}${endpoint}`;
}

defaultHeaders(): any {
const defaultHeaders = {};
const defaultHeaders: Record<string, string> = {};
if (!this.sendApiKeyAsQueryParam) {
defaultHeaders[APIKEYHEADERNAME] = this.apiKey;
}
defaultHeaders["Content-Type"] = "application/json";
return defaultHeaders;
}

async timer(seconds): Promise<void> {
async timer(seconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}

Expand Down
63 changes: 23 additions & 40 deletions src/Typesense/Configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,28 @@ import * as logger from "loglevel";
import { Logger, LogLevelDesc } from "loglevel";
import { MissingConfigurationError } from "./Errors";

export interface NodeConfiguration {
export interface NodeConfigurationWithHostname {
host: string;
port: number;
protocol: string;
path?: string;
url?: string;
}

export interface NodeConfigurationWithHostname {
host: string;
port: number;
protocol: string;
path?: string;
export interface NodeConfiguration extends NodeConfigurationWithHostname {
url?: string;
}

export interface NodeConfigurationWithUrl {
url: string;
}

type NodeType = NodeConfiguration | NodeConfigurationWithHostname | NodeConfigurationWithUrl | undefined;


function isNodeConfigurationWithHostname(node: NodeType): node is NodeConfigurationWithHostname {
return node !== undefined && (node as NodeConfigurationWithHostname).protocol !== undefined;
}

export interface ConfigurationOptions {
apiKey: string;
nodes:
Expand Down Expand Up @@ -166,49 +169,29 @@ export default class Configuration {
return (
!["protocol", "host", "port", "path"].every((key) => {
return node.hasOwnProperty(key);
}) && node["url"] == null
}) && node.hasOwnProperty("url") == null
);
}

private setDefaultPathInNode(
node:
| NodeConfiguration
| NodeConfigurationWithHostname
| NodeConfigurationWithUrl
| undefined
):
| NodeConfiguration
| NodeConfigurationWithHostname
| NodeConfigurationWithUrl
| undefined {
if (node != null && !node.hasOwnProperty("path")) {
node["path"] = "";
}
node: NodeType
): NodeType {
if (isNodeConfigurationWithHostname(node)) {
node.path = "";
}
return node;
}

private setDefaultPortInNode(
node:
| NodeConfiguration
| NodeConfigurationWithHostname
| NodeConfigurationWithUrl
| undefined
):
| NodeConfiguration
| NodeConfigurationWithHostname
| NodeConfigurationWithUrl
| undefined {
if (
node != null &&
!node.hasOwnProperty("port") &&
node.hasOwnProperty("protocol")
) {
switch (node["protocol"]) {
node: NodeType
): NodeType {
if (isNodeConfigurationWithHostname(node)) {
switch (node.protocol) {
case "https":
node["port"] = 443;
node.port = 443;
break;
case "http":
node["port"] = 80;
node.port = 80;
break;
}
}
Expand All @@ -233,7 +216,7 @@ export default class Configuration {
}
}

private shuffleArray(array) {
private shuffleArray(array: object[]) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
Expand Down
3 changes: 2 additions & 1 deletion src/Typesense/Documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,8 @@ export default class Documents<T extends DocumentSchema = object>
): Promise<UpdateByFilterResponse | T> {
if (!document) throw new Error("No document provided");

if (options["filter_by"] != null) {
// @ts-expect-error filter_by does not exist in options
if (options ["filter_by"] != null) {
return this.apiCall.patch<T>(
this.endpointPath(),
document,
Expand Down
6 changes: 3 additions & 3 deletions src/Typesense/Errors/ImportError.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import TypesenseError from "./TypesenseError";
import { ImportResponseFail } from "../Documents";
import { ImportResponseFail, ImportResponse } from "../Documents";

export default class ImportError extends TypesenseError {
importResults: ImportResponseFail;
constructor(message, importResults) {
importResults: ImportResponseFail | ImportResponse[];
constructor(message: string, importResults: ImportResponseFail | ImportResponse[]) {
super(message);
this.importResults = importResults;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Typesense/MultiSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ export default class MultiSearch {
.cacheSearchResultsForSeconds,
}: { cacheSearchResultsForSeconds?: number } = {}
): Promise<MultiSearchResponse<T>> {
const additionalHeaders = {};
const additionalHeaders: Record<string, string> = {};
if (this.useTextContentType) {
additionalHeaders["content-type"] = "text/plain";
}

const additionalQueryParams = {};
const additionalQueryParams: Record<string, boolean> = {};
if (this.configuration.useServerSideSearchCache === true) {
additionalQueryParams["use_cache"] = true;
}
Expand Down
4 changes: 3 additions & 1 deletion src/Typesense/SearchOnlyDocuments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,14 @@ export class SearchOnlyDocuments<T extends DocumentSchema>
abortSignal = null,
}: SearchOptions = {}
): Promise<SearchResponse<T>> {
const additionalQueryParams = {};
const additionalQueryParams: Record<string, boolean> = {};
if (this.configuration.useServerSideSearchCache === true) {
additionalQueryParams["use_cache"] = true;
}
for (const key in searchParameters) {
// @ts-expect-error allow random lookup
if (Array.isArray(searchParameters[key])) {
// @ts-expect-error allow random lookup
additionalQueryParams[key] = searchParameters[key].join(",");
}
}
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */,
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
Expand Down