discogs-marketplace-api-nodejs 1.11.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.
@@ -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
- import type SearchParams from './interfaces/search-params.interface';
3
- import type SearchResult from './interfaces/search-result.interface';
1
+ import type SearchParams from './interfaces/search-params.interface.js';
2
+ import type SearchResult from './interfaces/search-result.interface.js';
4
3
  /**
5
- * Search elements on discogs marketplace
6
- * @param pageInstance
7
- * If you are making a lot of requests, you can pass a playwright page instance to reuse it.
8
- * That way, you can create a page once, reuse it for all requests and close it yourself at the end.
9
- * @returns Items found
4
+ * Performs a search on the Discogs marketplace using the provided parameters.
5
+ * @param params Search parameters
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, isAudioSample, isMakeAnOfferOnly, from, seller, 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"));
10
- const country_data_1 = __importDefault(require("./data/country.data"));
11
- const scrape_1 = __importDefault(require("./scrape"));
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
- * Search elements on discogs marketplace
14
- * @param pageInstance
15
- * If you are making a lot of requests, you can pass a playwright page instance to reuse it.
16
- * That way, you can create a page once, reuse it for all requests and close it yourself at the end.
17
- * @returns Items found
10
+ * Performs a search on the Discogs marketplace using the provided parameters.
11
+ * @param params Search parameters
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, isAudioSample = false, isMakeAnOfferOnly = false, from, seller, sort = 'Listed Newest', 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
- audio: isAudioSample ? 1 : null,
35
- offers: isMakeAnOfferOnly ? 1 : null,
36
- ships_from: from,
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
- }
@@ -1,4 +1,7 @@
1
+ type SortField = 'listed' | 'condition' | 'artist' | 'title' | 'label' | 'seller' | 'price';
2
+ type SortDirection = 'asc' | 'desc';
1
3
  /**
2
4
  * Sorts
3
5
  */
4
- export type Sort = 'Artist A-Z' | 'Artist Z-A' | 'Condition (M)-(P)' | 'Condition (P)-(M)' | 'Label A-Z' | 'Label Z-A' | 'Listed Newest' | 'Listed Oldest' | 'Price Highest' | 'Price Lowest' | 'Seller A-Z' | 'Seller Z-A' | 'Title A-Z' | 'Title Z-A' | ({} & string);
6
+ export type Sort = `${SortField},${SortDirection}` | ({} & string);
7
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discogs-marketplace-api-nodejs",
3
- "version": "1.11.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,30 +40,30 @@
40
40
  }
41
41
  ],
42
42
  "dependencies": {
43
- "playwright-chromium": "^1.51.1",
44
- "user-agents": "^1.1.505"
43
+ "linkedom": "^0.18.12",
44
+ "user-agents": "^1.1.603"
45
45
  },
46
46
  "devDependencies": {
47
- "@eslint/js": "^9.24.0",
48
- "@types/node": "^20.17.30",
47
+ "@eslint/js": "^9.31.0",
48
+ "@types/node": "^20.19.8",
49
49
  "@types/user-agents": "^1.0.4",
50
50
  "@typescript-eslint/eslint-plugin": "^8.29.1",
51
51
  "@typescript-eslint/parser": "^8.29.1",
52
- "cspell": "^8.18.1",
53
- "eslint": "^9.24.0",
54
- "eslint-config-prettier": "^10.1.2",
55
- "eslint-import-resolver-typescript": "^4.3.2",
56
- "eslint-plugin-import": "^2.31.0",
57
- "eslint-plugin-jsdoc": "^50.6.9",
58
- "globals": "^16.0.0",
52
+ "cspell": "^9.1.5",
53
+ "eslint": "^9.31.0",
54
+ "eslint-config-prettier": "^10.1.5",
55
+ "eslint-import-resolver-typescript": "^4.4.4",
56
+ "eslint-plugin-import": "^2.32.0",
57
+ "eslint-plugin-jsdoc": "^51.4.1",
58
+ "globals": "^16.3.0",
59
59
  "husky": "^9.1.7",
60
- "knip": "^5.50.2",
61
- "lint-staged": "^15.5.0",
62
- "prettier": "^3.5.3",
60
+ "knip": "^5.61.3",
61
+ "lint-staged": "^16.1.2",
62
+ "prettier": "^3.6.2",
63
63
  "rimraf": "^6.0.1",
64
- "tsc-alias": "^1.8.15",
65
- "tsx": "^4.19.3",
64
+ "tsc-alias": "^1.8.16",
65
+ "tsx": "^4.20.3",
66
66
  "typescript": "^5.8.3",
67
- "typescript-eslint": "^8.29.1"
67
+ "typescript-eslint": "^8.37.0"
68
68
  }
69
69
  }
package/dist/scrape.d.ts DELETED
@@ -1,10 +0,0 @@
1
- import type SearchResult from './interfaces/search-result.interface';
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
- };