discogs-marketplace-api-nodejs 1.12.0 → 1.13.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
@@ -107,20 +107,7 @@ const result = await DiscogsMarketplace.search({
107
107
 
108
108
  ## 💁 Additional Features
109
109
 
110
- ### 1. Reuse a Playwright `Page` instance for faster scraping
111
-
112
- ```ts
113
- const browser = await playwright.launch()
114
- const browserContext = await browser.newContext()
115
- const browserPage = await browserContext.newPage()
116
-
117
- const result = await DiscogsMarketplace.search({ searchType: 'q'}, browserPage)
118
-
119
- await browserContext.close()
120
- await browser.close()
121
- ```
122
-
123
- ### 2. Extract correct parameters from URL
110
+ ### 1. Extract correct parameters from URL
124
111
 
125
112
  ```ts
126
113
  const searchParams = DiscogsMarketplace.getSearchParamsFromUrl('https://www.discogs.com/fr/sell/list?sort=listed,desc&limit=250&artist_id=244819&page=2&genre=Rock')
@@ -217,11 +204,6 @@ interface SearchParams {
217
204
  * Seller's username filter.
218
205
  */
219
206
  seller?: string
220
- /**
221
- * Hours range for wantlist searches.
222
- * @example '0-24'
223
- */
224
- hoursRange?: HoursRange
225
207
  /**
226
208
  * Sort order for the results.
227
209
  * @default 'listed,desc'
@@ -260,6 +242,7 @@ interface SearchResult {
260
242
  formats: Array<string>
261
243
  }
262
244
  url: string
245
+ listedAt: Date | null
263
246
  labels: Array<string>
264
247
  catnos: Array<string>
265
248
  imageUrl: string
@@ -324,7 +307,6 @@ interface SearchResult {
324
307
 
325
308
  ## 👉 Known Issues
326
309
 
327
- - Ensure all Playwright requirements are installed (see [Install system dependencies](https://playwright.dev/docs/browsers#install-system-dependencies)).
328
310
  - Requests hitting page >400 will result in a 404.
329
311
  - Some search parameters might not be compatible with every type of queries.
330
312
  - For other edge cases, feel free to open an [issue on GitHub](https://github.com/KirianCaumes/Discogs-Marketplace-API-NodeJS/issues).
@@ -37,16 +37,13 @@ function getSearchParamsFromUrl(url) {
37
37
  }
38
38
  }
39
39
  // Retrieve basic search values
40
- for (const key of ['currency', 'genre', 'ships_from', 'seller', 'sort', 'hours_range']) {
40
+ for (const key of ['currency', 'genre', 'ships_from', 'seller', 'sort']) {
41
41
  const value = urlSearchParams.get(key);
42
42
  if (value) {
43
43
  switch (key) {
44
44
  case 'ships_from':
45
45
  searchParams.from = value;
46
46
  break;
47
- case 'hours_range':
48
- searchParams.hoursRange = value;
49
- break;
50
47
  default:
51
48
  searchParams[key] = value;
52
49
  break;
@@ -0,0 +1,33 @@
1
+ export default interface ShopDetailsResultApi {
2
+ /** Data */
3
+ data?: {
4
+ /** Releases */
5
+ releases?: Array<{
6
+ /** InWantlistCount */
7
+ inWantlistCount?: number;
8
+ /** InCollectionCount */
9
+ inCollectionCount?: number;
10
+ /** Images */
11
+ images?: {
12
+ /** Edges */
13
+ edges?: Array<{
14
+ /** Node */
15
+ node?: {
16
+ /** Thumbnail */
17
+ thumbnail?: {
18
+ /** WebpUrl */
19
+ webpUrl?: string;
20
+ };
21
+ };
22
+ }>;
23
+ };
24
+ /** Ratings */
25
+ ratings?: {
26
+ /** AverageRating */
27
+ averageRating?: number;
28
+ };
29
+ /** DiscogsId */
30
+ discogsId?: number;
31
+ }>;
32
+ };
33
+ }
@@ -0,0 +1,111 @@
1
+ export default interface ShopResultApi {
2
+ /** Items */
3
+ items?: Array<{
4
+ /** ItemId */
5
+ itemId?: number;
6
+ /** AllowsOffers */
7
+ allowsOffers?: boolean;
8
+ /** Comments */
9
+ comments?: string;
10
+ /** ImageUrl */
11
+ imageUrl?: string;
12
+ /** InCart */
13
+ inCart?: boolean;
14
+ /** ListedDate */
15
+ listedDate?: string;
16
+ /** MediaCondition */
17
+ mediaCondition?: string;
18
+ /** PreviousPrice */
19
+ previousPrice?: string;
20
+ /** Price */
21
+ price?: {
22
+ /** Amount */
23
+ amount?: number;
24
+ /** AmountUsd */
25
+ amountUsd?: number;
26
+ /** CurrencyCode */
27
+ currencyCode?: string;
28
+ /** BuyerItemPrice */
29
+ buyerItemPrice?: string;
30
+ /** BuyerCurrencyCode */
31
+ buyerCurrencyCode?: string;
32
+ };
33
+ /** Release */
34
+ release?: {
35
+ /** ReleaseId */
36
+ releaseId?: number;
37
+ /** Artists */
38
+ artists?: Array<{
39
+ /** ArtistId */
40
+ artistId?: number;
41
+ /** Name */
42
+ name?: string;
43
+ }>;
44
+ /** Country */
45
+ country?: string;
46
+ /** FormatNames */
47
+ formatNames?: Array<string>;
48
+ /** Genres */
49
+ genres?: Array<{
50
+ /** GenreId */
51
+ genreId?: number;
52
+ /** Name */
53
+ name?: string;
54
+ }>;
55
+ /** Labels */
56
+ labels?: Array<{
57
+ /** LabelId */
58
+ labelId?: number;
59
+ /** Name */
60
+ name?: string;
61
+ }>;
62
+ /** MajorFormat */
63
+ majorFormat?: string;
64
+ /** Rating */
65
+ rating?: number;
66
+ /** Title */
67
+ title?: string;
68
+ /** Year */
69
+ year?: number;
70
+ };
71
+ /** Seller */
72
+ seller?: {
73
+ /** Uid */
74
+ uid?: number;
75
+ /** Name */
76
+ name?: string;
77
+ /** Rating */
78
+ rating?: number;
79
+ /** RatingCount */
80
+ ratingCount?: number;
81
+ /** ShipsFrom */
82
+ shipsFrom?: string;
83
+ /** MinBuyerRating */
84
+ minBuyerRating?: number;
85
+ /** IndependentSeller */
86
+ independentSeller?: boolean;
87
+ };
88
+ /** Shipping */
89
+ shipping?: {
90
+ /** ShippingPrice */
91
+ shippingPrice?: number;
92
+ /** BuyerShippingPrice */
93
+ buyerShippingPrice?: number;
94
+ /** FreeShippingMin */
95
+ freeShippingMin?: number;
96
+ };
97
+ /** SleeveCondition */
98
+ sleeveCondition?: string;
99
+ }>;
100
+ /** TotalCount */
101
+ totalCount?: number;
102
+ /** CompleteLookup */
103
+ completeLookup?: {
104
+ /** Artists */
105
+ artists?: string;
106
+ /** Sellers */
107
+ sellers?: string;
108
+ /** Releases */
109
+ releases?: Record<string, string>;
110
+ };
111
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -4,7 +4,6 @@ import type { FormatDescription } from '../types/format-description.type.js';
4
4
  import type { Format } from '../types/format.type.js';
5
5
  import type { From } from '../types/from.type.js';
6
6
  import type { Genre } from '../types/genre.type.js';
7
- import type { HoursRange } from '../types/hours-range.type.js';
8
7
  import type { Lang } from '../types/lang.type.js';
9
8
  import type { Limit } from '../types/limit.type.js';
10
9
  import type { Search } from '../types/search-type.type.js';
@@ -90,11 +89,6 @@ export default interface SearchParams {
90
89
  * Seller's username filter.
91
90
  */
92
91
  seller?: string;
93
- /**
94
- * Hours range for wantlist searches.
95
- * @example '0-24'
96
- */
97
- hoursRange?: HoursRange;
98
92
  /**
99
93
  * Sort order for the results.
100
94
  * @default 'listed,desc'
@@ -118,3 +112,11 @@ export default interface SearchParams {
118
112
  */
119
113
  lang?: Lang;
120
114
  }
115
+ export type SearchParamsDefaulted = SearchParams & {
116
+ searchType: NonNullable<SearchParams['searchType']>;
117
+ isMakeAnOfferOnly: NonNullable<SearchParams['isMakeAnOfferOnly']>;
118
+ sort: NonNullable<SearchParams['sort']>;
119
+ limit: NonNullable<SearchParams['limit']>;
120
+ page: NonNullable<SearchParams['page']>;
121
+ lang: NonNullable<SearchParams['lang']>;
122
+ };
@@ -21,6 +21,8 @@ export default interface SearchResult {
21
21
  };
22
22
  /** URL to the listing on Discogs */
23
23
  url: string;
24
+ /** Date the item was listed */
25
+ listedAt: Date | null;
24
26
  /** Array of label names */
25
27
  labels: Array<string>;
26
28
  /** Array of catalog numbers */
@@ -0,0 +1,11 @@
1
+ import type SearchResult from '../interfaces/search-result.interface.js';
2
+ import type { SearchParamsDefaulted } from '../interfaces/search-params.interface.js';
3
+ /**
4
+ * Parses the page and returns the items found.
5
+ * @param url Url to scrape
6
+ * @returns Items found and total
7
+ */
8
+ export default function scrapeLegacy({ searchType, searchValue, currency, genre, style, format, formatDescription, condition, year, years, isMakeAnOfferOnly, from, seller, sort, limit, page, lang, }: SearchParamsDefaulted): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
9
+ /** Total items found */
10
+ total: SearchResult['result']['total'];
11
+ }>;
@@ -1,47 +1,121 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = scrape;
4
- // These variables are injected by the browser context when the page is loaded.
5
- const { Country, Currency } = globalThis;
6
+ exports.default = scrapeLegacy;
7
+ const linkedom_1 = require("linkedom");
8
+ const currency_data_1 = __importDefault(require("../data/currency.data.js"));
9
+ const country_data_1 = __importDefault(require("../data/country.data.js"));
6
10
  /**
7
- * Parses the page and returns the items found.
8
- * This function is called by the browser context when the page is loaded.
9
- * @returns Items found and total
11
+ * Generate URL to be parsed
12
+ * @returns Url
10
13
  */
11
- function scrape() {
12
- /**
13
- * Converts a currency string to a standardized format.
14
- * @param value String to clean
15
- * @returns Cleaned-up string
16
- */
17
- const convertCurrency = (value) => {
18
- if (!value) {
19
- return '';
20
- }
21
- const currencyFound = Object.keys(Currency).find(key => value.includes(key));
22
- if (!currencyFound) {
23
- return '';
14
+ function generateUrl({ searchType, seller, lang, }) {
15
+ const baseUrl = `https://www.discogs.com/${lang}`;
16
+ if (seller) {
17
+ const path = searchType === 'user' ? 'mywants' : 'profile';
18
+ return `${baseUrl}/seller/${seller}/${path}`;
19
+ }
20
+ else {
21
+ const path = searchType === 'user' ? 'mywants' : 'list';
22
+ return `${baseUrl}/sell/${path}`;
23
+ }
24
+ }
25
+ /**
26
+ * Serialize params URL
27
+ * @param params Object of GET parameters
28
+ * @returns Url
29
+ */
30
+ function serializeParams(params) {
31
+ return Object.entries(params)
32
+ .flatMap(([key, value]) => {
33
+ if (value === undefined || value === null) {
34
+ return [];
24
35
  }
25
- const currencyClean = Currency[currencyFound];
26
- const amount = value
27
- .replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dots but the last, except for JPY
28
- .replace(currencyFound, '') // Remove original currency
29
- .replace(/\s\s+/g, ''); // Remove spaces
30
- const amountParsed = Number.parseFloat(amount);
31
- if (Number.isNaN(amountParsed)) {
32
- return '';
36
+ if (Array.isArray(value)) {
37
+ return value.map(v => `${key}=${encodeURIComponent(v)}`);
33
38
  }
34
- return `${amountParsed} ${currencyClean}`;
35
- };
36
- /**
37
- * Safely parses a number from a string.
38
- * @param value String to parse
39
- * @returns Parsed number or 0 if invalid
40
- */
41
- const safeParseInt = (value) => {
42
- const parsed = Number.parseInt(value ?? '', 10);
43
- return Number.isNaN(parsed) ? 0 : parsed;
44
- };
39
+ return [`${key}=${encodeURIComponent(value)}`];
40
+ })
41
+ .join('&');
42
+ }
43
+ /**
44
+ * Converts a currency string to a standardized format.
45
+ * @param value String to clean
46
+ * @returns Cleaned-up string
47
+ */
48
+ function convertCurrency(value) {
49
+ if (!value) {
50
+ return '';
51
+ }
52
+ const currencyFound = Object.keys(currency_data_1.default).find(key => value.includes(key));
53
+ if (!currencyFound) {
54
+ return '';
55
+ }
56
+ const currencyClean = currency_data_1.default[currencyFound];
57
+ const amount = value
58
+ .replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dots but the last, except for JPY
59
+ .replace(currencyFound, '') // Remove original currency
60
+ .replace(/\s\s+/g, ''); // Remove spaces
61
+ const amountParsed = Number.parseFloat(amount);
62
+ if (Number.isNaN(amountParsed)) {
63
+ return '';
64
+ }
65
+ return `${amountParsed} ${currencyClean}`;
66
+ }
67
+ /**
68
+ * Safely parses a number from a string.
69
+ * @param value String to parse
70
+ * @returns Parsed number or 0 if invalid
71
+ */
72
+ function safeParseInt(value) {
73
+ const parsed = Number.parseInt(value ?? '', 10);
74
+ return Number.isNaN(parsed) ? 0 : parsed;
75
+ }
76
+ /**
77
+ * Parses the page and returns the items found.
78
+ * @param url Url to scrape
79
+ * @returns Items found and total
80
+ */
81
+ async function scrapeLegacy({ searchType, searchValue, currency, genre, style, format, formatDescription, condition, year, years, isMakeAnOfferOnly, from, seller, sort, limit, page, lang, }) {
82
+ /** Url to be called by the browser */
83
+ const urlGenerated = [
84
+ generateUrl({ searchType, seller, lang }),
85
+ serializeParams({
86
+ [searchType]: searchValue,
87
+ currency,
88
+ genre,
89
+ style: style?.length ? style : null,
90
+ format: format?.length ? format : null,
91
+ format_desc: formatDescription?.length ? formatDescription : null,
92
+ condition: condition?.length ? condition : null,
93
+ year: year && !years ? year : null,
94
+ year1: years?.min && !year ? years.min : null,
95
+ year2: years?.max && !year ? years.max : null,
96
+ offers: isMakeAnOfferOnly ? 1 : null,
97
+ ships_from: from,
98
+ limit,
99
+ page,
100
+ sort,
101
+ }),
102
+ ].join('?');
103
+ const response = await globalThis.fetch(urlGenerated, {
104
+ headers: {
105
+ 'User-Agent': 'Discogs',
106
+ 'Content-Type': 'application/json',
107
+ 'X-PJAX': 'true',
108
+ },
109
+ referrer: 'https://discogs.com',
110
+ });
111
+ const content = await response.text();
112
+ const { document } = (0, linkedom_1.parseHTML)(content);
113
+ // If error status, reject
114
+ if (response.status >= 400) {
115
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
116
+ const errorMessage = document.querySelector('h1 + p')?.innerHTML.trim() || `An error ${response.status} occurred.`;
117
+ throw new Error(errorMessage);
118
+ }
45
119
  /**
46
120
  * Extracts and cleans text content from an element.
47
121
  * @param selector CSS selector
@@ -76,6 +150,7 @@ function scrape() {
76
150
  : [],
77
151
  },
78
152
  url: `https://www.discogs.com${itemHref}`,
153
+ listedAt: null,
79
154
  labels: [...el.querySelectorAll(".label_and_cat a[href^='https://www.discogs.com/']")]
80
155
  .map(x => x.textContent?.trim() ?? '')
81
156
  .filter((value, index, self) => self.indexOf(value) === index),
@@ -110,7 +185,7 @@ function scrape() {
110
185
  },
111
186
  country: {
112
187
  name: countryName,
113
- code: Country[countryName],
188
+ code: country_data_1.default[countryName],
114
189
  },
115
190
  community: {
116
191
  have: safeParseInt(getTextContent('.community_summary .community_result:nth-child(1) .community_number', el)),
@@ -122,5 +197,5 @@ function scrape() {
122
197
  },
123
198
  };
124
199
  });
125
- return { total, items };
200
+ return { total, items, urlGenerated };
126
201
  }
@@ -0,0 +1,14 @@
1
+ import type SearchResult from '../interfaces/search-result.interface.js';
2
+ import type { SearchParamsDefaulted } from '../interfaces/search-params.interface.js';
3
+ /**
4
+ * Parses the page and returns the items found.
5
+ * @param SearchParams Search parameters
6
+ * @returns Items found and total
7
+ */
8
+ export default function scrape({ currency, genre, format, formatDescription, condition, years, isMakeAnOfferOnly, from, sort, limit, page, releases, }: SearchParamsDefaulted & {
9
+ /** Releases */
10
+ releases?: Array<number>;
11
+ }): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
12
+ /** Total items found */
13
+ total: SearchResult['result']['total'];
14
+ }>;
@@ -0,0 +1,151 @@
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
+ exports.default = scrape;
7
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
8
+ const country_data_1 = __importDefault(require("../data/country.data.js"));
9
+ /**
10
+ * Parses the page and returns the items found.
11
+ * @param SearchParams Search parameters
12
+ * @returns Items found and total
13
+ */
14
+ async function scrape({ currency, genre, format, formatDescription, condition, years, isMakeAnOfferOnly, from,
15
+ // Seller,
16
+ sort, limit, page, releases, }) {
17
+ const urlGenerated = [
18
+ 'https://www.discogs.com/api/shop-page-api/sell_item',
19
+ new URLSearchParams([
20
+ ['sellerRatingMin', '0'],
21
+ ['includeGenericSleeves', 'true'],
22
+ ['includeSleevelessMedia', 'true'],
23
+ ['showUnavailable', 'true'],
24
+ ['sellerRatingCountMin', '0'],
25
+ [
26
+ 'sort',
27
+ {
28
+ listed: 'listedDate',
29
+ condition: 'mediaCondition',
30
+ artist: 'artist',
31
+ title: 'title',
32
+ seller: 'seller',
33
+ price: 'price',
34
+ }[sort.split(',').at(0)] ?? 'listedDate',
35
+ ],
36
+ [
37
+ 'sortOrder',
38
+ {
39
+ asc: 'ascending',
40
+ desc: 'descending',
41
+ }[sort.split(',').at(-1)] ?? 'ascending',
42
+ ],
43
+ ['count', limit.toString()],
44
+ ['offset', ((page - 1) * limit).toString()],
45
+ ...(releases?.map(r => ['release', r.toString()]) ?? []),
46
+ ['shipsFrom', Object.keys(country_data_1.default).find(key => country_data_1.default[key] === from)],
47
+ ...(format?.map(f => ['formatName', f]) ?? []),
48
+ ...(formatDescription?.map(fd => ['formatDescription', fd]) ?? []),
49
+ ...(condition?.map(fd => ['sleeveCondition', fd]) ?? []),
50
+ ...(condition?.map(fd => ['mediaCondition', fd]) ?? []),
51
+ ['allowsOffers', isMakeAnOfferOnly ? 'true' : ''],
52
+ ['currency', currency ?? ''],
53
+ ['genre', genre ?? ''],
54
+ ['yearRangeLow', years?.min.toString() ?? ''],
55
+ ['yearRangeHigh', years?.max.toString() ?? ''],
56
+ ].filter(([, p]) => !!p)).toString(),
57
+ ].join('?');
58
+ const result = (await (await globalThis.fetch(urlGenerated, {
59
+ method: 'GET',
60
+ headers: {
61
+ 'User-Agent': 'Discogs',
62
+ 'Content-Type': 'application/json',
63
+ },
64
+ referrer: 'https://discogs.com',
65
+ })).json());
66
+ const detailsResult = (await (await globalThis.fetch('https://www.discogs.com/graphql', {
67
+ method: 'POST',
68
+ headers: {
69
+ 'User-Agent': 'Discogs',
70
+ 'Content-Type': 'application/json',
71
+ },
72
+ referrer: 'https://discogs.com',
73
+ body: JSON.stringify({
74
+ // eslint-disable-next-line max-len
75
+ query: 'query Releases($discogsIds: [Int], $first: Int) {\n releases(discogsIds: $discogsIds) {\n inWantlistCount\n inCollectionCount\n images(first: $first) {\n edges {\n node {\n thumbnail {\n webpUrl\n }\n }\n }\n }\n ratings(first: 1) {\n averageRating\n }\n discogsId\n }\n}',
76
+ variables: {
77
+ discogsIds: result.items?.map(z => z.release?.releaseId ?? 0).filter((x, i, self) => x && self.indexOf(x) === i),
78
+ first: 1,
79
+ },
80
+ extensions: {
81
+ persistedQuery: {
82
+ version: 1,
83
+ sha256Hash: 'ee9d48441023ebd1e6ca169e550581b45de216e88b40711acb6617e49e1bb0cb',
84
+ },
85
+ },
86
+ }),
87
+ })).json());
88
+ const details = Object.fromEntries(detailsResult.data?.releases?.map(release => [
89
+ release.discogsId ?? 0,
90
+ {
91
+ imageUrl: release.images?.edges?.[0]?.node?.thumbnail?.webpUrl ?? null,
92
+ want: release.inWantlistCount ?? 0,
93
+ have: release.inCollectionCount ?? 0,
94
+ },
95
+ ]) ?? []);
96
+ const items = (result.items?.map(item => {
97
+ const detail = details[item.release?.releaseId ?? 0];
98
+ return {
99
+ id: item.itemId,
100
+ title: {
101
+ // eslint-disable-next-line max-len
102
+ original: `${item.release?.artists?.map(x => x.name ?? '').join(', ') ?? ''} - ${item.release?.title ?? ''} (${item.release?.majorFormat ?? ''})`,
103
+ artist: item.release?.artists?.map(x => x.name ?? '').join(', ') ?? '',
104
+ item: item.release?.title ?? '',
105
+ formats: item.release?.formatNames ?? [],
106
+ },
107
+ url: `https://www.discogs.com/sell/item/${item.itemId}`,
108
+ listedAt: new Date(item.listedDate ?? ''),
109
+ labels: item.release?.labels?.map(x => x.name ?? '').filter((value, index, self) => self.indexOf(value) === index) ?? [],
110
+ catnos: [],
111
+ imageUrl: detail?.imageUrl ?? '',
112
+ description: item.comments ?? '',
113
+ isAcceptingOffer: item.allowsOffers ?? false,
114
+ isAvailable: true,
115
+ condition: {
116
+ media: {
117
+ full: item.mediaCondition ?? '',
118
+ short: /\(([^)]+)\)/.exec(item.mediaCondition ?? '')?.[1] ?? '',
119
+ },
120
+ sleeve: {
121
+ full: item.sleeveCondition ?? '',
122
+ short: /\(([^)]+)\)/.exec(item.sleeveCondition ?? '')?.[1] ?? '',
123
+ },
124
+ },
125
+ seller: {
126
+ name: item.seller?.name ?? '',
127
+ url: `https://www.discogs.com/seller/${item.seller?.name ?? ''}/profile`,
128
+ score: item.seller?.rating?.toString() ?? '0',
129
+ notes: item.seller?.ratingCount ?? 0,
130
+ },
131
+ price: {
132
+ base: `${item.price?.amount ?? 0} ${(item.price?.currencyCode ?? '')}`,
133
+ shipping: item.shipping ? `${item.shipping.shippingPrice ?? 0} ${(item.price?.currencyCode ?? '')}` : '',
134
+ },
135
+ country: {
136
+ name: item.seller?.shipsFrom ?? '',
137
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
138
+ code: country_data_1.default[item.seller?.shipsFrom] ?? '',
139
+ },
140
+ community: {
141
+ have: detail?.have ?? 0,
142
+ want: detail?.want ?? 0,
143
+ },
144
+ release: {
145
+ id: item.release?.releaseId ?? 0,
146
+ url: `https://www.discogs.com/release/${item.release?.releaseId ?? ''}`,
147
+ },
148
+ };
149
+ }) ?? []);
150
+ return { total: result.totalCount ?? 0, items, urlGenerated };
151
+ }
@@ -0,0 +1,11 @@
1
+ import type SearchResult from '../interfaces/search-result.interface.js';
2
+ import type { SearchParamsDefaulted } from '../interfaces/search-params.interface.js';
3
+ /**
4
+ * Parses the page and returns the items found.
5
+ * @param searchParams Search parameters
6
+ * @returns Items found and total
7
+ */
8
+ export default function scrapeWantlist(searchParams: SearchParamsDefaulted): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
9
+ /** Total items found */
10
+ total: SearchResult['result']['total'];
11
+ }>;
@@ -0,0 +1,57 @@
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
+ exports.default = scrapeWantlist;
7
+ const linkedom_1 = require("linkedom");
8
+ const modern_scraper_1 = __importDefault(require("../scrapers/modern.scraper.js"));
9
+ const PER_PAGE = 250;
10
+ /**
11
+ * Parses the page and returns the items found.
12
+ * @param searchParams Search parameters
13
+ * @returns Items found and total
14
+ */
15
+ async function scrapeWantlist(searchParams) {
16
+ const { searchValue } = searchParams;
17
+ if (!searchValue) {
18
+ return { items: [], urlGenerated: '', total: 0 };
19
+ }
20
+ /** Fetch the first page of user wantlist */
21
+ const firstPage = await (await globalThis.fetch(`https://www.discogs.com/wantlist?${new URLSearchParams({
22
+ page: '1',
23
+ limit: PER_PAGE.toString(),
24
+ user: searchValue.toString(),
25
+ layout: 'sm',
26
+ }).toString()}`, {
27
+ headers: { 'User-Agent': 'Discogs', 'Content-Type': 'application/json' },
28
+ referrer: 'https://discogs.com',
29
+ })).text();
30
+ const { document: firstPageDocument } = (0, linkedom_1.parseHTML)(firstPage);
31
+ /** Total number of items in the wantlist */
32
+ const total = +(firstPageDocument.querySelector('.pagination_total')?.textContent?.split(' of ').pop()?.replace(',', '') ?? '0');
33
+ const wants = await Promise.all(new Array(Math.ceil(total / PER_PAGE)).fill({}).map(async (_, i) => {
34
+ const page = i + 1;
35
+ const result = page === 1
36
+ ? firstPage
37
+ : (await globalThis.fetch(`https://www.discogs.com/wantlist?${new URLSearchParams({
38
+ page: page.toString(),
39
+ limit: PER_PAGE.toString(),
40
+ user: searchValue.toString(),
41
+ layout: 'sm',
42
+ }).toString()}`, {
43
+ headers: { 'User-Agent': 'Discogs', 'Content-Type': 'application/json' },
44
+ referrer: 'https://discogs.com',
45
+ })).text();
46
+ const { document } = (0, linkedom_1.parseHTML)(result);
47
+ /** Extract the links to the items in the wantlist, if there's no link it's not for sale */
48
+ const links = [...document.querySelectorAll('.marketplace_for_sale_count a')];
49
+ return links.map(x => +(new URL(`https://discogs.com${x.href}`).pathname.split('/').pop() ?? '0'));
50
+ }));
51
+ const wantlistIds = wants.flat();
52
+ // If there's nothing for sale
53
+ if (wantlistIds.length === 0) {
54
+ return { items: [], total: 0, urlGenerated: '' };
55
+ }
56
+ return (0, modern_scraper_1.default)({ ...searchParams, releases: wantlistIds });
57
+ }
package/dist/search.d.ts CHANGED
@@ -1,11 +1,8 @@
1
- import { type Page } from 'playwright-chromium';
2
1
  import type SearchParams from './interfaces/search-params.interface.js';
3
2
  import type SearchResult from './interfaces/search-result.interface.js';
4
3
  /**
5
4
  * Performs a search on the Discogs marketplace using the provided parameters.
6
- * @param pageInstance
7
- * Optional Playwright page instance to reuse for multiple requests. This can be useful for reducing overhead when making numerous requests.
8
- * If not provided, a new browser instance will be created and managed internally.
5
+ * @param params Search parameters
9
6
  * @returns A promise that resolves to the search results, including items found, pagination details, and the generated URL.
10
7
  */
11
- export default function search({ searchType, searchValue, currency, genre, style, format, formatDescription, condition, year, years, isMakeAnOfferOnly, from, seller, hoursRange, sort, limit, page, lang, }: SearchParams, pageInstance?: Page): Promise<SearchResult>;
8
+ export default function search(params: SearchParams): Promise<SearchResult>;
package/dist/search.js CHANGED
@@ -4,151 +4,35 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.default = search;
7
- const user_agents_1 = __importDefault(require("user-agents"));
8
- const playwright_chromium_1 = require("playwright-chromium");
9
- const currency_data_1 = __importDefault(require("./data/currency.data.js"));
10
- const country_data_1 = __importDefault(require("./data/country.data.js"));
11
- const scrape_1 = __importDefault(require("./scrape.js"));
7
+ const legacy_scraper_1 = __importDefault(require("./scrapers/legacy.scraper.js"));
8
+ const wantlist_scraper_1 = __importDefault(require("./scrapers/wantlist.scraper.js"));
12
9
  /**
13
10
  * Performs a search on the Discogs marketplace using the provided parameters.
14
- * @param pageInstance
15
- * Optional Playwright page instance to reuse for multiple requests. This can be useful for reducing overhead when making numerous requests.
16
- * If not provided, a new browser instance will be created and managed internally.
11
+ * @param params Search parameters
17
12
  * @returns A promise that resolves to the search results, including items found, pagination details, and the generated URL.
18
13
  */
19
- async function search({ searchType = 'q', searchValue, currency, genre, style, format, formatDescription, condition, year, years, isMakeAnOfferOnly = false, from, seller, hoursRange, sort = 'listed,desc', limit = 25, page = 1, lang = 'en', }, pageInstance) {
20
- /** Url to be called by the browser */
21
- const url = [
22
- generateUrl({ searchType, seller, lang }),
23
- serializeParams({
24
- [searchType]: searchValue,
25
- currency,
26
- genre,
27
- style: style?.length ? style : null,
28
- format: format?.length ? format : null,
29
- format_desc: formatDescription?.length ? formatDescription : null,
30
- condition: condition?.length ? condition : null,
31
- year: year && !years ? year : null,
32
- year1: years?.min && !year ? years.min : null,
33
- year2: years?.max && !year ? years.max : null,
34
- offers: isMakeAnOfferOnly ? 1 : null,
35
- ships_from: from,
36
- hours_range: hoursRange,
37
- limit,
38
- page,
39
- sort,
40
- }),
41
- ].join('?');
42
- // Get browser page by user input or generate a new one
43
- const { browserPage, browser, browserContext } = pageInstance
44
- ? { browserPage: pageInstance }
45
- : await (async () => {
46
- /** Init browser */
47
- const browser = await playwright_chromium_1.chromium.launch({
48
- args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gl-drawing-for-tests'],
49
- });
50
- /** Init context */
51
- const browserContext = await browser.newContext({
52
- userAgent: new user_agents_1.default({ platform: 'Win32' }).toString(),
53
- extraHTTPHeaders: {
54
- 'X-PJAX': 'true',
55
- },
56
- javaScriptEnabled: false,
57
- });
58
- /** Init page */
59
- const browserPage = await browserContext.newPage();
60
- return {
61
- browser,
62
- browserContext,
63
- browserPage,
64
- };
65
- })();
66
- // Block all resources except document
67
- await browserPage.route('**/*', route => [
68
- 'stylesheet',
69
- 'image',
70
- 'media',
71
- 'font',
72
- 'script',
73
- 'texttrack',
74
- 'xhr',
75
- 'fetch',
76
- 'eventsource',
77
- 'websocket',
78
- 'manifest',
79
- 'other',
80
- ].includes(route.request().resourceType())
81
- ? route.abort()
82
- : route.continue());
83
- // Inject some globals to the page, so we can use them in the scraping function
84
- await browserPage.addInitScript(g => Object.assign(globalThis, g), { Country: country_data_1.default, Currency: currency_data_1.default });
85
- /** Init page */
86
- const response = await browserPage.goto(url, { waitUntil: 'domcontentloaded' });
87
- /** Status code from the page */
88
- const status = response?.status() ?? 500;
89
- // See current issue: https://github.com/evanw/esbuild/issues/2605
90
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
91
- await browserPage.evaluate(() => (window.__name ??= (func) => func));
92
- // If error status, reject
93
- if (status >= 400) {
94
- const errorMessage =
95
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
96
- (await browserPage.evaluate(() => document.querySelector('h1 + p')?.innerHTML.trim())) || `An error ${status} occurred.`;
97
- // Close browser
98
- await browserContext?.close();
99
- await browser?.close();
100
- throw new Error(errorMessage);
101
- }
102
- /** Url generated by the browser */
103
- const urlGenerated = browserPage.url();
104
- // Scrape data from the page
105
- const { items, total } = await browserPage.evaluate(scrape_1.default);
106
- // Close browser
107
- await browserContext?.close();
108
- await browser?.close();
14
+ async function search(params) {
15
+ const searchParams = {
16
+ ...params,
17
+ isMakeAnOfferOnly: params.isMakeAnOfferOnly ?? false,
18
+ sort: params.sort ?? 'listed,desc',
19
+ limit: params.limit ?? 25,
20
+ page: params.page ?? 1,
21
+ lang: params.lang ?? 'en',
22
+ };
23
+ // Determine which scraper to use
24
+ const isScrapingWantlist = searchParams.searchType === 'user' && !searchParams.seller;
25
+ const { items, total, urlGenerated } = await (isScrapingWantlist ? (0, wantlist_scraper_1.default)(searchParams) : (0, legacy_scraper_1.default)(searchParams));
109
26
  return {
110
27
  items,
111
28
  result: {
112
29
  total,
113
- perPage: limit,
30
+ perPage: searchParams.limit,
114
31
  },
115
32
  page: {
116
- current: page,
117
- total: Math.ceil(total / limit),
33
+ current: searchParams.page,
34
+ total: Math.ceil(total / searchParams.limit),
118
35
  },
119
36
  urlGenerated,
120
37
  };
121
38
  }
122
- /**
123
- * Generate URL to be parsed
124
- * @returns Url
125
- */
126
- function generateUrl({ searchType, seller, lang, }) {
127
- const baseUrl = `https://www.discogs.com/${lang}`;
128
- if (seller) {
129
- const path = searchType === 'user' ? 'mywants' : 'profile';
130
- return `${baseUrl}/seller/${seller}/${path}`;
131
- }
132
- else {
133
- const path = searchType === 'user' ? 'mywants' : 'list';
134
- return `${baseUrl}/sell/${path}`;
135
- }
136
- }
137
- /**
138
- * Serialize params URL
139
- * @param params Object of GET parameters
140
- * @returns Url
141
- */
142
- function serializeParams(params) {
143
- return Object.entries(params)
144
- .flatMap(([key, value]) => {
145
- if (value === undefined || value === null) {
146
- return [];
147
- }
148
- if (Array.isArray(value)) {
149
- return value.map(v => `${key}=${encodeURIComponent(v)}`);
150
- }
151
- return [`${key}=${encodeURIComponent(value)}`];
152
- })
153
- .join('&');
154
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discogs-marketplace-api-nodejs",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
5
5
  "keywords": [
6
6
  "discogs",
@@ -40,7 +40,7 @@
40
40
  }
41
41
  ],
42
42
  "dependencies": {
43
- "playwright-chromium": "^1.54.1",
43
+ "linkedom": "^0.18.12",
44
44
  "user-agents": "^1.1.603"
45
45
  },
46
46
  "devDependencies": {
package/dist/scrape.d.ts DELETED
@@ -1,10 +0,0 @@
1
- import type SearchResult from './interfaces/search-result.interface.js';
2
- /**
3
- * Parses the page and returns the items found.
4
- * This function is called by the browser context when the page is loaded.
5
- * @returns Items found and total
6
- */
7
- export default function scrape(): Pick<SearchResult, 'items'> & {
8
- /** Total items found */
9
- total: SearchResult['result']['total'];
10
- };
@@ -1,4 +0,0 @@
1
- /**
2
- * Hours range type
3
- */
4
- export type HoursRange = `${number}-${number}`;