discogs-marketplace-api-nodejs 1.12.0 → 1.14.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 +151 -176
- package/dist/index.d.ts +1 -3
- package/dist/index.js +1 -2
- package/dist/interfaces/api/shop-details-result.api.interface.d.ts +33 -0
- package/dist/interfaces/api/shop-result.api.interface.d.ts +111 -0
- package/dist/interfaces/search-params.interface.d.ts +166 -63
- package/dist/interfaces/search-result.interface.d.ts +39 -26
- package/dist/scrapers/legacy.scraper.d.ts +11 -0
- package/dist/scrapers/legacy.scraper.js +200 -0
- package/dist/scrapers/modern.scraper.d.ts +11 -0
- package/dist/scrapers/modern.scraper.js +167 -0
- package/dist/scrapers/wantlist.scraper.d.ts +11 -0
- package/dist/scrapers/wantlist.scraper.js +53 -0
- package/dist/search.d.ts +6 -6
- package/dist/search.js +21 -134
- package/dist/types/api.type.d.ts +4 -0
- package/dist/types/api.type.js +2 -0
- package/dist/types/from.type.d.ts +2 -1
- package/package.json +2 -2
- package/dist/get-search-params.d.ts +0 -10
- package/dist/get-search-params.js +0 -122
- package/dist/scrape.d.ts +0 -10
- package/dist/scrape.js +0 -126
- package/dist/types/hours-range.type.d.ts +0 -4
- package/dist/types/search-type.type.d.ts +0 -4
- /package/dist/{types/hours-range.type.js → interfaces/api/shop-details-result.api.interface.js} +0 -0
- /package/dist/{types/search-type.type.js → interfaces/api/shop-result.api.interface.js} +0 -0
|
@@ -0,0 +1,167 @@
|
|
|
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
|
+
const search_1 = require("../search.js");
|
|
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 scrape({ currencies, genres, formats, formatDescriptions, conditions, years, isMakeAnOfferOnly = false, from, sort = search_1.DEFAULT_SORT, limit = search_1.DEFAULT_LIMIT, page = search_1.DEFAULT_PAGE, releaseIds, sellerIds, artistIds, priceRange, sellerRatingMin = 0, includeGenericSleeves = true, includeSleevelessMedia = true, showUnavailable = true, sellerRatingCountMin = 0, }) {
|
|
16
|
+
const [sortType, sortOrder] = sort.split(',');
|
|
17
|
+
const urlGenerated = [
|
|
18
|
+
'https://www.discogs.com/api/shop-page-api/sell_item',
|
|
19
|
+
new URLSearchParams([
|
|
20
|
+
['sellerRatingMin', sellerRatingMin.toString()],
|
|
21
|
+
['includeGenericSleeves', includeGenericSleeves.toString()],
|
|
22
|
+
['includeSleevelessMedia', includeSleevelessMedia.toString()],
|
|
23
|
+
['showUnavailable', showUnavailable.toString()],
|
|
24
|
+
['sellerRatingCountMin', sellerRatingCountMin.toString()],
|
|
25
|
+
[
|
|
26
|
+
'sort',
|
|
27
|
+
{
|
|
28
|
+
listed: 'listedDate',
|
|
29
|
+
condition: 'mediaCondition',
|
|
30
|
+
artist: 'artist',
|
|
31
|
+
title: 'title',
|
|
32
|
+
seller: 'seller',
|
|
33
|
+
price: 'price',
|
|
34
|
+
}[sortType] ?? 'listedDate',
|
|
35
|
+
],
|
|
36
|
+
[
|
|
37
|
+
'sortOrder',
|
|
38
|
+
{
|
|
39
|
+
asc: 'ascending',
|
|
40
|
+
desc: 'descending',
|
|
41
|
+
}[sortOrder] ?? 'ascending',
|
|
42
|
+
],
|
|
43
|
+
['count', limit.toString()],
|
|
44
|
+
['offset', ((page - 1) * limit).toString()],
|
|
45
|
+
...(releaseIds?.map(r => ['release', r.toString()]) ?? []),
|
|
46
|
+
...(from?.map(f => Object.keys(country_data_1.default).find(key => f === country_data_1.default[key]) ?? '') ?? []).map(f => [
|
|
47
|
+
'shipsFrom',
|
|
48
|
+
f,
|
|
49
|
+
]),
|
|
50
|
+
...(formats?.map(f => ['formatName', f]) ?? []),
|
|
51
|
+
...(formatDescriptions?.map(fd => ['formatDescription', fd]) ?? []),
|
|
52
|
+
...(conditions?.map(c => ['sleeveCondition', c]) ?? []),
|
|
53
|
+
...(conditions?.map(c => ['mediaCondition', c]) ?? []),
|
|
54
|
+
...(currencies?.map(c => ['currency', c]) ?? []),
|
|
55
|
+
...(genres?.map(g => ['genre', g]) ?? []),
|
|
56
|
+
...(sellerIds?.map(s => ['seller', s.toString()]) ?? []),
|
|
57
|
+
...(artistIds?.map(a => ['artist', a.toString()]) ?? []),
|
|
58
|
+
['allowsOffers', isMakeAnOfferOnly ? 'true' : ''],
|
|
59
|
+
['yearRangeLow', years?.min.toString() ?? ''],
|
|
60
|
+
['yearRangeHigh', years?.max.toString() ?? ''],
|
|
61
|
+
['priceRangeLow', priceRange?.min.toString() ?? ''],
|
|
62
|
+
['priceRangeHigh', priceRange?.max.toString() ?? ''],
|
|
63
|
+
].filter(([, p]) => !!p)).toString(),
|
|
64
|
+
].join('?');
|
|
65
|
+
const result = (await (await globalThis.fetch(urlGenerated, {
|
|
66
|
+
method: 'GET',
|
|
67
|
+
headers: {
|
|
68
|
+
'User-Agent': 'Discogs',
|
|
69
|
+
'Content-Type': 'application/json',
|
|
70
|
+
},
|
|
71
|
+
referrer: 'https://discogs.com',
|
|
72
|
+
})).json());
|
|
73
|
+
const detailsResult = (await (await globalThis.fetch('https://www.discogs.com/graphql', {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
headers: {
|
|
76
|
+
'User-Agent': 'Discogs',
|
|
77
|
+
'Content-Type': 'application/json',
|
|
78
|
+
},
|
|
79
|
+
referrer: 'https://discogs.com',
|
|
80
|
+
body: JSON.stringify({
|
|
81
|
+
// eslint-disable-next-line max-len
|
|
82
|
+
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}',
|
|
83
|
+
variables: {
|
|
84
|
+
discogsIds: result.items?.map(z => z.release?.releaseId ?? 0).filter((x, i, self) => x && self.indexOf(x) === i),
|
|
85
|
+
first: 1,
|
|
86
|
+
},
|
|
87
|
+
extensions: {
|
|
88
|
+
persistedQuery: {
|
|
89
|
+
version: 1,
|
|
90
|
+
sha256Hash: 'ee9d48441023ebd1e6ca169e550581b45de216e88b40711acb6617e49e1bb0cb',
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
}),
|
|
94
|
+
})).json());
|
|
95
|
+
const details = Object.fromEntries(detailsResult.data?.releases?.map(release => [
|
|
96
|
+
release.discogsId ?? 0,
|
|
97
|
+
{
|
|
98
|
+
imageUrl: release.images?.edges?.[0]?.node?.thumbnail?.webpUrl ?? null,
|
|
99
|
+
want: release.inWantlistCount ?? 0,
|
|
100
|
+
have: release.inCollectionCount ?? 0,
|
|
101
|
+
},
|
|
102
|
+
]) ?? []);
|
|
103
|
+
const items = result.items?.map(item => {
|
|
104
|
+
const detail = details[item.release?.releaseId ?? 0];
|
|
105
|
+
return {
|
|
106
|
+
id: item.itemId,
|
|
107
|
+
title: `${item.release?.artists?.map(x => x.name ?? '').join(', ') ?? ''} - ${item.release?.title ?? ''} (${item.release?.majorFormat ?? ''})`,
|
|
108
|
+
artists: item.release?.artists?.map(x => ({
|
|
109
|
+
id: x.artistId ?? null,
|
|
110
|
+
name: x.name ?? '',
|
|
111
|
+
url: x.artistId ? `https://www.discogs.com/artist/${x.artistId}` : null,
|
|
112
|
+
})) ?? [],
|
|
113
|
+
release: {
|
|
114
|
+
id: item.release?.releaseId ?? 0,
|
|
115
|
+
name: item.release?.title ?? '',
|
|
116
|
+
url: `https://www.discogs.com/release/${item.release?.releaseId ?? '0'}`,
|
|
117
|
+
},
|
|
118
|
+
formats: item.release?.formatNames ?? [],
|
|
119
|
+
labels: item.release?.labels?.map(x => ({
|
|
120
|
+
id: x.labelId ?? 0,
|
|
121
|
+
name: x.name ?? '',
|
|
122
|
+
url: `https://www.discogs.com/label/${x.labelId ?? '0'}`,
|
|
123
|
+
})) ?? [],
|
|
124
|
+
url: `https://www.discogs.com/sell/item/${item.itemId}`,
|
|
125
|
+
listedAt: new Date(item.listedDate ?? ''),
|
|
126
|
+
catnos: [],
|
|
127
|
+
imageUrl: detail?.imageUrl ?? null,
|
|
128
|
+
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
129
|
+
description: item.comments || null,
|
|
130
|
+
isAcceptingOffer: item.allowsOffers ?? false,
|
|
131
|
+
isAvailable: true,
|
|
132
|
+
condition: {
|
|
133
|
+
media: {
|
|
134
|
+
full: item.mediaCondition ?? '',
|
|
135
|
+
short: /\(([^)]+)\)/.exec(item.mediaCondition ?? '')?.[1] ?? '',
|
|
136
|
+
},
|
|
137
|
+
sleeve: {
|
|
138
|
+
full: item.sleeveCondition ?? null,
|
|
139
|
+
short: /\(([^)]+)\)/.exec(item.sleeveCondition ?? '')?.[1] ?? null,
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
seller: {
|
|
143
|
+
name: item.seller?.name ?? '',
|
|
144
|
+
url: `https://www.discogs.com/seller/${item.seller?.name ?? ''}/profile`,
|
|
145
|
+
score: item.seller?.rating ? `${item.seller.rating.toFixed(1)}%` : null,
|
|
146
|
+
notes: item.seller?.ratingCount ?? null,
|
|
147
|
+
},
|
|
148
|
+
price: {
|
|
149
|
+
base: `${item.price?.currencyCode === 'JPY' ? (item.price.amount ?? 0) : (item.price?.amount ?? 0).toFixed(2)} ${(item.price?.currencyCode ?? '')}`,
|
|
150
|
+
shipping: item.shipping
|
|
151
|
+
? `${item.price?.currencyCode === 'JPY'
|
|
152
|
+
? (item.shipping.shippingPrice ?? 0)
|
|
153
|
+
: (item.shipping.shippingPrice ?? 0).toFixed(2)} ${(item.price?.currencyCode ?? '')}`
|
|
154
|
+
: null,
|
|
155
|
+
},
|
|
156
|
+
country: {
|
|
157
|
+
name: item.seller?.shipsFrom ?? '',
|
|
158
|
+
code: country_data_1.default[item.seller?.shipsFrom],
|
|
159
|
+
},
|
|
160
|
+
community: {
|
|
161
|
+
have: detail?.have ?? 0,
|
|
162
|
+
want: detail?.want ?? 0,
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}) ?? [];
|
|
166
|
+
return { total: result.totalCount ?? 0, items, urlGenerated };
|
|
167
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type SearchResult from '../interfaces/search-result.interface.js';
|
|
2
|
+
import type { SearchParamsModern } 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: SearchParamsModern): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
|
|
9
|
+
/** Total items found */
|
|
10
|
+
total: SearchResult['result']['total'];
|
|
11
|
+
}>;
|
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
/** Fetch the first page of user wantlist */
|
|
17
|
+
const firstPage = await (await globalThis.fetch(`https://www.discogs.com/wantlist?${new URLSearchParams({
|
|
18
|
+
page: '1',
|
|
19
|
+
limit: PER_PAGE.toString(),
|
|
20
|
+
user: searchParams.wantlist ?? '',
|
|
21
|
+
layout: 'sm',
|
|
22
|
+
}).toString()}`, {
|
|
23
|
+
headers: { 'User-Agent': 'Discogs', 'Content-Type': 'application/json' },
|
|
24
|
+
referrer: 'https://discogs.com',
|
|
25
|
+
})).text();
|
|
26
|
+
const { document: firstPageDocument } = (0, linkedom_1.parseHTML)(firstPage);
|
|
27
|
+
/** Total number of items in the wantlist */
|
|
28
|
+
const total = +(firstPageDocument.querySelector('.pagination_total')?.textContent?.split(' of ').pop()?.replace(',', '') ?? '0');
|
|
29
|
+
const wants = await Promise.all(new Array(Math.ceil(total / PER_PAGE)).fill({}).map(async (_, i) => {
|
|
30
|
+
const page = i + 1;
|
|
31
|
+
const result = page === 1
|
|
32
|
+
? firstPage
|
|
33
|
+
: (await globalThis.fetch(`https://www.discogs.com/wantlist?${new URLSearchParams({
|
|
34
|
+
page: page.toString(),
|
|
35
|
+
limit: PER_PAGE.toString(),
|
|
36
|
+
user: searchParams.wantlist ?? '',
|
|
37
|
+
layout: 'sm',
|
|
38
|
+
}).toString()}`, {
|
|
39
|
+
headers: { 'User-Agent': 'Discogs', 'Content-Type': 'application/json' },
|
|
40
|
+
referrer: 'https://discogs.com',
|
|
41
|
+
})).text();
|
|
42
|
+
const { document } = (0, linkedom_1.parseHTML)(result);
|
|
43
|
+
/** Extract the links to the items in the wantlist, if there's no link it's not for sale */
|
|
44
|
+
const links = [...document.querySelectorAll('.marketplace_for_sale_count a')];
|
|
45
|
+
return links.map(x => +(new URL(`https://discogs.com${x.href}`).pathname.split('/').pop() ?? '0'));
|
|
46
|
+
}));
|
|
47
|
+
const wantlistIds = wants.flat();
|
|
48
|
+
// If there's nothing for sale
|
|
49
|
+
if (wantlistIds.length === 0) {
|
|
50
|
+
return { items: [], total: 0, urlGenerated: '' };
|
|
51
|
+
}
|
|
52
|
+
return (0, modern_scraper_1.default)({ ...searchParams, releaseIds: wantlistIds, wantlist: undefined });
|
|
53
|
+
}
|
package/dist/search.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type SearchParams from './interfaces/search-params.interface.js';
|
|
1
|
+
import type { SearchParams } from './interfaces/search-params.interface.js';
|
|
3
2
|
import type SearchResult from './interfaces/search-result.interface.js';
|
|
3
|
+
export declare const DEFAULT_LIMIT = 25;
|
|
4
|
+
export declare const DEFAULT_PAGE = 1;
|
|
5
|
+
export declare const DEFAULT_SORT = "listed,desc";
|
|
4
6
|
/**
|
|
5
7
|
* Performs a search on the Discogs marketplace using the provided parameters.
|
|
6
|
-
* @param
|
|
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.
|
|
8
|
+
* @param searchParams Search parameters
|
|
9
9
|
* @returns A promise that resolves to the search results, including items found, pagination details, and the generated URL.
|
|
10
10
|
*/
|
|
11
|
-
export default function search(
|
|
11
|
+
export default function search(searchParams: SearchParams): Promise<SearchResult>;
|
package/dist/search.js
CHANGED
|
@@ -3,152 +3,39 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.DEFAULT_SORT = exports.DEFAULT_PAGE = exports.DEFAULT_LIMIT = void 0;
|
|
6
7
|
exports.default = search;
|
|
7
|
-
const
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
const legacy_scraper_1 = __importDefault(require("./scrapers/legacy.scraper.js"));
|
|
9
|
+
const wantlist_scraper_1 = __importDefault(require("./scrapers/wantlist.scraper.js"));
|
|
10
|
+
const modern_scraper_1 = __importDefault(require("./scrapers/modern.scraper.js"));
|
|
11
|
+
exports.DEFAULT_LIMIT = 25;
|
|
12
|
+
exports.DEFAULT_PAGE = 1;
|
|
13
|
+
exports.DEFAULT_SORT = 'listed,desc';
|
|
12
14
|
/**
|
|
13
15
|
* Performs a search on the Discogs marketplace using the provided parameters.
|
|
14
|
-
* @param
|
|
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.
|
|
16
|
+
* @param searchParams Search parameters
|
|
17
17
|
* @returns A promise that resolves to the search results, including items found, pagination details, and the generated URL.
|
|
18
18
|
*/
|
|
19
|
-
async function search(
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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();
|
|
19
|
+
async function search(searchParams) {
|
|
20
|
+
const { items, total, urlGenerated } = await (() => {
|
|
21
|
+
if (searchParams.api === 'v2' && searchParams.wantlist) {
|
|
22
|
+
return (0, wantlist_scraper_1.default)(searchParams);
|
|
23
|
+
}
|
|
24
|
+
if (searchParams.api === 'v2') {
|
|
25
|
+
return (0, modern_scraper_1.default)(searchParams);
|
|
26
|
+
}
|
|
27
|
+
return (0, legacy_scraper_1.default)(searchParams);
|
|
28
|
+
})();
|
|
109
29
|
return {
|
|
110
30
|
items,
|
|
111
31
|
result: {
|
|
112
32
|
total,
|
|
113
|
-
perPage: limit,
|
|
33
|
+
perPage: searchParams.limit ?? exports.DEFAULT_LIMIT,
|
|
114
34
|
},
|
|
115
35
|
page: {
|
|
116
|
-
current: page,
|
|
117
|
-
total: Math.ceil(total / limit),
|
|
36
|
+
current: searchParams.page ?? exports.DEFAULT_PAGE,
|
|
37
|
+
total: Math.ceil(total / (searchParams.limit ?? exports.DEFAULT_LIMIT)),
|
|
118
38
|
},
|
|
119
39
|
urlGenerated,
|
|
120
40
|
};
|
|
121
41
|
}
|
|
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,5 @@
|
|
|
1
|
+
import type { CountryValues } from '../data/country.data.js';
|
|
1
2
|
/**
|
|
2
3
|
* From
|
|
3
4
|
*/
|
|
4
|
-
export type From =
|
|
5
|
+
export type From = CountryValues | ({} & string);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "discogs-marketplace-api-nodejs",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.14.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
|
-
"
|
|
43
|
+
"linkedom": "^0.18.12",
|
|
44
44
|
"user-agents": "^1.1.603"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type SearchParams from './interfaces/search-params.interface.js';
|
|
2
|
-
/**
|
|
3
|
-
* Get search parameters from a Discogs Marketplace URL
|
|
4
|
-
* @param url Discogs Marketplace URL
|
|
5
|
-
* @returns Search parameters
|
|
6
|
-
* @example
|
|
7
|
-
* const searchParams = getSearchParamsFromUrl('https://www.discogs.com/sell/list?sort=listed,desc&limit=250&artist_id=244819&page=2&genre=Rock')
|
|
8
|
-
* // { searchType: 'artist_id', searchValue: '244819', genre: 'Rock', sort: 'listed,desc', limit: 250, page: 2 }
|
|
9
|
-
*/
|
|
10
|
-
export default function getSearchParamsFromUrl(url: string): SearchParams;
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/* eslint-disable no-restricted-syntax */
|
|
3
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.default = getSearchParamsFromUrl;
|
|
5
|
-
/**
|
|
6
|
-
* Safely parse an integer from a string
|
|
7
|
-
* @param value String to parse
|
|
8
|
-
* @returns Parsed integer or undefined if parsing fails
|
|
9
|
-
*/
|
|
10
|
-
const safeParseInt = (value) => {
|
|
11
|
-
const parsed = parseInt(value ?? '', 10);
|
|
12
|
-
return isNaN(parsed) ? undefined : parsed;
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* Get search parameters from a Discogs Marketplace URL
|
|
16
|
-
* @param url Discogs Marketplace URL
|
|
17
|
-
* @returns Search parameters
|
|
18
|
-
* @example
|
|
19
|
-
* const searchParams = getSearchParamsFromUrl('https://www.discogs.com/sell/list?sort=listed,desc&limit=250&artist_id=244819&page=2&genre=Rock')
|
|
20
|
-
* // { searchType: 'artist_id', searchValue: '244819', genre: 'Rock', sort: 'listed,desc', limit: 250, page: 2 }
|
|
21
|
-
*/
|
|
22
|
-
function getSearchParamsFromUrl(url) {
|
|
23
|
-
const { searchParams: urlSearchParams, pathname, host } = new URL(url);
|
|
24
|
-
if (!host.includes('discogs.com')) {
|
|
25
|
-
throw new Error(`Invalid host: ${host}. Expected 'www.discogs.com' or 'discogs.com'.`);
|
|
26
|
-
}
|
|
27
|
-
const searchParams = {
|
|
28
|
-
searchType: 'q', // Default search type
|
|
29
|
-
};
|
|
30
|
-
// Retrieve the search type and value
|
|
31
|
-
const searchType = ['q', 'master_id', 'release_id', 'label_id', 'artist_id', 'user'].find(type => urlSearchParams.has(type));
|
|
32
|
-
if (searchType) {
|
|
33
|
-
searchParams.searchType = searchType;
|
|
34
|
-
const searchValue = urlSearchParams.get(searchType);
|
|
35
|
-
if (searchValue) {
|
|
36
|
-
searchParams.searchValue = searchValue;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
// Retrieve basic search values
|
|
40
|
-
for (const key of ['currency', 'genre', 'ships_from', 'seller', 'sort', 'hours_range']) {
|
|
41
|
-
const value = urlSearchParams.get(key);
|
|
42
|
-
if (value) {
|
|
43
|
-
switch (key) {
|
|
44
|
-
case 'ships_from':
|
|
45
|
-
searchParams.from = value;
|
|
46
|
-
break;
|
|
47
|
-
case 'hours_range':
|
|
48
|
-
searchParams.hoursRange = value;
|
|
49
|
-
break;
|
|
50
|
-
default:
|
|
51
|
-
searchParams[key] = value;
|
|
52
|
-
break;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
// Retrieve number search values
|
|
57
|
-
for (const key of ['limit', 'page']) {
|
|
58
|
-
const value = safeParseInt(urlSearchParams.get(key));
|
|
59
|
-
if (value) {
|
|
60
|
-
switch (key) {
|
|
61
|
-
case 'limit':
|
|
62
|
-
searchParams.limit = value;
|
|
63
|
-
break;
|
|
64
|
-
default:
|
|
65
|
-
searchParams[key] = value;
|
|
66
|
-
break;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
// Retrieve array search values
|
|
71
|
-
for (const key of ['style', 'format', 'format_desc', 'condition']) {
|
|
72
|
-
const values = urlSearchParams.getAll(key);
|
|
73
|
-
if (values.length) {
|
|
74
|
-
switch (key) {
|
|
75
|
-
case 'format_desc':
|
|
76
|
-
searchParams.formatDescription = values;
|
|
77
|
-
break;
|
|
78
|
-
default:
|
|
79
|
-
searchParams[key] = values;
|
|
80
|
-
break;
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
// Check if search is on offers only
|
|
85
|
-
if (urlSearchParams.get('offers') === '1') {
|
|
86
|
-
searchParams.isMakeAnOfferOnly = true;
|
|
87
|
-
}
|
|
88
|
-
// Handle year and years
|
|
89
|
-
const year = safeParseInt(urlSearchParams.get('year'));
|
|
90
|
-
const year1 = safeParseInt(urlSearchParams.get('year1'));
|
|
91
|
-
const year2 = safeParseInt(urlSearchParams.get('year2'));
|
|
92
|
-
if (year) {
|
|
93
|
-
searchParams.year = year;
|
|
94
|
-
}
|
|
95
|
-
else if (year1 && year2) {
|
|
96
|
-
searchParams.years = { min: year1, max: year2 };
|
|
97
|
-
}
|
|
98
|
-
// Retrieve the language from the URL path
|
|
99
|
-
const pathSegments = pathname.split('/').filter(x => x);
|
|
100
|
-
if (/^[a-z]{2}$/i.test(pathSegments[0] ?? '')) {
|
|
101
|
-
searchParams.lang = pathSegments[0]?.toLowerCase();
|
|
102
|
-
}
|
|
103
|
-
// Handle specific case for release ID in the URL path
|
|
104
|
-
const releaseIdMatch = /\/sell\/release\/(\d+)/.exec(url);
|
|
105
|
-
if (releaseIdMatch?.[1]) {
|
|
106
|
-
searchParams.searchType = 'release_id';
|
|
107
|
-
searchParams.searchValue = releaseIdMatch[1];
|
|
108
|
-
}
|
|
109
|
-
// Handle specific case for seller profile in the URL path
|
|
110
|
-
const sellerProfileMatch = /\/seller\/([^/]+)\/profile/.exec(url);
|
|
111
|
-
if (sellerProfileMatch?.[1]) {
|
|
112
|
-
searchParams.seller = sellerProfileMatch[1];
|
|
113
|
-
}
|
|
114
|
-
// Handle specific case for seller name on wantlist in the URL path
|
|
115
|
-
const sellerMyWantsMatch = /\/seller\/([^/]+)\/mywants/.exec(url);
|
|
116
|
-
if (sellerMyWantsMatch?.[1]) {
|
|
117
|
-
searchParams.searchType = 'user';
|
|
118
|
-
searchParams.searchValue = urlSearchParams.get('user') ?? '';
|
|
119
|
-
searchParams.seller = sellerMyWantsMatch[1];
|
|
120
|
-
}
|
|
121
|
-
return searchParams;
|
|
122
|
-
}
|
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
|
-
};
|