@wikicasa-dev/node-common 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ export * from "./src/Cache";
2
+ export { CacheES } from "./src/CacheES";
3
+ export * from "./src/CallPool";
4
+ export * from "./src/common";
5
+ export * from "./src/Console";
6
+ export * from "./src/Crawler";
7
+ export * from "./src/Pool";
8
+ export * from "./src/utils";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ // src/index.ts
2
+ export * from "./src/Cache";
3
+ export { CacheES } from "./src/CacheES";
4
+ export * from "./src/CallPool";
5
+ export * from "./src/common";
6
+ export * from "./src/Console";
7
+ export * from "./src/Crawler";
8
+ export * from "./src/Pool";
9
+ export * from "./src/utils";
package/dist/src/Cache.js CHANGED
@@ -31,8 +31,13 @@ export class Cache {
31
31
  case MODE.STRING_BROTLI:
32
32
  default: {
33
33
  const value = await this.client.get(key);
34
- const dataRaw = brotliDecompressSync(Buffer.from(value, "binary")).toString();
35
- data = JSON.parse(dataRaw);
34
+ if (value !== null) {
35
+ const dataRaw = brotliDecompressSync(Buffer.from(value, "binary")).toString();
36
+ data = JSON.parse(dataRaw);
37
+ }
38
+ else {
39
+ data = null;
40
+ }
36
41
  break;
37
42
  }
38
43
  }
@@ -86,6 +91,7 @@ export class Cache {
86
91
  catch (e) {
87
92
  console.error("Can't check data exists");
88
93
  }
94
+ return;
89
95
  }
90
96
  async select(db) {
91
97
  if (!this.init)
@@ -106,4 +112,3 @@ export class Cache {
106
112
  }
107
113
  }
108
114
  }
109
- //# sourceMappingURL=Cache.js.map
@@ -99,13 +99,14 @@ export class CacheES {
99
99
  async exists(id) {
100
100
  try {
101
101
  return !!(await this.client.exists({
102
- index,
102
+ index: "redis_data",
103
103
  id
104
104
  }));
105
105
  }
106
106
  catch (e) {
107
107
  console.error(`Can't check data exists: ${e}`);
108
108
  }
109
+ return;
109
110
  }
110
111
  async quit() {
111
112
  try {
@@ -116,4 +117,3 @@ export class CacheES {
116
117
  }
117
118
  }
118
119
  }
119
- //# sourceMappingURL=CacheES.js.map
@@ -31,7 +31,7 @@ export class CallPool {
31
31
  concurrency;
32
32
  minConcurrency = 1;
33
33
  maxConcurrency;
34
- _print;
34
+ _print = "";
35
35
  limiter;
36
36
  proxy;
37
37
  CLOCK_NUMBER = 1;
@@ -41,6 +41,7 @@ export class CallPool {
41
41
  clock = this.CLOCK_NUMBER;
42
42
  queue = [];
43
43
  activeCount;
44
+ // @ts-ignore
44
45
  agent;
45
46
  constructor(name = "default", proxy = PROXY.STATIC, minConcurrency = 1, maxConcurrency, limitCall = 1000, limitInterval = 1000) {
46
47
  this.name = name;
@@ -136,7 +137,7 @@ export class CallPool {
136
137
  { name: "Edge", version: 116 }
137
138
  ];
138
139
  return RandomUserAgent.getRandom(function (ua) {
139
- return browsers.some(b => b.name === ua.browserName && b.version <= ua.browserVersion);
140
+ return browsers.some(b => b.name === ua.browserName && b.version <= parseInt(ua.browserVersion));
140
141
  });
141
142
  }
142
143
  enqueue(call) {
@@ -151,34 +152,37 @@ export class CallPool {
151
152
  }
152
153
  schedule() {
153
154
  while (this.activeCount < this.concurrency && this.queue.length > 0) {
154
- const { call, resolve, reject } = this.queue.shift();
155
+ const item = this.queue.shift();
156
+ if (!item)
157
+ return;
158
+ const { call, resolve, reject } = item;
155
159
  this.activeCount++;
156
160
  const time = performance.now();
157
161
  this.limiter(() => {
158
162
  call()
159
163
  .then((result) => {
160
- resolve(result);
161
- })
164
+ resolve(result);
165
+ })
162
166
  .catch((error) => {
163
- reject(error);
164
- })
167
+ reject(error);
168
+ })
165
169
  .finally(() => {
166
- this.activeCount--;
167
- this.clock--;
168
- if (this.clock < 0) {
169
- this.clock = this.CLOCK_NUMBER;
170
- if (this.mean > this.targetMean && this.mean > 10)
171
- this.concurrency = Math.max(this.concurrency - Math.floor(this.concurrency / 10), this.minConcurrency);
172
- if (this.mean < this.targetMean || this.mean < 2)
173
- this.concurrency = Math.min(this.concurrency + Math.ceil(this.concurrency / 20), this.maxConcurrency);
174
- this.targetMean = this.mean;
175
- }
176
- const t = (performance.now() - time) / 1000;
177
- this.mean = this.mean > 0 ? this.mean + (t - this.mean) / this.WEIGHT : t;
178
- this.updatePrint();
179
- //console.debug(this.name, t, this.mean, this.targetMean, `${this.activeCount}/${this.queue.length}`, this.concurrency, `${(60 / this.mean) * this.concurrency} avg/m`);
180
- this.schedule();
181
- });
170
+ this.activeCount--;
171
+ this.clock--;
172
+ if (this.clock < 0) {
173
+ this.clock = this.CLOCK_NUMBER;
174
+ if (this.mean > this.targetMean && this.mean > 10)
175
+ this.concurrency = Math.max(this.concurrency - Math.floor(this.concurrency / 10), this.minConcurrency);
176
+ if (this.mean < this.targetMean || this.mean < 2)
177
+ this.concurrency = Math.min(this.concurrency + Math.ceil(this.concurrency / 20), this.maxConcurrency);
178
+ this.targetMean = this.mean;
179
+ }
180
+ const t = (performance.now() - time) / 1000;
181
+ this.mean = this.mean > 0 ? this.mean + (t - this.mean) / this.WEIGHT : t;
182
+ this.updatePrint();
183
+ //console.debug(this.name, t, this.mean, this.targetMean, `${this.activeCount}/${this.queue.length}`, this.concurrency, `${(60 / this.mean) * this.concurrency} avg/m`);
184
+ this.schedule();
185
+ });
182
186
  });
183
187
  }
184
188
  }
@@ -220,4 +224,3 @@ export class CallPool {
220
224
  }
221
225
  }
222
226
  }
223
- //# sourceMappingURL=CallPool.js.map
@@ -111,4 +111,3 @@ export default class Console {
111
111
  this.first = false;
112
112
  }
113
113
  }
114
- //# sourceMappingURL=Console.js.map
@@ -27,9 +27,9 @@ export default class Crawler {
27
27
  return this.crawlFn(driver, url)
28
28
  .then(results => this.options.callback?.call(null, results, index, this.first))
29
29
  .finally(() => {
30
- this.first = false;
31
- this.drivers.push(driver);
32
- });
30
+ this.first = false;
31
+ this.drivers.push(driver);
32
+ });
33
33
  });
34
34
  pool(tasks, this.options.concurrent).then(results => {
35
35
  this.destroyDrivers();
@@ -66,11 +66,11 @@ export default class Crawler {
66
66
  driver.get(listing.url).then(() => _self.options.crawlDetail(driver).then(detail => resolve1({ ...listing, ...detail })));
67
67
  })), 1)
68
68
  .then(details => {
69
- _self.options.pageCallback?.call(null, details);
70
- driver.get(url).then(() => _self.options.nextPage(driver)
71
- .then(url => _self.crawlFn(driver, url).then(acc => resolve([...details, ...acc])))
72
- .catch(() => resolve(details)));
73
- });
69
+ _self.options.pageCallback?.call(null, details);
70
+ driver.get(url).then(() => _self.options.nextPage(driver)
71
+ .then(url => _self.crawlFn(driver, url).then(acc => resolve([...details, ...acc])))
72
+ .catch(() => resolve(details)));
73
+ });
74
74
  }
75
75
  else {
76
76
  _self.options.pageCallback?.call(null, listings);
@@ -83,4 +83,3 @@ export default class Crawler {
83
83
  });
84
84
  }
85
85
  }
86
- //# sourceMappingURL=Crawler.js.map
package/dist/src/Pool.js CHANGED
@@ -39,16 +39,16 @@ export class Pool {
39
39
  this.activeCount++;
40
40
  call()
41
41
  .then((result) => {
42
- resolve(result);
43
- })
42
+ resolve(result);
43
+ })
44
44
  .catch((error) => {
45
- reject(error);
46
- })
45
+ reject(error);
46
+ })
47
47
  .finally(() => {
48
- this.activeCount--;
49
- this.updatePrint();
50
- this.schedule();
51
- });
48
+ this.activeCount--;
49
+ this.updatePrint();
50
+ this.schedule();
51
+ });
52
52
  }
53
53
  }
54
54
  print() {
@@ -68,4 +68,3 @@ export class Pool {
68
68
  }
69
69
  _print;
70
70
  }
71
- //# sourceMappingURL=Pool.js.map
@@ -38,11 +38,11 @@ export function pool(promises, concurrent, stopIfError = true) {
38
38
  .for(promises)
39
39
  .withConcurrency(concurrent)
40
40
  .handleError(async (error, user, pool) => {
41
- if (stopIfError || (error instanceof CustomError && error.critical)) {
42
- reject(error);
43
- pool.stop();
44
- }
45
- })
41
+ if (stopIfError || (error instanceof CustomError && error.critical)) {
42
+ reject(error);
43
+ pool.stop();
44
+ }
45
+ })
46
46
  .useCorrespondingResults()
47
47
  .process((fn) => fn())
48
48
  .then((poolResult) => resolve(poolResult.results))
@@ -148,4 +148,3 @@ export function unique(array) {
148
148
  return;
149
149
  return Array.from(new Set(array));
150
150
  }
151
- //# sourceMappingURL=common.js.map
@@ -7,7 +7,6 @@ export declare function trimAll(str: string): string;
7
7
  export declare function cleanUpSpecialChars2(str: string): string;
8
8
  export declare function capitalizeWords(str: string): string;
9
9
  export declare function capitalizeFirstLetter(str: string): string | undefined;
10
- export declare function readJson(path: string): any;
11
10
  export declare function orderBy<T extends object>(arr: Array<T>, prop: any): Array<T>;
12
11
  export declare function pan(number: number, digits: number): string;
13
12
  export declare function uniqWith<T>(array: Array<T>, compareFn: any): Array<T>;
package/dist/src/utils.js CHANGED
@@ -1,4 +1,3 @@
1
- import fs from "fs";
2
1
  import hash from "object-hash";
3
2
  export function arrayRotate(arr, n) {
4
3
  Array.from(Array(n)).forEach((x, i) => {
@@ -40,18 +39,6 @@ export function capitalizeFirstLetter(str) {
40
39
  return;
41
40
  return str?.charAt(0).toUpperCase() + str?.slice(1);
42
41
  }
43
- export function readJson(path) {
44
- if (!fs.existsSync(path))
45
- return null;
46
- let json;
47
- try {
48
- json = JSON.parse(fs.readFileSync(path, "utf8"));
49
- }
50
- catch (e) {
51
- json = null;
52
- }
53
- return json;
54
- }
55
42
  export function orderBy(arr, prop) {
56
43
  arr.sort((a, b) => {
57
44
  if (a[prop] > b[prop]) {
@@ -207,4 +194,3 @@ export function convertPolygonStringToArray(polygonString) {
207
194
  return [lon, lat]; // Return [longitude, latitude]
208
195
  });
209
196
  }
210
- //# sourceMappingURL=utils.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wikicasa-dev/node-common",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "Wikicasa node common",
5
5
  "type": "module",
6
6
  "files": [
package/dist/Cache.js DELETED
@@ -1,114 +0,0 @@
1
- import redis from "redis";
2
- import { brotliCompressSync, brotliDecompressSync } from "zlib";
3
- import { Buffer } from "node:buffer";
4
- export var MODE;
5
- (function (MODE) {
6
- MODE[MODE["STRING"] = 0] = "STRING";
7
- MODE[MODE["JSON"] = 1] = "JSON";
8
- MODE[MODE["HASH"] = 2] = "HASH";
9
- MODE[MODE["STRING_BROTLI"] = 3] = "STRING_BROTLI";
10
- })(MODE || (MODE = {}));
11
- export class Cache {
12
- init;
13
- client;
14
- constructor(options) {
15
- this.client = redis.createClient(options);
16
- }
17
- async start() {
18
- this.init = this.client.connect();
19
- }
20
- async get(key, mode = MODE.STRING_BROTLI) {
21
- if (!this.init)
22
- await this.start();
23
- //if (!await this.client.exists(key))
24
- // return null;
25
- let data;
26
- try {
27
- switch (mode) {
28
- case MODE.STRING:
29
- data = await this.client.get(key);
30
- break;
31
- case MODE.STRING_BROTLI:
32
- default: {
33
- const value = await this.client.get(key);
34
- if (value !== null) {
35
- const dataRaw = brotliDecompressSync(Buffer.from(value, "binary")).toString();
36
- data = JSON.parse(dataRaw);
37
- }
38
- else {
39
- data = null;
40
- }
41
- break;
42
- }
43
- }
44
- }
45
- catch (e) {
46
- data = null;
47
- }
48
- return data;
49
- }
50
- async set(key, value, mode = MODE.STRING_BROTLI) {
51
- if (!this.init)
52
- await this.start();
53
- try {
54
- switch (mode) {
55
- case MODE.STRING: {
56
- await this.client.set(key, value.toString("binary"));
57
- break;
58
- }
59
- case MODE.JSON:
60
- // @ts-ignore
61
- await this.client.jSet(key, ".", value);
62
- break;
63
- case MODE.STRING_BROTLI:
64
- default: {
65
- const data = brotliCompressSync(JSON.stringify(value));
66
- await this.client.set(key, data.toString("binary"));
67
- break;
68
- }
69
- }
70
- }
71
- catch (e) {
72
- console.error("Can't cache data");
73
- }
74
- }
75
- async delete(key) {
76
- if (!this.init)
77
- await this.start();
78
- try {
79
- await this.client.del(key);
80
- }
81
- catch (e) {
82
- console.error("Can't delete data");
83
- }
84
- }
85
- async exists(key) {
86
- if (!this.init)
87
- await this.start();
88
- try {
89
- return !!(await this.client.exists(key));
90
- }
91
- catch (e) {
92
- console.error("Can't check data exists");
93
- }
94
- return;
95
- }
96
- async select(db) {
97
- if (!this.init)
98
- await this.start();
99
- try {
100
- await this.client.select(db);
101
- }
102
- catch (e) {
103
- console.error("Can't select db");
104
- }
105
- }
106
- async quit() {
107
- try {
108
- await this.client.quit();
109
- }
110
- catch (e) {
111
- console.error("Can't quit");
112
- }
113
- }
114
- }
package/dist/CacheES.js DELETED
@@ -1,119 +0,0 @@
1
- import { Client } from "@elastic/elasticsearch";
2
- import { brotliCompressSync, brotliDecompressSync } from "zlib";
3
- import { Buffer } from "node:buffer";
4
- const index = "redis_data";
5
- export var MODE;
6
- (function (MODE) {
7
- MODE[MODE["STRING"] = 0] = "STRING";
8
- MODE[MODE["JSON"] = 1] = "JSON";
9
- MODE[MODE["HASH"] = 2] = "HASH";
10
- MODE[MODE["STRING_BROTLI"] = 3] = "STRING_BROTLI";
11
- })(MODE || (MODE = {}));
12
- export class CacheES {
13
- client;
14
- constructor(options) {
15
- this.client = new Client({
16
- ...(options || {}),
17
- tls: {
18
- rejectUnauthorized: false
19
- }
20
- });
21
- }
22
- async get(id, mode = MODE.STRING_BROTLI) {
23
- let data;
24
- try {
25
- switch (mode) {
26
- case MODE.STRING: {
27
- const value = (await this.client.get({
28
- index,
29
- id
30
- }))._source;
31
- data = value.data;
32
- break;
33
- }
34
- case MODE.STRING_BROTLI:
35
- default: {
36
- const value = (await this.client.get({
37
- index,
38
- id
39
- }))._source;
40
- const dataRaw = brotliDecompressSync(Buffer.from(value.data, "binary")).toString();
41
- data = JSON.parse(dataRaw);
42
- break;
43
- }
44
- }
45
- }
46
- catch (e) {
47
- data = null;
48
- }
49
- return data;
50
- }
51
- async set(id, value, mode = MODE.STRING_BROTLI) {
52
- try {
53
- switch (mode) {
54
- case MODE.STRING: {
55
- await this.client.index({
56
- index: "redis_data", // puoi cambiare il nome dell'indice
57
- id,
58
- document: {
59
- id,
60
- data: value.toString("binary")
61
- }
62
- });
63
- break;
64
- }
65
- case MODE.JSON:
66
- // @ts-ignore
67
- await this.client.jSet(id, ".", value);
68
- break;
69
- case MODE.STRING_BROTLI:
70
- default: {
71
- const data = brotliCompressSync(JSON.stringify(value));
72
- await this.client.index({
73
- index: "redis_data", // puoi cambiare il nome dell'indice
74
- id,
75
- document: {
76
- id,
77
- data: data.toString("binary")
78
- }
79
- });
80
- break;
81
- }
82
- }
83
- }
84
- catch (e) {
85
- console.error(`Can't cache data: ${e}`);
86
- }
87
- }
88
- async delete(id) {
89
- try {
90
- await this.client.delete({
91
- index,
92
- id
93
- });
94
- }
95
- catch (e) {
96
- console.error(`Can't delete data: ${e}`);
97
- }
98
- }
99
- async exists(id) {
100
- try {
101
- return !!(await this.client.exists({
102
- index: "redis_data",
103
- id
104
- }));
105
- }
106
- catch (e) {
107
- console.error(`Can't check data exists: ${e}`);
108
- }
109
- return;
110
- }
111
- async quit() {
112
- try {
113
- await this.client.close();
114
- }
115
- catch (e) {
116
- console.error(`Can't quit connection: ${e}`);
117
- }
118
- }
119
- }