discogs-marketplace-api-nodejs 1.8.1 → 1.9.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
@@ -4,10 +4,15 @@ Another (better ?) NodeJs library to fetch data from Discogs marketplace. 💿
4
4
 
5
5
  ## 📂 Installation (with npm)
6
6
 
7
+ 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.
8
+
7
9
  Run the following command in your project:
8
10
 
9
11
  ```sh
10
12
  npm install discogs-marketplace-api-nodejs
13
+
14
+ # Or to avoid installing Playwright
15
+ PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install discogs-marketplace-api-nodejs
11
16
  ```
12
17
 
13
18
  ## ▶️ Quick Start
@@ -102,6 +107,31 @@ const result = await DiscogsMarketplace.search({
102
107
  })
103
108
  ```
104
109
 
110
+ ## 🤠 About strategies
111
+
112
+ > Which `strategy` should I choose?
113
+
114
+ This project provides two ways to scrape data:
115
+
116
+ - `fetch` (default): Get the result with a classic HTTP fetch request (Axios).
117
+ - For the moment, this is the simplest and fastest solution to choose.
118
+ - `browser`: Get the result by creating a new instance of a browser (Playwright) to scrape the page.
119
+ - This can help bypass Cloudflare (or other) protection for some cases.
120
+ - Slightly slower than `fetch` (see [benchmarks](https://github.com/KirianCaumes/Discogs-Marketplace-API-NodeJS/releases/tag/v1.8.1))
121
+
122
+ **Both strategies will give you the exact same result.**
123
+
124
+ 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.
125
+
126
+ With both strategies, you are free to choose the one that suits you!
127
+
128
+ ```js
129
+ const result = await DiscogsMarketplace.search({
130
+ // ...
131
+ strategy: 'fetch' // or 'browser'
132
+ })
133
+ ```
134
+
105
135
  ## 📃 Data format
106
136
 
107
137
  You can provide parameters to `DiscogsMarketplace.search` function according to this interface:
@@ -198,6 +228,12 @@ interface InputInterface {
198
228
  * Default to `en`.
199
229
  */
200
230
  lang?: LangType
231
+ /**
232
+ * Strategy to scrape data:
233
+ * - `fetch` (default): Get the result with a classic HTTP fetch request (Axios).
234
+ * - `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.
235
+ */
236
+ strategy?: 'fetch' | 'browser'
201
237
  }
202
238
  ```
203
239
 
@@ -292,6 +328,20 @@ You can open a pull request with your new additions.
292
328
 
293
329
  ## 🐛 Known issues/problems
294
330
 
331
+ ### Linkedom
332
+
333
+ If you are using this library on a Typescript project, you might encounter issues with `linkedom`.
334
+
335
+ To fix it, use this in command line: `--skipLibCheck` or add that in you `tsconfig.json`:
336
+
337
+ ```json
338
+ {
339
+ "compilerOptions": {
340
+ "skipLibCheck": true
341
+ }
342
+ }
343
+ ```
344
+
295
345
  ### Playwright
296
346
 
297
347
  Install system dependencies:
@@ -302,4 +352,4 @@ sudo npx playwright install-deps chromium
302
352
 
303
353
  More information [here](https://playwright.dev/docs/browsers#install-system-dependencies).
304
354
 
305
- If you found another problem, feel free to open an issue.
355
+ 👉 If you find another problem, feel free to open an issue.
@@ -75,23 +75,34 @@ interface InputInterface {
75
75
  seller?: string;
76
76
  /**
77
77
  * Sort elements by.
78
+ *
78
79
  * Default to `Listed Newest`.
79
80
  */
80
81
  sort?: SortType;
81
82
  /**
82
83
  * Limit of elements to search (25 | 50 | 100 | 250).
84
+ *
83
85
  * Default to `25`.
84
86
  */
85
87
  limit?: LimitType;
86
88
  /**
87
89
  * Page (Must be < 401 or discogs will return an error 404).
90
+ *
88
91
  * Default to `1`.
89
92
  */
90
93
  page?: number;
91
94
  /**
92
95
  * Lang to use for Discogs.
96
+ *
93
97
  * Default to `en`.
94
98
  */
95
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';
96
107
  }
97
108
  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, }: InputInterface): Promise<OutputSuccessInterface>;
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>;
11
11
  /**
12
12
  * Generate URL to be parsed
13
13
  * @returns Url
@@ -19,6 +19,16 @@ 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;
22
32
  /**
23
33
  * Parse HTML to clean result
24
34
  * @returns Items found
@@ -5,6 +5,8 @@ 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"));
8
10
  const data_1 = require("./data/index.js");
9
11
  /**
10
12
  * Discogs Marketplace
@@ -14,40 +16,8 @@ class Marketplace {
14
16
  * Search elements on discogs
15
17
  * @returns Items found
16
18
  */
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', }) {
18
- var _a;
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', }) {
19
20
  try {
20
- /** Init browser */
21
- const browser = await playwright_chromium_1.chromium.launch({
22
- args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gl-drawing-for-tests'],
23
- });
24
- /** Init context */
25
- const browserContext = await browser.newContext({
26
- userAgent: new user_agents_1.default({ platform: 'Win32' }).toString(),
27
- extraHTTPHeaders: {
28
- 'X-PJAX': 'true',
29
- },
30
- javaScriptEnabled: false,
31
- });
32
- /** Init page */
33
- const browserPage = await browserContext.newPage();
34
- /** Block useless resources */
35
- await browserPage.route('**/*', route => [
36
- 'stylesheet',
37
- 'image',
38
- 'media',
39
- 'font',
40
- 'script',
41
- 'texttrack',
42
- 'xhr',
43
- 'fetch',
44
- 'eventsource',
45
- 'websocket',
46
- 'manifest',
47
- 'other',
48
- ].includes(route.request().resourceType())
49
- ? route.abort()
50
- : route.continue());
51
21
  /** Url to call */
52
22
  const url = [
53
23
  this.generateUrl({ searchType, seller, lang }),
@@ -70,39 +40,23 @@ class Marketplace {
70
40
  sort,
71
41
  }),
72
42
  ].join('?');
73
- /** Init page */
74
- const response = await browserPage.goto(url, { waitUntil: 'domcontentloaded' });
75
- /** Status code from the page */
76
- const status = (response === null || response === void 0 ? void 0 : response.status()) || 500;
77
- /** If error, reject */
78
- if (status >= 400) {
79
- // eslint-disable-next-line @typescript-eslint/no-throw-literal
80
- throw {
81
- message: (_a = (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(); }))) !== null && _a !== void 0 ? _a : 'An error occurred',
82
- code: status,
83
- };
84
- }
85
- /** Url generated by browser */
86
- const urlGenerated = browserPage.url();
87
- /**
88
- * Result from scraping.
89
- * Scraping inside Playwright is faster (x2) compare to exporting HTML outside and parsing it with another library.
90
- */
91
- const result = await browserPage.evaluate(this.getResult, {
92
- input: {
93
- page,
94
- limit,
95
- searchValue,
96
- searchType,
97
- },
98
- dependencies: {
99
- urlGenerated,
100
- CURRENCIES: data_1.CURRENCIES,
101
- COUNTRIES: data_1.COUNTRIES,
102
- },
103
- });
104
- /** Close browser */
105
- await browser.close();
43
+ /** Result got by different strategy type */
44
+ const result = await (async () => {
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
+ })();
106
60
  return result;
107
61
  }
108
62
  catch (error) {
@@ -166,11 +120,115 @@ class Marketplace {
166
120
  }
167
121
  return param.join('&');
168
122
  }
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, _c;
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
+ });
136
+ /** Generate document */
137
+ const { document } = (0, linkedom_1.parseHTML)(bodyHTML);
138
+ /** If error, reject */
139
+ if (status >= 400) {
140
+ // eslint-disable-next-line @typescript-eslint/no-throw-literal
141
+ throw {
142
+ message: (_c = (_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()) !== null && _c !== void 0 ? _c : 'An error occurred',
143
+ code: status,
144
+ };
145
+ }
146
+ const result = this.getResult({
147
+ input: { page, limit, searchValue, searchType },
148
+ dependencies: { urlGenerated: url, CURRENCIES: data_1.CURRENCIES, COUNTRIES: data_1.COUNTRIES },
149
+ document,
150
+ });
151
+ return result;
152
+ }
153
+ /**
154
+ * Get result by creating a new instance of a navigator (Playwright) to crawl the page
155
+ * @param url Url
156
+ */
157
+ static async getResultWithBrowser({ input: { page, limit, searchValue, searchType }, dependencies: { url }, }) {
158
+ var _a;
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: (_a = (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(); }))) !== null && _a !== void 0 ? _a : '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
+ }
169
226
  /**
170
227
  * Parse HTML to clean result
171
228
  * @returns Items found
172
229
  */
173
- static getResult({ input: { page, limit, searchValue, searchType }, dependencies: { urlGenerated, CURRENCIES, COUNTRIES }, }) {
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
232
  var _a, _b, _c, _d, _e;
175
233
  /**
176
234
  * Function to convert currency to ISO name
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discogs-marketplace-api-nodejs",
3
- "version": "1.8.1",
3
+ "version": "1.9.0",
4
4
  "description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
5
5
  "keywords": [
6
6
  "discogs",
@@ -33,6 +33,8 @@
33
33
  "node": ">=14.0.0"
34
34
  },
35
35
  "dependencies": {
36
+ "axios": "^1.6.2",
37
+ "linkedom": "^0.16.4",
36
38
  "playwright-chromium": "^1.40.0",
37
39
  "user-agents": "^1.1.24"
38
40
  },