discogs-marketplace-api-nodejs 1.7.3 → 1.8.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.
package/README.MD CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Another (better ?) NodeJs library to fetch data from Discogs marketplace. 💿
4
4
 
5
- ## Installation (with npm)
5
+ ## 📂 Installation (with npm)
6
6
 
7
7
  Run the following command in your project:
8
8
 
@@ -10,7 +10,7 @@ Run the following command in your project:
10
10
  npm install discogs-marketplace-api-nodejs
11
11
  ```
12
12
 
13
- ## Quick Start
13
+ ## ▶️ Quick Start
14
14
 
15
15
  Import `DiscogsMarketplace` into your project:
16
16
 
@@ -22,7 +22,7 @@ import { DiscogsMarketplace } from 'discogs-marketplace-api-nodejs'
22
22
  const DiscogsMarketplace = require('discogs-marketplace-api-nodejs').DiscogsMarketplace
23
23
  ```
24
24
 
25
- ## Examples
25
+ ## 🤔 Examples
26
26
 
27
27
  - Get top 250 items, of the 2nd page, filtered by Rock, listed by newest, for a given artist
28
28
 
@@ -102,7 +102,7 @@ const result = await DiscogsMarketplace.search({
102
102
  })
103
103
  ```
104
104
 
105
- ## Data format
105
+ ## 📃 Data format
106
106
 
107
107
  You can provide parameters to `DiscogsMarketplace.search` function according to this interface:
108
108
 
@@ -278,7 +278,7 @@ interface OutputErrorInterface {
278
278
  }
279
279
  ```
280
280
 
281
- ## How to contribute
281
+ ## 💡 How to contribute
282
282
 
283
283
  There is a [devcontainer](https://code.visualstudio.com/docs/devcontainers/containers) on that project already configured, feel free to use it.
284
284
 
@@ -290,20 +290,16 @@ npm install
290
290
 
291
291
  You can open a pull request with your new additions.
292
292
 
293
- ## Know issues
293
+ ## 🐛 Known issues/problems
294
294
 
295
- ### Linkedom
295
+ ### Playwright
296
296
 
297
- If you are using this library on a Typescript project, you might encounter issues with `linkedom`.
297
+ Install system dependencies:
298
298
 
299
- To fix it, use this in command line: `--skipLibCheck` or add that in you `tsconfig.json`:
300
-
301
- ```json
302
- {
303
- "compilerOptions": {
304
- "skipLibCheck": true
305
- }
306
- }
299
+ ```sh
300
+ sudo npx playwright install-deps chromium
307
301
  ```
308
302
 
303
+ More information [here](https://playwright.dev/docs/browsers#install-system-dependencies).
304
+
309
305
  If you found another problem, feel free to open an issue.
@@ -19,17 +19,9 @@ export default abstract class Marketplace {
19
19
  * @returns Url
20
20
  */
21
21
  private static serializeParams;
22
- /**
23
- * Function to convert currency to ISO name
24
- * @param value String to clean
25
- * @returns Cleanup string
26
- */
27
- private static convertCurrency;
28
22
  /**
29
23
  * Parse HTML to clean result
30
- * @param document Document to parse
31
- * @param urlGenerated Url generated
32
24
  * @returns Items found
33
25
  */
34
- private static getData;
26
+ private static getResult;
35
27
  }
@@ -1,20 +1,10 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
14
5
  Object.defineProperty(exports, "__esModule", { value: true });
15
6
  const user_agents_1 = __importDefault(require("user-agents"));
16
- const linkedom_1 = require("linkedom");
17
- const axios_1 = __importDefault(require("axios"));
7
+ const playwright_chromium_1 = require("playwright-chromium");
18
8
  const data_1 = require("./data/index.js");
19
9
  /**
20
10
  * Discogs Marketplace
@@ -24,65 +14,108 @@ class Marketplace {
24
14
  * Search elements on discogs
25
15
  * @returns Items found
26
16
  */
27
- static 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', }) {
28
- var _a, _b, _c, _d;
29
- return __awaiter(this, void 0, void 0, function* () {
30
- try {
31
- const config = {
32
- url: this.generateUrl({ searchType, seller, lang }),
33
- method: 'GET',
34
- params: {
35
- [searchType]: searchValue,
36
- currency,
37
- genre,
38
- style: (style === null || style === void 0 ? void 0 : style.length) ? style : undefined,
39
- format: (format === null || format === void 0 ? void 0 : format.length) ? format : undefined,
40
- format_desc: (formatDescription === null || formatDescription === void 0 ? void 0 : formatDescription.length) ? formatDescription : undefined,
41
- condition: (condition === null || condition === void 0 ? void 0 : condition.length) ? condition : undefined,
42
- year: year && !years ? year : undefined,
43
- year1: (years === null || years === void 0 ? void 0 : years.min) && !year ? years === null || years === void 0 ? void 0 : years.min : undefined,
44
- year2: (years === null || years === void 0 ? void 0 : years.max) && !year ? years === null || years === void 0 ? void 0 : years.max : undefined,
45
- audio: isAudioSample ? 1 : undefined,
46
- offers: isMakeAnOfferOnly ? 1 : undefined,
47
- ships_from: (from === null || from === void 0 ? void 0 : from.length) ? from : undefined,
48
- limit,
49
- page,
50
- sort,
51
- },
52
- paramsSerializer: {
53
- serialize: this.serializeParams,
54
- },
55
- headers: {
56
- // cspell: disable-next-line
57
- 'X-PJAX': 'true',
58
- 'User-Agent': new user_agents_1.default({ platform: 'Win32' }).toString(),
59
- },
60
- };
61
- const { data: bodyHTML } = yield axios_1.default.request(config);
62
- return this.getData((0, linkedom_1.parseHTML)(bodyHTML).document, axios_1.default.getUri(config), {
63
- searchType,
64
- searchValue,
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
+ 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
+ /** Url to call */
52
+ const url = [
53
+ this.generateUrl({ searchType, seller, lang }),
54
+ this.serializeParams({
55
+ [searchType]: searchValue,
56
+ currency,
57
+ genre,
58
+ style: (style === null || style === void 0 ? void 0 : style.length) ? style : undefined,
59
+ format: (format === null || format === void 0 ? void 0 : format.length) ? format : undefined,
60
+ format_desc: (formatDescription === null || formatDescription === void 0 ? void 0 : formatDescription.length) ? formatDescription : undefined,
61
+ condition: (condition === null || condition === void 0 ? void 0 : condition.length) ? condition : undefined,
62
+ year: year && !years ? year : undefined,
63
+ year1: (years === null || years === void 0 ? void 0 : years.min) && !year ? years === null || years === void 0 ? void 0 : years.min : undefined,
64
+ year2: (years === null || years === void 0 ? void 0 : years.max) && !year ? years === null || years === void 0 ? void 0 : years.max : undefined,
65
+ audio: isAudioSample ? 1 : undefined,
66
+ offers: isMakeAnOfferOnly ? 1 : undefined,
67
+ ships_from: (from === null || from === void 0 ? void 0 : from.length) ? from : undefined,
65
68
  limit,
66
69
  page,
67
- });
68
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
- }
70
- catch (error) {
71
- const { response, message } = error;
72
- if ((response === null || response === void 0 ? void 0 : response.data) && response.status) {
73
- // eslint-disable-next-line @typescript-eslint/no-throw-literal
74
- throw {
75
- message: (_d = (_c = (_b = (_a = (0, linkedom_1.parseHTML)(response.data).document) === null || _a === void 0 ? void 0 : _a.querySelector('h1 + p')) === null || _b === void 0 ? void 0 : _b.innerHTML) === null || _c === void 0 ? void 0 : _c.trim()) !== null && _d !== void 0 ? _d : 'An error occurred',
76
- code: response.status,
77
- };
78
- }
70
+ sort,
71
+ }),
72
+ ].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
79
  // eslint-disable-next-line @typescript-eslint/no-throw-literal
80
80
  throw {
81
- message: message || 'An error occurred',
82
- code: 500,
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
83
  };
84
84
  }
85
- });
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();
106
+ return result;
107
+ }
108
+ catch (error) {
109
+ if (error.message && error.code) {
110
+ // Rethrow error
111
+ throw error;
112
+ }
113
+ // eslint-disable-next-line @typescript-eslint/no-throw-literal
114
+ throw {
115
+ message: (error === null || error === void 0 ? void 0 : error.message) || 'An error occurred',
116
+ code: 500,
117
+ };
118
+ }
86
119
  }
87
120
  /**
88
121
  * Generate URL to be parsed
@@ -133,47 +166,45 @@ class Marketplace {
133
166
  }
134
167
  return param.join('&');
135
168
  }
136
- /**
137
- * Function to convert currency to ISO name
138
- * @param value String to clean
139
- * @returns Cleanup string
140
- */
141
- static convertCurrency(value) {
142
- var _a;
143
- if (!value) {
144
- return value;
145
- }
146
- const currencyFound = (_a = Object.keys(data_1.CURRENCIES).find(key => value.includes(key))) !== null && _a !== void 0 ? _a : '';
147
- if (!currencyFound) {
148
- return value;
149
- }
150
- const currencyClean = data_1.CURRENCIES[currencyFound];
151
- const amount = value
152
- .replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dot but last, except if JPY
153
- .replace(currencyFound, '') // Remove original currency
154
- .replace(/\s/g, ''); // Remove spaces
155
- return `${amount} ${currencyClean}`.replace(/\s\s+/g, ' '); // Remove useless spaces
156
- }
157
169
  /**
158
170
  * Parse HTML to clean result
159
- * @param document Document to parse
160
- * @param urlGenerated Url generated
161
171
  * @returns Items found
162
172
  */
163
- static getData(document, urlGenerated, { searchType = 'q', searchValue = undefined, limit = 25, page = 1 }) {
173
+ static getResult({ input: { page, limit, searchValue, searchType }, dependencies: { urlGenerated, CURRENCIES, COUNTRIES }, }) {
164
174
  var _a, _b, _c, _d, _e;
175
+ /**
176
+ * Function to convert currency to ISO name
177
+ * @param value String to clean
178
+ * @returns Cleanup string
179
+ */
180
+ const convertCurrency = (value) => {
181
+ var _a;
182
+ if (!value) {
183
+ return value;
184
+ }
185
+ const currencyFound = (_a = Object.keys(CURRENCIES).find(key => value.includes(key))) !== null && _a !== void 0 ? _a : '';
186
+ if (!currencyFound) {
187
+ return value;
188
+ }
189
+ const currencyClean = CURRENCIES[currencyFound];
190
+ const amount = value
191
+ .replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dot but last, except if JPY
192
+ .replace(currencyFound, '') // Remove original currency
193
+ .replace(/\s/g, ''); // Remove spaces
194
+ return `${amount} ${currencyClean}`.replace(/\s\s+/g, ' '); // Remove useless spaces
195
+ };
165
196
  const totalItems = parseFloat(((_d = (_c = (_b = (_a = document
166
- .querySelector('.pagination_total')) === null || _a === void 0 ? void 0 : _a.textContent) === null || _b === void 0 ? void 0 : _b.split(' ')) === null || _c === void 0 ? void 0 : _c.filter((x) => x).pop()) === null || _d === void 0 ? void 0 : _d.replace(/(,|\.|\s)/g, '')) || '0');
197
+ .querySelector('.pagination_total')) === null || _a === void 0 ? void 0 : _a.textContent) === null || _b === void 0 ? void 0 : _b.split(' ')) === null || _c === void 0 ? void 0 : _c.filter(x => x).pop()) === null || _d === void 0 ? void 0 : _d.replace(/(,|\.|\s)/g, '')) || '0');
167
198
  return {
168
199
  items: ((_e = [...document.querySelectorAll('table.table_block tbody tr')]) === null || _e === void 0 ? void 0 : _e.map(el => {
169
200
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58;
170
201
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
171
- const shipping = this.convertCurrency((_g = (_f = (_e = (_d = (_c = (_b = (_a = el
202
+ const shipping = convertCurrency((_g = (_f = (_e = (_d = (_c = (_b = (_a = el
172
203
  .querySelector('.item_shipping')) === null || _a === void 0 ? void 0 : _a.childNodes) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.textContent) === null || _d === void 0 ? void 0 : _d.replace(/(\s+|\+)/g, ' ')) === null || _e === void 0 ? void 0 : _e.trim()) === null || _f === void 0 ? void 0 : _f.replace(',', '.')) !== null && _g !== void 0 ? _g : '');
173
204
  const have = Number.parseInt((_j = (_h = el.querySelector('.community_summary .community_result:nth-child(1) .community_number')) === null || _h === void 0 ? void 0 : _h.textContent) !== null && _j !== void 0 ? _j : '', 10);
174
205
  const want = Number.parseInt((_l = (_k = el.querySelector('.community_summary .community_result:nth-child(2) .community_number')) === null || _k === void 0 ? void 0 : _k.textContent) !== null && _l !== void 0 ? _l : '', 10);
175
206
  const countryName = (_q = (_p = (_o = (_m = el.querySelector('.seller_info li:nth-child(3)')) === null || _m === void 0 ? void 0 : _m.textContent) === null || _o === void 0 ? void 0 : _o.split(':')) === null || _p === void 0 ? void 0 : _p.pop()) !== null && _q !== void 0 ? _q : '';
176
- const countryCode = data_1.COUNTRIES[countryName];
207
+ const countryCode = COUNTRIES[countryName];
177
208
  const releaseId = Number.parseInt((_v = (_u = (_t = (_s = (_r = el.querySelector('a.item_release_link')) === null || _r === void 0 ? void 0 : _r.href.split('release/')) === null || _s === void 0 ? void 0 : _s.pop()) === null || _t === void 0 ? void 0 : _t.split('-')) === null || _u === void 0 ? void 0 : _u.shift()) !== null && _v !== void 0 ? _v : '0', 10);
178
209
  const itemId = Number.parseInt((_y = (_x = (_w = el.querySelector('a.item_description_title')) === null || _w === void 0 ? void 0 : _w.href) === null || _x === void 0 ? void 0 : _x.split('/').pop()) !== null && _y !== void 0 ? _y : '0', 10);
179
210
  const notes = Number.parseInt((_5 = (_4 = (_3 = (_2 = (_1 = (_0 = (_z = el
@@ -221,7 +252,7 @@ class Marketplace {
221
252
  notes: Number.isNaN(notes) ? 0 : notes,
222
253
  },
223
254
  price: {
224
- base: this.convertCurrency((_57 = (_56 = (_55 = (_54 = el.querySelector('.price')) === null || _54 === void 0 ? void 0 : _54.textContent) === null || _55 === void 0 ? void 0 : _55.replace(/\s+/g, ' ')) === null || _56 === void 0 ? void 0 : _56.replace(/,/, '.')) !== null && _57 !== void 0 ? _57 : ''),
255
+ base: convertCurrency((_57 = (_56 = (_55 = (_54 = el.querySelector('.price')) === null || _54 === void 0 ? void 0 : _54.textContent) === null || _55 === void 0 ? void 0 : _55.replace(/\s+/g, ' ')) === null || _56 === void 0 ? void 0 : _56.replace(/,/, '.')) !== null && _57 !== void 0 ? _57 : ''),
225
256
  shipping: Number.isNaN(parseFloat(shipping)) ? null : shipping,
226
257
  },
227
258
  country: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discogs-marketplace-api-nodejs",
3
- "version": "1.7.3",
3
+ "version": "1.8.1",
4
4
  "description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
5
5
  "keywords": [
6
6
  "discogs",
@@ -33,8 +33,7 @@
33
33
  "node": ">=14.0.0"
34
34
  },
35
35
  "dependencies": {
36
- "axios": "^1.6.2",
37
- "linkedom": "^0.16.4",
36
+ "playwright-chromium": "^1.40.0",
38
37
  "user-agents": "^1.1.24"
39
38
  },
40
39
  "devDependencies": {