discogs-marketplace-api-nodejs 1.9.3 → 1.10.0

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.
package/README.MD CHANGED
@@ -6,15 +6,10 @@ Another (better ?) NodeJs library to fetch data from Discogs marketplace. 💿
6
6
 
7
7
  ## 📂 Installation (with npm)
8
8
 
9
- This library works with two different `strategies` to scrape data: with a classic HTTP fetch request (Axios) or by creating a new instance of a browser (Playwright). Take a look at the "[About strategies](#-about-strategies)" chapter to learn more.
10
-
11
9
  Run the following command in your project:
12
10
 
13
11
  ```sh
14
- npm install discogs-marketplace-api-nodejs
15
-
16
- # Or to avoid installing Playwright
17
- PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install discogs-marketplace-api-nodejs
12
+ npm i discogs-marketplace-api-nodejs
18
13
  ```
19
14
 
20
15
  ## ▶️ Quick Start
@@ -109,31 +104,6 @@ const result = await DiscogsMarketplace.search({
109
104
  })
110
105
  ```
111
106
 
112
- ## 🤠 About strategies
113
-
114
- > Which `strategy` should I choose?
115
-
116
- This project provides two ways to scrape data:
117
-
118
- - `fetch` (default): Get the result with a classic HTTP fetch request (Axios).
119
- - For the moment, this is the simplest and fastest solution to choose.
120
- - `browser`: Get the result by creating a new instance of a browser (Playwright) to scrape the page.
121
- - This can help bypass Cloudflare (or other) protection for some cases.
122
- - Slightly slower than `fetch` (see [benchmarks](https://github.com/KirianCaumes/Discogs-Marketplace-API-NodeJS/releases/tag/v1.8.1))
123
-
124
- **Both strategies will give you the exact same result.**
125
-
126
- I choose to maintain this two solutions, because over time Discogs is changing: one day they activated a protection that prevented a `fetch` solution from working, so I implemented to `browser` solution. But a few days later, they disabled that protection and the original solution became the best again.
127
-
128
- With both strategies, you are free to choose the one that suits you!
129
-
130
- ```js
131
- const result = await DiscogsMarketplace.search({
132
- // ...
133
- strategy: 'fetch' // or 'browser'
134
- })
135
- ```
136
-
137
107
  ## 📃 Data format
138
108
 
139
109
  You can provide parameters to `DiscogsMarketplace.search` function according to this interface:
@@ -230,12 +200,6 @@ interface InputInterface {
230
200
  * Default to `en`.
231
201
  */
232
202
  lang?: LangType
233
- /**
234
- * Strategy to scrape data:
235
- * - `fetch` (default): Get the result with a classic HTTP fetch request (Axios).
236
- * - `browser`: Get the result by creating a new instance of a browser (Playwright) to scrape the page. This can help bypass Cloudflare (or other) protection for some cases.
237
- */
238
- strategy?: 'fetch' | 'browser'
239
203
  }
240
204
  ```
241
205
 
@@ -330,20 +294,6 @@ You can open a pull request with your new additions.
330
294
 
331
295
  ## 🐛 Known issues/problems
332
296
 
333
- ### Linkedom
334
-
335
- If you are using this library on a Typescript project, you might encounter issues with `linkedom`.
336
-
337
- To fix it, use this in command line: `--skipLibCheck` or add that in you `tsconfig.json`:
338
-
339
- ```json
340
- {
341
- "compilerOptions": {
342
- "skipLibCheck": true
343
- }
344
- }
345
- ```
346
-
347
297
  ### Playwright
348
298
 
349
299
  Install system dependencies:
@@ -97,12 +97,5 @@ interface InputInterface {
97
97
  * Default to `en`.
98
98
  */
99
99
  lang?: LangType;
100
- /**
101
- * Strategy to scrape data:
102
- * - `fetch` (default): Get the result with a classic HTTP fetch request (Axios).
103
- * - `browser`: Get the result by creating a new instance of a browser (Playwright) to scrape the page.
104
- * This can help bypass Cloudflare (or other) protection for some cases.
105
- */
106
- strategy?: 'fetch' | 'browser';
107
100
  }
108
101
  export default InputInterface;
@@ -7,7 +7,7 @@ export default abstract class Marketplace {
7
7
  * Search elements on discogs
8
8
  * @returns Items found
9
9
  */
10
- static search({ searchType, searchValue, currency, genre, style, format, formatDescription, condition, year, years, isAudioSample, isMakeAnOfferOnly, from, seller, sort, limit, page, lang, strategy, }: InputInterface): Promise<OutputSuccessInterface>;
10
+ static search({ searchType, searchValue, currency, genre, style, format, formatDescription, condition, year, years, isAudioSample, isMakeAnOfferOnly, from, seller, sort, limit, page, lang, }: InputInterface): Promise<OutputSuccessInterface>;
11
11
  /**
12
12
  * Generate URL to be parsed
13
13
  * @returns Url
@@ -19,16 +19,6 @@ export default abstract class Marketplace {
19
19
  * @returns Url
20
20
  */
21
21
  private static serializeParams;
22
- /**
23
- * Get result with a classic HTTP fetch request (Axios)
24
- * @param url Url
25
- */
26
- private static getResultWithFetch;
27
- /**
28
- * Get result by creating a new instance of a navigator (Playwright) to crawl the page
29
- * @param url Url
30
- */
31
- private static getResultWithBrowser;
32
22
  /**
33
23
  * Parse HTML to clean result
34
24
  * @returns Items found
@@ -5,8 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const user_agents_1 = __importDefault(require("user-agents"));
7
7
  const playwright_chromium_1 = require("playwright-chromium");
8
- const linkedom_1 = require("linkedom");
9
- const axios_1 = __importDefault(require("axios"));
10
8
  const data_1 = require("./data/index.js");
11
9
  /**
12
10
  * Discogs Marketplace
@@ -16,7 +14,7 @@ class Marketplace {
16
14
  * Search elements on discogs
17
15
  * @returns Items found
18
16
  */
19
- static async search({ searchType = 'q', searchValue = undefined, currency = undefined, genre = undefined, style = [], format = [], formatDescription = [], condition = [], year = undefined, years = undefined, isAudioSample = false, isMakeAnOfferOnly = false, from = undefined, seller = undefined, sort = 'Listed Newest', limit = 25, page = 1, lang = 'en', strategy = 'fetch', }) {
17
+ static async search({ searchType = 'q', searchValue = undefined, currency = undefined, genre = undefined, style = [], format = [], formatDescription = [], condition = [], year = undefined, years = undefined, isAudioSample = false, isMakeAnOfferOnly = false, from = undefined, seller = undefined, sort = 'Listed Newest', limit = 25, page = 1, lang = 'en', }) {
20
18
  try {
21
19
  /** Url to call */
22
20
  const url = [
@@ -40,23 +38,72 @@ class Marketplace {
40
38
  sort,
41
39
  }),
42
40
  ].join('?');
43
- /** Result got by different strategy type */
44
- const result = await (() => {
45
- switch (strategy) {
46
- case 'fetch':
47
- return this.getResultWithFetch({
48
- input: { page, limit, searchValue, searchType },
49
- dependencies: { url },
50
- });
51
- case 'browser':
52
- return this.getResultWithBrowser({
53
- input: { page, limit, searchValue, searchType },
54
- dependencies: { url },
55
- });
56
- default:
57
- throw new Error('Unreachable');
58
- }
59
- })();
41
+ /** Init browser */
42
+ const browser = await playwright_chromium_1.chromium.launch({
43
+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gl-drawing-for-tests'],
44
+ });
45
+ /** Init context */
46
+ const browserContext = await browser.newContext({
47
+ userAgent: new user_agents_1.default({ platform: 'Win32' }).toString(),
48
+ extraHTTPHeaders: {
49
+ 'X-PJAX': 'true',
50
+ },
51
+ javaScriptEnabled: false,
52
+ });
53
+ /** Init page */
54
+ const browserPage = await browserContext.newPage();
55
+ /** Block useless resources */
56
+ await browserPage.route('**/*', route => [
57
+ 'stylesheet',
58
+ 'image',
59
+ 'media',
60
+ 'font',
61
+ 'script',
62
+ 'texttrack',
63
+ 'xhr',
64
+ 'fetch',
65
+ 'eventsource',
66
+ 'websocket',
67
+ 'manifest',
68
+ 'other',
69
+ ].includes(route.request().resourceType())
70
+ ? route.abort()
71
+ : route.continue());
72
+ /** Init page */
73
+ const response = await browserPage.goto(url, { waitUntil: 'domcontentloaded' });
74
+ /** Status code from the page */
75
+ const status = (response === null || response === void 0 ? void 0 : response.status()) || 500;
76
+ // See current issue: https://github.com/evanw/esbuild/issues/2605
77
+ // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-explicit-any, no-return-assign
78
+ await browserPage.evaluate(() => { var _a; var _b; return ((_a = (_b = window).__name) !== null && _a !== void 0 ? _a : (_b.__name = (func) => func)); });
79
+ /** If error, reject */
80
+ if (status >= 400) {
81
+ // eslint-disable-next-line @typescript-eslint/no-throw-literal
82
+ throw {
83
+ message: (await browserPage.evaluate(() => { var _a, _b; return (_b = (_a = document === null || document === void 0 ? void 0 : document.querySelector('h1 + p')) === null || _a === void 0 ? void 0 : _a.innerHTML) === null || _b === void 0 ? void 0 : _b.trim(); })) || 'An error occurred',
84
+ code: status,
85
+ };
86
+ }
87
+ /** Url generated by browser */
88
+ const urlGenerated = browserPage.url();
89
+ /**
90
+ * Result from scraping.
91
+ * Scraping inside Playwright is faster (x2) compare to exporting HTML outside and parsing it with another library.
92
+ */
93
+ const result = await browserPage.evaluate(this.getResult, {
94
+ input: {
95
+ page,
96
+ limit,
97
+ searchValue,
98
+ searchType,
99
+ },
100
+ urlGenerated,
101
+ CURRENCIES: data_1.CURRENCIES,
102
+ COUNTRIES: data_1.COUNTRIES,
103
+ });
104
+ /** Close context/browser */
105
+ await browserContext.close();
106
+ await browser.close();
60
107
  return result;
61
108
  }
62
109
  catch (error) {
@@ -120,115 +167,11 @@ class Marketplace {
120
167
  }
121
168
  return param.join('&');
122
169
  }
123
- /**
124
- * Get result with a classic HTTP fetch request (Axios)
125
- * @param url Url
126
- */
127
- static async getResultWithFetch({ input: { page, limit, searchValue, searchType }, dependencies: { url }, }) {
128
- var _a, _b;
129
- const { data: bodyHTML, status } = await axios_1.default.get(url, {
130
- headers: {
131
- // cspell: disable-next-line
132
- 'X-PJAX': 'true',
133
- 'User-Agent': new user_agents_1.default({ platform: 'Win32' }).toString(),
134
- },
135
- validateStatus: () => true,
136
- });
137
- /** Generate document */
138
- const { document } = (0, linkedom_1.parseHTML)(bodyHTML);
139
- /** If error, reject */
140
- if (status >= 400) {
141
- // eslint-disable-next-line @typescript-eslint/no-throw-literal
142
- throw {
143
- message: ((_b = (_a = document === null || document === void 0 ? void 0 : document.querySelector('h1 + p')) === null || _a === void 0 ? void 0 : _a.innerHTML) === null || _b === void 0 ? void 0 : _b.trim()) || 'An error occurred',
144
- code: status,
145
- };
146
- }
147
- const result = this.getResult({
148
- input: { page, limit, searchValue, searchType },
149
- dependencies: { urlGenerated: url, CURRENCIES: data_1.CURRENCIES, COUNTRIES: data_1.COUNTRIES },
150
- document,
151
- });
152
- return result;
153
- }
154
- /**
155
- * Get result by creating a new instance of a navigator (Playwright) to crawl the page
156
- * @param url Url
157
- */
158
- static async getResultWithBrowser({ input: { page, limit, searchValue, searchType }, dependencies: { url }, }) {
159
- /** Init browser */
160
- const browser = await playwright_chromium_1.chromium.launch({
161
- args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gl-drawing-for-tests'],
162
- });
163
- /** Init context */
164
- const browserContext = await browser.newContext({
165
- userAgent: new user_agents_1.default({ platform: 'Win32' }).toString(),
166
- extraHTTPHeaders: {
167
- 'X-PJAX': 'true',
168
- },
169
- javaScriptEnabled: false,
170
- });
171
- /** Init page */
172
- const browserPage = await browserContext.newPage();
173
- /** Block useless resources */
174
- await browserPage.route('**/*', route => [
175
- 'stylesheet',
176
- 'image',
177
- 'media',
178
- 'font',
179
- 'script',
180
- 'texttrack',
181
- 'xhr',
182
- 'fetch',
183
- 'eventsource',
184
- 'websocket',
185
- 'manifest',
186
- 'other',
187
- ].includes(route.request().resourceType())
188
- ? route.abort()
189
- : route.continue());
190
- /** Init page */
191
- const response = await browserPage.goto(url, { waitUntil: 'domcontentloaded' });
192
- /** Status code from the page */
193
- const status = (response === null || response === void 0 ? void 0 : response.status()) || 500;
194
- /** If error, reject */
195
- if (status >= 400) {
196
- // eslint-disable-next-line @typescript-eslint/no-throw-literal
197
- throw {
198
- message: (await browserPage.evaluate(() => { var _a, _b; return (_b = (_a = document === null || document === void 0 ? void 0 : document.querySelector('h1 + p')) === null || _a === void 0 ? void 0 : _a.innerHTML) === null || _b === void 0 ? void 0 : _b.trim(); })) || 'An error occurred',
199
- code: status,
200
- };
201
- }
202
- /** Url generated by browser */
203
- const urlGenerated = browserPage.url();
204
- /**
205
- * Result from scraping.
206
- * Scraping inside Playwright is faster (x2) compare to exporting HTML outside and parsing it with another library.
207
- */
208
- const result = await browserPage.evaluate(this.getResult, {
209
- input: {
210
- page,
211
- limit,
212
- searchValue,
213
- searchType,
214
- },
215
- dependencies: {
216
- urlGenerated,
217
- CURRENCIES: data_1.CURRENCIES,
218
- COUNTRIES: data_1.COUNTRIES,
219
- },
220
- });
221
- /** Close context/browser */
222
- await browserContext.close();
223
- await browser.close();
224
- return result;
225
- }
226
170
  /**
227
171
  * Parse HTML to clean result
228
172
  * @returns Items found
229
173
  */
230
- static getResult({ input: { page, limit, searchValue, searchType }, dependencies: { urlGenerated, CURRENCIES, COUNTRIES }, document = globalThis.document, // Note: this default value will only work with Playwright
231
- }) {
174
+ static getResult({ input: { page, limit, searchValue, searchType }, urlGenerated, CURRENCIES, COUNTRIES, }) {
232
175
  var _a, _b, _c, _d, _e;
233
176
  /**
234
177
  * Function to convert currency to ISO name
@@ -277,10 +220,10 @@ class Marketplace {
277
220
  original: originalTitle !== null && originalTitle !== void 0 ? originalTitle : '',
278
221
  artist: (_10 = originalTitle === null || originalTitle === void 0 ? void 0 : originalTitle.substring(0, firstIndexOfDash)) !== null && _10 !== void 0 ? _10 : '',
279
222
  item: firstIndexOfDash > -1 && lastIndexOfParenthesis > -1
280
- ? (_11 = originalTitle === null || originalTitle === void 0 ? void 0 : originalTitle.substring(firstIndexOfDash + 3, lastIndexOfParenthesis)) !== null && _11 !== void 0 ? _11 : ''
223
+ ? ((_11 = originalTitle === null || originalTitle === void 0 ? void 0 : originalTitle.substring(firstIndexOfDash + 3, lastIndexOfParenthesis)) !== null && _11 !== void 0 ? _11 : '')
281
224
  : '',
282
225
  formats: lastIndexOfParenthesis > -1
283
- ? (_13 = (_12 = originalTitle === null || originalTitle === void 0 ? void 0 : originalTitle.substring(lastIndexOfParenthesis + 2, originalTitle.length - 1)) === null || _12 === void 0 ? void 0 : _12.split(', ')) !== null && _13 !== void 0 ? _13 : []
226
+ ? ((_13 = (_12 = originalTitle === null || originalTitle === void 0 ? void 0 : originalTitle.substring(lastIndexOfParenthesis + 2, originalTitle.length - 1)) === null || _12 === void 0 ? void 0 : _12.split(', ')) !== null && _13 !== void 0 ? _13 : [])
284
227
  : [],
285
228
  },
286
229
  url: `https://www.discogs.com${(_14 = el
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discogs-marketplace-api-nodejs",
3
- "version": "1.9.3",
3
+ "version": "1.10.0",
4
4
  "description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
5
5
  "keywords": [
6
6
  "discogs",
@@ -16,11 +16,11 @@
16
16
  "author": "KirianCaumes",
17
17
  "license": "MIT",
18
18
  "scripts": {
19
- "prepare": "husky install && npm run build",
19
+ "prepare": "husky && npm run build",
20
20
  "prebuild": "rimraf dist",
21
21
  "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
22
- "start:dev": "nodemon -r tsconfig-paths/register ./src/index.ts",
23
- "test": "jest",
22
+ "start:dev": "node --import tsx --watch ./src/index.ts",
23
+ "test": "node --import tsx --test ./test/*.test.ts",
24
24
  "eslint:fix": "eslint src test --ext .ts,.js --fix",
25
25
  "eslint": "eslint src test --ext .ts,.js",
26
26
  "prettier": "prettier --check .",
@@ -40,35 +40,28 @@
40
40
  }
41
41
  ],
42
42
  "dependencies": {
43
- "axios": "^1.6.8",
44
- "linkedom": "^0.16.11",
45
- "playwright-chromium": "^1.43.1",
46
- "user-agents": "^1.1.186"
43
+ "playwright-chromium": "^1.45.2",
44
+ "user-agents": "^1.1.271"
47
45
  },
48
46
  "devDependencies": {
49
- "@types/jest": "^29.5.12",
50
- "@types/node": "^20.12.7",
47
+ "@types/node": "^20.14.11",
51
48
  "@types/user-agents": "^1.0.4",
52
- "@typescript-eslint/eslint-plugin": "^7.7.1",
53
- "@typescript-eslint/parser": "^7.7.1",
54
- "cspell": "^8.7.0",
49
+ "@typescript-eslint/eslint-plugin": "^7.16.1",
50
+ "@typescript-eslint/parser": "^7.16.1",
51
+ "cspell": "^8.11.0",
55
52
  "eslint": "^8.57.0",
56
53
  "eslint-config-airbnb-base": "^15.0.0",
57
54
  "eslint-config-airbnb-typescript": "^18.0.0",
58
55
  "eslint-config-prettier": "^9.1.0",
59
- "eslint-import-resolver-typescript": "^3.6.1",
60
56
  "eslint-plugin-import": "^2.29.1",
61
- "eslint-plugin-jsdoc": "^48.2.3",
62
- "husky": "^9.0.11",
63
- "jest": "^29.7.0",
64
- "knip": "^5.11.0",
65
- "lint-staged": "^15.2.2",
66
- "nodemon": "^3.1.0",
67
- "prettier": "^3.2.5",
68
- "rimraf": "^5.0.5",
69
- "ts-jest": "^29.1.2",
70
- "tsc-alias": "^1.8.8",
71
- "tsconfig-paths": "^4.2.0",
72
- "typescript": "^5.4.5"
57
+ "eslint-plugin-jsdoc": "^48.8.3",
58
+ "husky": "^9.1.1",
59
+ "knip": "^5.26.0",
60
+ "lint-staged": "^15.2.7",
61
+ "prettier": "^3.3.3",
62
+ "rimraf": "^6.0.1",
63
+ "tsc-alias": "^1.8.10",
64
+ "tsx": "^4.16.2",
65
+ "typescript": "^5.5.3"
73
66
  }
74
67
  }