discogs-marketplace-api-nodejs 1.10.1 → 1.11.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.
Files changed (37) hide show
  1. package/README.MD +47 -39
  2. package/dist/data/{countries.data.d.ts → country.data.d.ts} +5 -2
  3. package/dist/data/{countries.data.js → country.data.js} +6 -6
  4. package/dist/data/{currencies.data.d.ts → currency.data.d.ts} +5 -2
  5. package/dist/data/{currencies.data.js → currency.data.js} +2 -2
  6. package/dist/index.d.ts +11 -4
  7. package/dist/index.js +6 -2
  8. package/dist/interfaces/{input.interface.d.ts → search-params.interface.d.ts} +39 -24
  9. package/dist/interfaces/{output-success.interface.d.ts → search-result.interface.d.ts} +19 -16
  10. package/dist/scrape.d.ts +10 -0
  11. package/dist/scrape.js +126 -0
  12. package/dist/search.d.ts +11 -0
  13. package/dist/search.js +154 -0
  14. package/dist/types/condition.type.d.ts +1 -1
  15. package/dist/types/currency.type.d.ts +1 -1
  16. package/dist/types/format-description.type.d.ts +1 -1
  17. package/dist/types/format.type.d.ts +1 -1
  18. package/dist/types/from.type.d.ts +1 -1
  19. package/dist/types/genre.type.d.ts +1 -1
  20. package/dist/types/lang.type.d.ts +1 -1
  21. package/dist/types/limit.type.d.ts +1 -1
  22. package/dist/types/search-type.type.d.ts +1 -1
  23. package/dist/types/sort.type.d.ts +1 -1
  24. package/dist/types/style.type.d.ts +1 -1
  25. package/package.json +3 -2
  26. package/dist/data/index.d.ts +0 -3
  27. package/dist/data/index.js +0 -10
  28. package/dist/interfaces/index.d.ts +0 -4
  29. package/dist/interfaces/output-error.interface.d.ts +0 -9
  30. package/dist/interfaces/output-error.interface.js +0 -2
  31. package/dist/interfaces/output-success.interface.js +0 -2
  32. package/dist/marketplace.d.ts +0 -27
  33. package/dist/marketplace.js +0 -311
  34. package/dist/types/index.d.ts +0 -12
  35. package/dist/types/index.js +0 -2
  36. /package/dist/interfaces/{index.js → search-params.interface.js} +0 -0
  37. /package/dist/interfaces/{input.interface.js → search-result.interface.js} +0 -0
@@ -1,311 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const user_agents_1 = __importDefault(require("user-agents"));
7
- const playwright_chromium_1 = require("playwright-chromium");
8
- const data_1 = require("./data");
9
- /**
10
- * Discogs Marketplace
11
- */
12
- // eslint-disable-next-line @typescript-eslint/no-extraneous-class
13
- class Marketplace {
14
- /**
15
- * Search elements on discogs
16
- * @returns Items found
17
- */
18
- 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', }) {
19
- try {
20
- /** Url to call */
21
- const url = [
22
- this.generateUrl({ searchType, seller, lang }),
23
- this.serializeParams({
24
- [searchType]: searchValue,
25
- currency,
26
- genre,
27
- style: style.length ? style : undefined,
28
- format: format.length ? format : undefined,
29
- format_desc: formatDescription.length ? formatDescription : undefined,
30
- condition: condition.length ? condition : undefined,
31
- year: year && !years ? year : undefined,
32
- year1: years?.min && !year ? years.min : undefined,
33
- year2: years?.max && !year ? years.max : undefined,
34
- audio: isAudioSample ? 1 : undefined,
35
- offers: isMakeAnOfferOnly ? 1 : undefined,
36
- ships_from: from?.length ? from : undefined,
37
- limit,
38
- page,
39
- sort,
40
- }),
41
- ].join('?');
42
- /** Init browser */
43
- const browser = await playwright_chromium_1.chromium.launch({
44
- args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gl-drawing-for-tests'],
45
- });
46
- /** Init context */
47
- const browserContext = await browser.newContext({
48
- userAgent: new user_agents_1.default({ platform: 'Win32' }).toString(),
49
- extraHTTPHeaders: {
50
- 'X-PJAX': 'true',
51
- },
52
- javaScriptEnabled: false,
53
- });
54
- /** Init page */
55
- const browserPage = await browserContext.newPage();
56
- /** Block useless resources */
57
- await browserPage.route('**/*', route => [
58
- 'stylesheet',
59
- 'image',
60
- 'media',
61
- 'font',
62
- 'script',
63
- 'texttrack',
64
- 'xhr',
65
- 'fetch',
66
- 'eventsource',
67
- 'websocket',
68
- 'manifest',
69
- 'other',
70
- ].includes(route.request().resourceType())
71
- ? route.abort()
72
- : route.continue());
73
- /** Init page */
74
- const response = await browserPage.goto(url, { waitUntil: 'domcontentloaded' });
75
- /** Status code from the page */
76
- const status = response?.status() ?? 500;
77
- // See current issue: https://github.com/evanw/esbuild/issues/2605
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
79
- await browserPage.evaluate(() => (window.__name ??= (func) => func));
80
- /** If error, reject */
81
- if (status >= 400) {
82
- // eslint-disable-next-line @typescript-eslint/only-throw-error
83
- throw {
84
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
85
- message: (await browserPage.evaluate(() => document.querySelector('h1 + p')?.innerHTML.trim())) || 'An error occurred',
86
- code: status,
87
- };
88
- }
89
- /** Url generated by browser */
90
- const urlGenerated = browserPage.url();
91
- /**
92
- * Result from scraping.
93
- * Scraping inside Playwright is faster (x2) compare to exporting HTML outside and parsing it with another library.
94
- */
95
- // eslint-disable-next-line @typescript-eslint/unbound-method
96
- const result = await browserPage.evaluate(this.getResult, {
97
- input: {
98
- page,
99
- limit,
100
- searchValue,
101
- searchType,
102
- },
103
- urlGenerated,
104
- CURRENCIES: data_1.CURRENCIES,
105
- COUNTRIES: data_1.COUNTRIES,
106
- });
107
- /** Close context/browser */
108
- await browserContext.close();
109
- await browser.close();
110
- return result;
111
- }
112
- catch (error) {
113
- if (error.message && error.code) {
114
- // Rethrow error
115
- throw error;
116
- }
117
- // eslint-disable-next-line @typescript-eslint/only-throw-error
118
- throw {
119
- message: error.message || 'An error occurred',
120
- code: 500,
121
- };
122
- }
123
- }
124
- /**
125
- * Generate URL to be parsed
126
- * @returns Url
127
- */
128
- static generateUrl({ searchType, seller, lang, }) {
129
- let url = `https://www.discogs.com/${lang}/`;
130
- if (seller) {
131
- url += `seller/${seller}/`;
132
- url += searchType === 'user' ? 'mywants' : 'profile';
133
- }
134
- else {
135
- url += 'sell/';
136
- url += searchType === 'user' ? 'mywants' : 'list';
137
- }
138
- return url;
139
- }
140
- /**
141
- * Serialize params URL
142
- * @param params Object of GET parameters
143
- * @returns Url
144
- */
145
- static serializeParams(params) {
146
- const param = [];
147
- // eslint-disable-next-line no-restricted-syntax
148
- for (const key in params) {
149
- if (params[key] === undefined || params[key] === null) {
150
- continue;
151
- }
152
- else if (Array.isArray(params[key])) {
153
- /** Custom handle for array */
154
- if (params[key].length > 0) {
155
- // eslint-disable-next-line no-restricted-syntax
156
- for (const el of params[key]) {
157
- param.push(`${key}=${encodeURIComponent(el)}`);
158
- }
159
- }
160
- else {
161
- continue;
162
- }
163
- }
164
- else {
165
- param.push(`${key}=${encodeURIComponent(params[key])}`);
166
- }
167
- }
168
- return param.join('&');
169
- }
170
- /**
171
- * Parse HTML to clean result
172
- * @returns Items found
173
- */
174
- static getResult({ input: { page, limit, searchValue, searchType }, urlGenerated, CURRENCIES, COUNTRIES, }) {
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
- if (!value) {
182
- return value;
183
- }
184
- const currencyFound = Object.keys(CURRENCIES).find(key => value.includes(key)) ?? '';
185
- if (!currencyFound) {
186
- return value;
187
- }
188
- const currencyClean = CURRENCIES[currencyFound];
189
- const amount = value
190
- .replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dot but last, except if JPY
191
- .replace(currencyFound, '') // Remove original currency
192
- .replace(/\s/g, ''); // Remove spaces
193
- return `${amount} ${currencyClean}`.replace(/\s\s+/g, ' '); // Remove useless spaces
194
- };
195
- const totalItems = parseFloat(document
196
- .querySelector('.pagination_total')
197
- ?.textContent?.split(' ')
198
- .filter(x => x)
199
- .pop()
200
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
201
- ?.replace(/(,|\.|\s)/g, '') || '0');
202
- return {
203
- items: [...document.querySelectorAll('table.table_block tbody tr')].map(el => {
204
- const shipping = convertCurrency(el
205
- .querySelector('.item_shipping')
206
- ?.childNodes[0]?.textContent?.replace(/(\s+|\+)/g, ' ')
207
- .trim()
208
- .replace(',', '.') ?? '');
209
- const have = Number.parseInt(el.querySelector('.community_summary .community_result:nth-child(1) .community_number')?.textContent ?? '', 10);
210
- const want = Number.parseInt(el.querySelector('.community_summary .community_result:nth-child(2) .community_number')?.textContent ?? '', 10);
211
- const countryName = el.querySelector('.seller_info li:nth-child(3)')?.textContent?.split(':').pop() ?? '';
212
- const countryCode = COUNTRIES[countryName];
213
- const releaseId = Number.parseInt(el
214
- .querySelector('a.item_release_link')
215
- ?.getAttribute('href')
216
- ?.split('release/')
217
- .pop()
218
- ?.split('-')
219
- .shift() ?? '0', 10);
220
- const itemId = Number.parseInt(el.querySelector('a.item_description_title')?.getAttribute('href')?.split('/').pop() ?? '0', 10);
221
- const notes = Number.parseInt(el
222
- .querySelector('.seller_info li:nth-child(2) .section_link')
223
- ?.textContent?.replace(/\s+/g, ' ')
224
- .trim()
225
- .split(' ')[0]
226
- ?.replace(/,/g, '') ?? '', 10);
227
- const originalTitle = el.querySelector('a.item_description_title')?.textContent;
228
- const firstIndexOfDash = originalTitle?.indexOf(' - ') ?? -1;
229
- const lastIndexOfParenthesis = originalTitle?.lastIndexOf(' (') ?? -1;
230
- return {
231
- id: Number.isNaN(itemId) ? 0 : itemId,
232
- title: {
233
- original: originalTitle ?? '',
234
- artist: originalTitle?.substring(0, firstIndexOfDash) ?? '',
235
- item: firstIndexOfDash > -1 && lastIndexOfParenthesis > -1
236
- ? (originalTitle?.substring(firstIndexOfDash + 3, lastIndexOfParenthesis) ?? '')
237
- : '',
238
- formats: lastIndexOfParenthesis > -1
239
- ? (originalTitle?.substring(lastIndexOfParenthesis + 2, originalTitle.length - 1).split(', ') ?? [])
240
- : [],
241
- },
242
- url: `https://www.discogs.com${el.querySelector('a.item_description_title')?.getAttribute('href') ?? ''}`,
243
- labels: [...el.querySelectorAll(".label_and_cat a[href^='https://www.discogs.com/']")]
244
- .map(x => x.textContent ?? '')
245
- .filter((value, index, self) => self.indexOf(value) === index),
246
- catnos: el
247
- // cspell: disable-next-line
248
- .querySelector('.label_and_cat .item_catno')
249
- ?.textContent?.replace(/\s+/g, ' ')
250
- .split(', ')
251
- .filter(x => x !== 'none') ?? [],
252
- imageUrl: el.querySelector('.marketplace_image')?.getAttribute('data-src') ?? '',
253
- description: el.querySelector('.item_condition')?.nextElementSibling?.textContent?.replace(/\s+/g, ' ').trim() ?? '',
254
- isAcceptingOffer: (el.querySelector('.item_add_to_cart p a strong')?.textContent?.split('/').length ?? 0) > 1,
255
- isAvailable: !el.classList.contains('unavailable'),
256
- condition: {
257
- media: {
258
- full: el.querySelector('.item_condition span:nth-child(3)')?.textContent?.replace(/\s+/g, ' ').trim() ?? '',
259
- short: el
260
- .querySelector('.item_condition span:nth-child(3)')
261
- ?.textContent?.replace(/\s+/g, ' ')
262
- .trim()
263
- .match(/\(([^)]+)\)/)?.[1] ?? '',
264
- },
265
- sleeve: {
266
- full: el.querySelector('.item_condition span.item_sleeve_condition')?.textContent ?? '',
267
- short: el.querySelector('.item_condition span.item_sleeve_condition')?.textContent?.match(/\(([^)]+)\)/)?.[1] ??
268
- '',
269
- },
270
- },
271
- seller: {
272
- name: el.querySelector('.seller_info a')?.textContent ?? '',
273
- url: `https://www.discogs.com${el.querySelector('.seller_info a')?.getAttribute('href') ?? ''}`,
274
- score: el.querySelector('.seller_info li:nth-child(2) strong')?.textContent ?? '',
275
- notes: Number.isNaN(notes) ? 0 : notes,
276
- },
277
- price: {
278
- base: convertCurrency(el.querySelector('.price')?.textContent?.replace(/\s+/g, ' ').replace(/,/, '.') ?? ''),
279
- shipping: Number.isNaN(parseFloat(shipping)) ? '' : shipping,
280
- },
281
- country: {
282
- name: countryName,
283
- code: countryCode,
284
- },
285
- community: {
286
- have: Number.isNaN(have) ? 0 : have,
287
- want: Number.isNaN(want) ? 0 : want,
288
- },
289
- release: {
290
- id: Number.isNaN(releaseId) ? 0 : releaseId,
291
- url: `https://www.discogs.com${el.querySelector('a.item_release_link')?.getAttribute('href') ?? ''}`,
292
- },
293
- };
294
- }),
295
- page: {
296
- current: page,
297
- total: Math.ceil(totalItems / limit),
298
- },
299
- result: {
300
- total: totalItems,
301
- perPage: limit,
302
- },
303
- search: {
304
- value: searchValue ?? '',
305
- type: searchType,
306
- },
307
- urlGenerated,
308
- };
309
- }
310
- }
311
- exports.default = Marketplace;
@@ -1,12 +0,0 @@
1
- import type { LimitType } from '../types/limit.type';
2
- import type { GenreType } from '../types/genre.type';
3
- import type { CurrencyType } from '../types/currency.type';
4
- import type { FromType } from '../types/from.type';
5
- import type { StyleType } from '../types/style.type';
6
- import type { FormatType } from '../types/format.type';
7
- import type { ConditionType } from '../types/condition.type';
8
- import type { SortType } from '../types/sort.type';
9
- import type { LangType } from '../types/lang.type';
10
- import type { FormatDescriptionType } from '../types/format-description.type';
11
- import type { SearchTypeType } from '../types/search-type.type';
12
- export type { LimitType, GenreType, CurrencyType, FromType, StyleType, FormatType, ConditionType, SortType, LangType, FormatDescriptionType, SearchTypeType, };
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });