Skip to content

Commit 4315823

Browse files
committed
refactor: update type definitions and improve JSDoc annotations in common module
1 parent 34aeb08 commit 4315823

File tree

3 files changed

+155
-54
lines changed

3 files changed

+155
-54
lines changed

api/utils/common.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66
* @typedef {import('../../types/requestProcessor').Params} Params
77
* @typedef {import('../../types/common').TimeObject} TimeObject
88
* @typedef {import('mongodb').ObjectId} ObjectId
9-
* typedef {import('moment-timezone').Moment} MomentTimezone
9+
* @typedef {import('moment-timezone').Moment} MomentTimezone
1010
*/
1111

1212
/** @lends module:api/utils/common **/
13-
/** @type(import('../../types/common').Common) */
13+
/** @type {import('../../types/common').Common} */
1414
const common = {};
1515

16-
/** @type(import('moment-timezone')) */
16+
/** @type {import('moment-timezone')} */
1717
const moment = require('moment-timezone');
1818
const crypto = require('crypto');
1919
const logger = require('./log.js');
@@ -3465,5 +3465,5 @@ common.trimWhitespaceStartEnd = function(value) {
34653465
return value;
34663466
};
34673467

3468-
/** @type(import('../../types/common').Common) */
3468+
/** @type {import('../../types/common').Common} */
34693469
module.exports = common;

tsconfig.json

Lines changed: 37 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,45 @@
22
// npm i typescript --save-dev
33
//
44
// to run the summary check, call:
5-
// npx tsc
5+
// npx tsc --checkJs --noEmit
66
{
7-
"include": [
8-
//"plugins/push/**/*.ts",
9-
//"plugins/push/**/*.js"
10-
"api/utils/common.js",
11-
"api/utils/localization.js",
12-
"api/lib/countly.common.js",
13-
"api/utils/requestProcessor.js"
14-
],
15-
"exclude": [
16-
"node_modules"
7+
// Explicitly specify which files to include in compilation
8+
"files": [
9+
"types/global.d.ts", // Global type declarations for legacy compatibility
10+
"types/common.d.ts", // Common utility functions type definitions
11+
"types/requestProcessor.d.ts", // Request processor type definitions
12+
"types/localization.d.ts", // Localization module type definitions
13+
"types/log.d.ts", // Logging module type definitions
14+
"types/config.d.ts", // Configuration type definitions
15+
"types/pluginManager.d.ts", // Plugin manager type definitions
16+
"types/utils.d.ts", // Utility functions type definitions
17+
"types/batcher.d.ts", // Database batcher type definitions
18+
"api/utils/localization.js" // Include JS file for type checking
1719
],
1820
"compilerOptions": {
19-
"outDir": "dist", // we're not building the app. but still necessary for, reasons...
20-
"allowJs": true,
21-
"checkJs": true,
22-
"resolveJsonModule": true,
23-
"strict": true
21+
// Language and Environment
22+
"target": "ES2022", // Set the JavaScript language version for emitted JavaScript
23+
"lib": ["ES2022", "DOM"], // Specify a set of bundled library declaration files
24+
25+
// Modules
26+
"moduleResolution": "Node", // Specify how TypeScript looks up a file from a given module specifier
27+
"baseUrl": ".", // Specify the base directory to resolve non-relative module names
28+
"paths": { // Specify a set of entries that re-map imports to additional lookup locations
29+
"@countly/*": ["./api/*"], // Map @countly imports to api directory
30+
"@plugins/*": ["./plugins/*"], // Map @plugins imports to plugins directory
31+
"@frontend/*": ["./frontend/*"] // Map @frontend imports to frontend directory
32+
},
33+
"resolveJsonModule": true, // Enable importing .json files
34+
35+
// JavaScript Support
36+
"allowJs": true, // Allow JavaScript files to be a part of your program
37+
38+
// Interop Constraints
39+
"esModuleInterop": true, // Emit additional JavaScript to ease support for importing CommonJS modules
40+
"forceConsistentCasingInFileNames": true, // Ensure that casing is correct in imports
41+
42+
// Completeness
43+
"skipLibCheck": true, // Skip type checking all .d.ts files
44+
"typeRoots": ["./types", "./node_modules/@types"] // Specify multiple folders that act like './node_modules/@types'
2445
}
2546
}

types/common.d.ts

Lines changed: 114 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,27 @@
11
import { Moment } from "moment-timezone";
22
import { Collection, Db, ObjectId } from "mongodb";
33
import { Params } from "./requestProcessor";
4+
import { PluginManager, Database } from "./pluginManager";
5+
import { Logger } from "./log";
6+
import { CountlyAPIConfig } from "./config";
7+
8+
/** Node.js Request object */
9+
export interface req {
10+
headers: { [key: string]: string | string[] };
11+
connection: {
12+
remoteAddress?: string;
13+
};
14+
socket?: {
15+
remoteAddress?: string;
16+
};
17+
ip?: string;
18+
ips?: string[];
19+
}
20+
21+
/** Generic output object for responses */
22+
export interface output {
23+
[key: string]: any;
24+
}
425

526
export interface TimeObject {
627
/** Momentjs instance for request's time in app's timezone */
@@ -68,6 +89,9 @@ export interface DbUserMap {
6889
platform: string;
6990
platform_version: string;
7091
app_version: string;
92+
app_version_major: string;
93+
app_version_minor: string;
94+
app_version_patch: string;
7195
last_begin_session_timestamp: string;
7296
last_end_session_timestamp: string;
7397
has_ongoing_session: string;
@@ -101,48 +125,54 @@ export interface OsMapping {
101125
export interface ValidationArgProperties {
102126
[key: string]: {
103127
/** should property be present in args */
104-
required: boolean;
128+
required?: boolean;
105129
/** what type should property be, possible values: String, Array, Number, URL, Boolean, Object, Email */
106-
type: string;// | string[] | object;
107-
//array: boolean;
108-
//discriminator: (value: any) => any;
130+
type?: 'String' | 'Array' | 'Number' | 'URL' | 'Boolean' | 'Object' | 'Email' | string;
109131
/** property should not be longer than provided value */
110-
'max-length': string;//number;
132+
'max-length'?: number;
111133
/** property should not be shorter than provided value */
112-
'min-length': string;//number;
113-
max: string;// number;
114-
min: string;// number;
134+
'min-length'?: number;
135+
max?: number;
136+
min?: number;
115137
/** should string property has any number in it */
116-
'has-number': string;//boolean;
138+
'has-number'?: boolean;
117139
/** should string property has any latin character in it */
118-
'has-char': string;//boolean;
140+
'has-char'?: boolean;
119141
/** should string property has any upper cased latin character in it */
120-
'has-upchar': string;//boolean;
142+
'has-upchar'?: boolean;
121143
/** should string property has any none latin character in it */
122-
'has-special': string;//boolean;
123-
//in?: string[] | (() => string[]);
124-
//nonempty: boolean;
125-
//custom: (value: any) => string | undefined;
126-
//regex: string;
144+
'has-special'?: boolean;
145+
/** allowed values for validation */
146+
in?: string[] | (() => string[]);
127147
/** should property be present in returned validated args object */
128-
'exclude-from-ret-obj': string;//boolean;
129-
//trim: boolean;
130-
//mods: string;
131-
//multiple: boolean;
148+
'exclude-from-ret-obj'?: boolean;
149+
/** custom validation function */
150+
custom?: (value: any) => string | undefined;
151+
/** regex pattern for validation */
152+
regex?: string;
153+
/** should value be non-empty */
154+
nonempty?: boolean;
155+
/** should trim whitespace */
156+
trim?: boolean;
157+
/** additional modifiers */
158+
mods?: string;
159+
/** allow multiple values */
160+
multiple?: boolean;
132161
};
133162
}
134163

135164
/** Validation result */
136165
export interface ValidationResult {
137166
result: boolean;
138167
errors?: string[];
139-
obj?: any;
168+
obj?: Record<string, any>;
140169
}
141170

142171
/** Date IDs */
143172
export interface DateIds {
144173
zero: string;
145174
month: string;
175+
[key: string]: string;
146176
}
147177

148178
/** Custom metric properties */
@@ -157,9 +187,7 @@ export interface CustomMetricProps {
157187
/** value to increment current metric for, default 1 */
158188
value?: number;
159189
/** object with segments to record data, key segment name and value segment value or array of segment values */
160-
segments?: {
161-
[key: string]: string | string[];
162-
};
190+
segments?: Record<string, string | string[] | number | boolean>;
163191
/** if metric should be treated as unique, and stored in 0 docs and be estimated on output */
164192
unique?: boolean;
165193
/** timestamp in seconds to be used to determine if unique metrics it unique for specific period */
@@ -205,15 +233,15 @@ export interface HTMLWhitelist {
205233
*/
206234
export interface Common {
207235
/** Reference to plugins */
208-
plugins: any;
236+
plugins: PluginManager;
209237

210238
/**
211239
* Escape special characters in the given string of html.
212240
* @param {string} string - The string to escape for inserting into HTML
213241
* @param {boolean} more - if false, escapes only tags, if true escapes also quotes and ampersands
214242
* @returns {string} escaped string
215243
**/
216-
escape_html: (string: string, more: boolean) => string;
244+
escape_html: (string: string, more?: boolean) => string;
217245

218246
/**
219247
* Function to escape unicode characters
@@ -234,7 +262,7 @@ export interface Common {
234262
* @param {string} val - string that might be json encoded
235263
* @returns {object} with property data for parsed data and property valid to check if it was valid json encoded string or not
236264
**/
237-
getJSON: (val: string) => object;
265+
getJSON: (val: string) => { valid: boolean; data?: any };
238266

239267
/**
240268
* Logger object for creating module-specific logging
@@ -243,7 +271,7 @@ export interface Common {
243271
* const log = common.log('myplugin:api');
244272
* log.i('myPlugin got a request: %j', params.qstring);
245273
*/
246-
log: (module: string) => any;
274+
log: (module: string) => Logger;
247275

248276
/**
249277
* Mapping some common property names from longer understandable to shorter representation stored in database
@@ -266,15 +294,15 @@ export interface Common {
266294
/**
267295
* Default {@link countlyConfig} object for API server
268296
*/
269-
config: object;
297+
config: CountlyAPIConfig;
270298

271299
/** Reference to moment-timezone which combines moment.js with timezone support */
272-
moment: Moment;
300+
moment: typeof import('moment-timezone');
273301

274302
/**
275303
* Reference to crypto module
276304
*/
277-
crypto: object;
305+
crypto: typeof import('crypto');
278306

279307
/**
280308
* Operating syste/platform mappings from what can be passed in metrics to shorter representations
@@ -292,7 +320,7 @@ export interface Common {
292320
dbPromise: (collection: string, method: string, ...args: any[]) => Promise<any>;
293321

294322
/** Database reference */
295-
db: Db;
323+
db: Database;
296324

297325
/**
298326
* Fetches nested property values from an obj.
@@ -329,7 +357,7 @@ export interface Common {
329357
* common.convertToType("test") //outputs "test"
330358
* common.convertToType("12345678901234567890") //outputs "12345678901234567890"
331359
*/
332-
convertToType: (value: any, preventParsingToNumber: boolean) => any;
360+
convertToType: (value: any, preventParsingToNumber?: boolean) => any;
333361

334362
/**
335363
* Safe division between numbers providing 0 as result in cases when dividing by 0
@@ -417,7 +445,7 @@ export interface Common {
417445
* @param {string} reqTimestamp - timestamp in the request
418446
* @returns {TimeObject} Time object for current request
419447
*/
420-
initTimeObj: (appTimezone: string, reqTimestamp: string) => TimeObject;
448+
initTimeObj: (appTimezone: string, reqTimestamp: string | number) => TimeObject;
421449

422450
/**
423451
* Creates a Date object from provided seconds timestamp in provided timezone
@@ -939,8 +967,60 @@ export interface Common {
939967
*/
940968
trimWhitespaceStartEnd: (value: any) => any;
941969

970+
971+
972+
/** DataTable class for server-side processing */
973+
DataTable: any;
974+
942975
/** Write batcher */
943976
writeBatcher: {
944977
add: (collection: string, id: string, update: any) => void;
945978
};
979+
980+
/** Database connection for output */
981+
outDb?: Database;
982+
983+
/** Database connection for drill queries */
984+
drillDb?: Database;
985+
986+
/** Request processor function */
987+
processRequest?: any;
988+
989+
/** Read batcher */
990+
readBatcher?: import('./batcher').ReadBatcher;
991+
992+
/** Insert batcher */
993+
insertBatcher?: any;
994+
995+
/** Drill read batcher */
996+
drillReadBatcher?: any;
997+
998+
/** Job runners */
999+
runners?: any;
1000+
1001+
/** Cache instance */
1002+
cache?: any;
1003+
1004+
/** Cached schema */
1005+
cachedSchema?: {
1006+
[appId: string]: {
1007+
loading: boolean;
1008+
ts: number;
1009+
};
1010+
};
1011+
1012+
/** Collection mapping */
1013+
collectionMap?: {
1014+
[hash: string]: {
1015+
a: string; // app id
1016+
e?: string; // event name (for events)
1017+
vs?: string; // view segment (for views)
1018+
name: string; // display name
1019+
};
1020+
};
1021+
9461022
}
1023+
1024+
/** Default export of common module */
1025+
declare const common: Common;
1026+
export default common;

0 commit comments

Comments
 (0)