discogs-marketplace-api-nodejs 1.16.8 → 1.17.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 +111 -151
- package/dist/data/country.data.d.ts +1 -1
- package/dist/data/style.data.d.ts +763 -0
- package/dist/data/style.data.js +765 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +3 -2
- package/dist/interfaces/api/marketplace-search-result.api.interface.d.ts +148 -0
- package/dist/interfaces/api/{shop-details-result.api.interface.d.ts → releases-result.api.interface.d.ts} +4 -1
- package/dist/interfaces/api/wantlist-result.api.interface.d.ts +109 -0
- package/dist/interfaces/search-params.interface.d.ts +83 -163
- package/dist/interfaces/search-result.interface.d.ts +22 -20
- package/dist/scrapers/browser-context.d.ts +9 -0
- package/dist/scrapers/browser-context.js +28 -0
- package/dist/scrapers/marketplace.scraper.d.ts +10 -0
- package/dist/scrapers/marketplace.scraper.js +292 -0
- package/dist/search.d.ts +6 -9
- package/dist/search.js +10 -57
- package/dist/types/condition.type.d.ts +4 -0
- package/dist/types/currency.type.d.ts +1 -1
- package/dist/types/format-description.type.d.ts +1 -1
- package/dist/types/from.type.d.ts +1 -1
- package/dist/types/sort.type.d.ts +1 -1
- package/dist/types/style.type.d.ts +2 -1
- package/dist/wantlist.d.ts +28 -0
- package/dist/wantlist.js +101 -0
- package/package.json +16 -18
- package/dist/data/currency.data.d.ts +0 -36
- package/dist/data/currency.data.js +0 -35
- package/dist/interfaces/api/shop-result-error.api.interface.d.ts +0 -8
- package/dist/interfaces/api/shop-result.api.interface.d.ts +0 -111
- package/dist/scrapers/extractors/legacy.extractor.d.ts +0 -11
- package/dist/scrapers/extractors/legacy.extractor.js +0 -138
- package/dist/scrapers/legacy.scraper.d.ts +0 -13
- package/dist/scrapers/legacy.scraper.js +0 -75
- package/dist/scrapers/modern.scraper.d.ts +0 -13
- package/dist/scrapers/modern.scraper.js +0 -199
- package/dist/scrapers/wantlist.scraper.d.ts +0 -13
- package/dist/scrapers/wantlist.scraper.js +0 -66
- package/dist/types/api.type.d.ts +0 -4
- package/dist/types/api.type.js +0 -2
- package/dist/types/lang.type.d.ts +0 -4
- package/dist/types/lang.type.js +0 -2
- package/dist/types/limit.type.d.ts +0 -4
- package/dist/types/limit.type.js +0 -2
- /package/dist/interfaces/api/{shop-details-result.api.interface.js → marketplace-search-result.api.interface.js} +0 -0
- /package/dist/interfaces/api/{shop-result-error.api.interface.js → releases-result.api.interface.js} +0 -0
- /package/dist/interfaces/api/{shop-result.api.interface.js → wantlist-result.api.interface.js} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { CountryValues } from 'data/country.data';
|
|
2
|
-
import type {
|
|
1
|
+
import type { CountryValues } from '../data/country.data.js';
|
|
2
|
+
import type { Currency } from '../types/currency.type.js';
|
|
3
3
|
/**
|
|
4
4
|
* Result returned from a Discogs Marketplace search.
|
|
5
5
|
*/
|
|
@@ -27,6 +27,12 @@ export default interface SearchResult {
|
|
|
27
27
|
name: string;
|
|
28
28
|
/** Release URL */
|
|
29
29
|
url: string;
|
|
30
|
+
/** Release year */
|
|
31
|
+
year: number | null;
|
|
32
|
+
/** Release country */
|
|
33
|
+
country: string | null;
|
|
34
|
+
/** Average rating of the release by the community, from 0 to 5 */
|
|
35
|
+
rating: number | null;
|
|
30
36
|
};
|
|
31
37
|
/** List of formats */
|
|
32
38
|
formats: Array<string>;
|
|
@@ -45,8 +51,10 @@ export default interface SearchResult {
|
|
|
45
51
|
listedAt: Date | null;
|
|
46
52
|
/** Array of catalog numbers */
|
|
47
53
|
catnos: Array<string>;
|
|
48
|
-
/** URL to the
|
|
54
|
+
/** URL to the release's image */
|
|
49
55
|
imageUrl: string | null;
|
|
56
|
+
/** URLs of the photos of the item, taken by the seller */
|
|
57
|
+
photos: Array<string>;
|
|
50
58
|
/** Text description of the item */
|
|
51
59
|
description: string | null;
|
|
52
60
|
/** Indicates if offers are accepted */
|
|
@@ -72,6 +80,8 @@ export default interface SearchResult {
|
|
|
72
80
|
};
|
|
73
81
|
/** Seller information */
|
|
74
82
|
seller: {
|
|
83
|
+
/** Seller's ID, to use in `sellerIds` */
|
|
84
|
+
id: number;
|
|
75
85
|
/** Seller's username */
|
|
76
86
|
name: string;
|
|
77
87
|
/** Seller's profile URL */
|
|
@@ -80,6 +90,8 @@ export default interface SearchResult {
|
|
|
80
90
|
score: string | null;
|
|
81
91
|
/** Number of notes/reviews */
|
|
82
92
|
notes: number | null;
|
|
93
|
+
/** Whether the seller is an independent record store */
|
|
94
|
+
isIndependent: boolean;
|
|
83
95
|
};
|
|
84
96
|
/** Pricing details */
|
|
85
97
|
price: {
|
|
@@ -87,12 +99,12 @@ export default interface SearchResult {
|
|
|
87
99
|
* Base price as a string combining amount and currency.
|
|
88
100
|
* @example '12.34 USD'
|
|
89
101
|
*/
|
|
90
|
-
base: `${number} ${
|
|
102
|
+
base: `${number} ${Currency}`;
|
|
91
103
|
/**
|
|
92
104
|
* Shipping cost as a string combining amount and currency.
|
|
93
105
|
* @example '5.67 USD'
|
|
94
106
|
*/
|
|
95
|
-
shipping: `${number} ${
|
|
107
|
+
shipping: `${number} ${Currency}` | null;
|
|
96
108
|
};
|
|
97
109
|
/** Shipping origin country */
|
|
98
110
|
country: {
|
|
@@ -112,20 +124,10 @@ export default interface SearchResult {
|
|
|
112
124
|
want: number;
|
|
113
125
|
};
|
|
114
126
|
}>;
|
|
115
|
-
/**
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
total: number;
|
|
121
|
-
};
|
|
122
|
-
/** Overall search result metadata */
|
|
123
|
-
result: {
|
|
124
|
-
/** Total number of results found */
|
|
125
|
-
total: number;
|
|
126
|
-
/** Number of results per page */
|
|
127
|
-
perPage: number;
|
|
128
|
-
};
|
|
129
|
-
/** The generated URL used for the search */
|
|
127
|
+
/** Total number of results found */
|
|
128
|
+
total: number;
|
|
129
|
+
/** Cursor of the next page, to pass as `after`, or null on the last page */
|
|
130
|
+
nextCursor: string | null;
|
|
131
|
+
/** URL of the same search on Discogs */
|
|
130
132
|
urlGenerated: string;
|
|
131
133
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Browser, BrowserContext } from 'patchright';
|
|
2
|
+
/**
|
|
3
|
+
* Run a function in a headless browser context suited to call Discogs, closing what it opened afterwards.
|
|
4
|
+
* JavaScript is disabled and the User-Agent is the one of the Discogs apps, which Cloudflare lets through.
|
|
5
|
+
* @param browserInstance Browser to use, launched and closed here when not provided
|
|
6
|
+
* @param fn Function to run
|
|
7
|
+
* @returns Result of the function
|
|
8
|
+
*/
|
|
9
|
+
export default function withBrowserContext<T>(browserInstance: Browser | undefined, fn: (browserContext: BrowserContext) => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = withBrowserContext;
|
|
4
|
+
const patchright_1 = require("patchright");
|
|
5
|
+
/**
|
|
6
|
+
* Run a function in a headless browser context suited to call Discogs, closing what it opened afterwards.
|
|
7
|
+
* JavaScript is disabled and the User-Agent is the one of the Discogs apps, which Cloudflare lets through.
|
|
8
|
+
* @param browserInstance Browser to use, launched and closed here when not provided
|
|
9
|
+
* @param fn Function to run
|
|
10
|
+
* @returns Result of the function
|
|
11
|
+
*/
|
|
12
|
+
async function withBrowserContext(browserInstance, fn) {
|
|
13
|
+
const browser = browserInstance ?? (await patchright_1.chromium.launch({ headless: true, chromiumSandbox: false }));
|
|
14
|
+
try {
|
|
15
|
+
const browserContext = await browser.newContext({ javaScriptEnabled: false, userAgent: 'Discogs' });
|
|
16
|
+
try {
|
|
17
|
+
return await fn(browserContext);
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
await browserContext.close();
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
if (!browserInstance) {
|
|
25
|
+
await browser.close();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SearchParams } from '../interfaces/search-params.interface.js';
|
|
2
|
+
import type SearchResult from '../interfaces/search-result.interface.js';
|
|
3
|
+
import type { BrowserContext } from 'patchright';
|
|
4
|
+
/**
|
|
5
|
+
* Searches the listings through the `MarketplaceSearch` GraphQL query of the Discogs shop.
|
|
6
|
+
* @param searchParams Search parameters
|
|
7
|
+
* @param browserContext Patchright browser context
|
|
8
|
+
* @returns Items found, total, next cursor and url of the same search on Discogs
|
|
9
|
+
*/
|
|
10
|
+
export default function scrapeMarketplace({ query, artistIds, labelIds, masterIds, releaseIds, sellerIds, genres, styles, formats, formatDescriptions, mediaConditions, sleeveConditions, from, currencies, priceRange, sellerRatingMin, sellerRatingCountMin, years, isMakeAnOfferOnly, hasItemPhotos, hideGenericSleeves, hideSleevelessMedia, showUnavailable, sort, limit, after, }: SearchParams, browserContext: BrowserContext): Promise<SearchResult>;
|
|
@@ -0,0 +1,292 @@
|
|
|
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 = scrapeMarketplace;
|
|
7
|
+
const country_data_1 = __importDefault(require("../data/country.data.js"));
|
|
8
|
+
const style_data_1 = __importDefault(require("../data/style.data.js"));
|
|
9
|
+
/** Hashes of the persisted GraphQL queries of the Discogs shop */
|
|
10
|
+
const HASHES = {
|
|
11
|
+
MarketplaceSearch: '7ce2bd7801f216b0999648d626c935fc86c8fd85e562529bd87b690c974f08c2',
|
|
12
|
+
Releases: 'ee9d48441023ebd1e6ca169e550581b45de216e88b40711acb6617e49e1bb0cb',
|
|
13
|
+
};
|
|
14
|
+
/** Sort dimensions of the Discogs shop */
|
|
15
|
+
const SORT_DIMENSIONS = {
|
|
16
|
+
listed: 'LISTED_DATE',
|
|
17
|
+
condition: 'MEDIA_CONDITION',
|
|
18
|
+
sleeveCondition: 'SLEEVE_CONDITION',
|
|
19
|
+
artist: 'ARTIST',
|
|
20
|
+
title: 'TITLE',
|
|
21
|
+
year: 'YEAR',
|
|
22
|
+
releaseCountry: 'COUNTRY',
|
|
23
|
+
seller: 'SELLER',
|
|
24
|
+
sellerRating: 'SELLER_RATING',
|
|
25
|
+
sellerRatingCount: 'SELLER_RATING_COUNT',
|
|
26
|
+
shipsFrom: 'SHIPS_FROM',
|
|
27
|
+
price: 'PRICE',
|
|
28
|
+
};
|
|
29
|
+
/** Sort slugs of the Discogs shop url, which does not offer every sort of its API */
|
|
30
|
+
const SORT_SLUGS = {
|
|
31
|
+
listed: 'date-listed',
|
|
32
|
+
condition: 'media-condition',
|
|
33
|
+
artist: 'artist',
|
|
34
|
+
title: 'title',
|
|
35
|
+
seller: 'seller',
|
|
36
|
+
price: 'price',
|
|
37
|
+
};
|
|
38
|
+
/** Conditions as returned by the API, to the labels used everywhere else */
|
|
39
|
+
const CONDITIONS = {
|
|
40
|
+
MINT: 'Mint (M)',
|
|
41
|
+
NEAR_MINT: 'Near Mint (NM or M-)',
|
|
42
|
+
VERY_GOOD_PLUS: 'Very Good Plus (VG+)',
|
|
43
|
+
VERY_GOOD: 'Very Good (VG)',
|
|
44
|
+
GOOD_PLUS: 'Good Plus (G+)',
|
|
45
|
+
GOOD: 'Good (G)',
|
|
46
|
+
FAIR: 'Fair (F)',
|
|
47
|
+
POOR: 'Poor (P)',
|
|
48
|
+
GENERIC: 'Generic',
|
|
49
|
+
NOT_GRADED: 'Not Graded',
|
|
50
|
+
NO_COVER: 'No Cover',
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Run a GraphQL query of the Discogs shop from the page, which must be on the Discogs origin.
|
|
54
|
+
* @param page Page
|
|
55
|
+
* @param operationName Name of the persisted query
|
|
56
|
+
* @param variables Variables
|
|
57
|
+
* @returns Response
|
|
58
|
+
*/
|
|
59
|
+
async function queryGraphql(page, operationName, variables) {
|
|
60
|
+
const { status, json } = await page.evaluate(async (body) => {
|
|
61
|
+
const res = await fetch('/graphql', {
|
|
62
|
+
method: 'POST',
|
|
63
|
+
headers: { 'Content-Type': 'application/json' },
|
|
64
|
+
body: JSON.stringify(body),
|
|
65
|
+
});
|
|
66
|
+
return { status: res.status, json: (await res.json().catch(() => null)) };
|
|
67
|
+
}, { operationName, variables, extensions: { persistedQuery: { version: 1, sha256Hash: HASHES[operationName] } } });
|
|
68
|
+
const result = json;
|
|
69
|
+
if (!result?.data) {
|
|
70
|
+
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
71
|
+
throw new Error(result?.errors?.map(x => x.message).join(', ') || `An error ${status} occurred.`);
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Format a price as a string combining amount and currency
|
|
77
|
+
* @param price Price
|
|
78
|
+
* @param price.amount Amount
|
|
79
|
+
* @param price.currency Currency
|
|
80
|
+
* @returns Price
|
|
81
|
+
*/
|
|
82
|
+
function formatPrice(price) {
|
|
83
|
+
return `${price?.currency === 'JPY' ? (price.amount ?? 0) : (price?.amount ?? 0).toFixed(2)} ${price?.currency ?? ''}`;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Get a condition from the value returned by the API
|
|
87
|
+
* @param value Value
|
|
88
|
+
* @returns Condition
|
|
89
|
+
*/
|
|
90
|
+
function toCondition(value) {
|
|
91
|
+
const full = value ? (CONDITIONS[value] ?? value) : null;
|
|
92
|
+
return { full, short: /\(([^)]+)\)/.exec(full ?? '')?.[1] ?? null };
|
|
93
|
+
}
|
|
94
|
+
/** HTML entities the notes of the sellers can hold, besides the numeric ones */
|
|
95
|
+
const HTML_ENTITIES = { quot: '"', apos: "'", lt: '<', gt: '>', nbsp: '\u00a0' }; // cspell: disable-line
|
|
96
|
+
/**
|
|
97
|
+
* Decode the HTML entities of a text, as the notes of the sellers come HTML escaped
|
|
98
|
+
* @param text Text
|
|
99
|
+
* @returns Decoded text
|
|
100
|
+
*/
|
|
101
|
+
function decodeHtmlEntities(text) {
|
|
102
|
+
return text
|
|
103
|
+
.replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)))
|
|
104
|
+
.replace(/&#x([\da-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16)))
|
|
105
|
+
.replace(new RegExp(`&(${Object.keys(HTML_ENTITIES).join('|')});`, 'g'), (_, name) => HTML_ENTITIES[name] ?? '')
|
|
106
|
+
.replace(/&/g, '&');
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Searches the listings through the `MarketplaceSearch` GraphQL query of the Discogs shop.
|
|
110
|
+
* @param searchParams Search parameters
|
|
111
|
+
* @param browserContext Patchright browser context
|
|
112
|
+
* @returns Items found, total, next cursor and url of the same search on Discogs
|
|
113
|
+
*/
|
|
114
|
+
async function scrapeMarketplace({ query, artistIds, labelIds, masterIds, releaseIds, sellerIds, genres, styles, formats, formatDescriptions, mediaConditions, sleeveConditions, from, currencies, priceRange, sellerRatingMin, sellerRatingCountMin, years, isMakeAnOfferOnly = false, hasItemPhotos = false, hideGenericSleeves = false, hideSleevelessMedia = false, showUnavailable = true, sort = 'listed,desc', limit = 25, after, }, browserContext) {
|
|
115
|
+
const [sortField = 'listed', sortOrder = 'desc'] = sort.split(',');
|
|
116
|
+
const countries = from?.flatMap(code => {
|
|
117
|
+
const names = Object.keys(country_data_1.default).filter(key => code === country_data_1.default[key]);
|
|
118
|
+
return names.length ? names : [code];
|
|
119
|
+
});
|
|
120
|
+
const styleIds = styles?.flatMap(name => {
|
|
121
|
+
const ids = style_data_1.default[name];
|
|
122
|
+
return ids ? [ids] : [];
|
|
123
|
+
}) ?? [];
|
|
124
|
+
/** Url of the same search on the Discogs shop */
|
|
125
|
+
const urlGenerated = [
|
|
126
|
+
'https://www.discogs.com/shop/list',
|
|
127
|
+
new URLSearchParams([
|
|
128
|
+
['q', query ?? ''],
|
|
129
|
+
...(artistIds?.map(x => ['artist', x.toString()]) ?? []),
|
|
130
|
+
...(labelIds?.map(x => ['label', x.toString()]) ?? []),
|
|
131
|
+
...(masterIds?.map(x => ['master', x.toString()]) ?? []),
|
|
132
|
+
...(releaseIds?.map(x => ['release', x.toString()]) ?? []),
|
|
133
|
+
...(sellerIds?.map(x => ['seller', x.toString()]) ?? []),
|
|
134
|
+
...(genres?.map(x => ['genre', x]) ?? []),
|
|
135
|
+
...(styles?.map(x => ['style', x]) ?? []),
|
|
136
|
+
...(formats?.map(x => ['formatName', x]) ?? []),
|
|
137
|
+
...(formatDescriptions?.map(x => ['formatDescription', x]) ?? []),
|
|
138
|
+
...(mediaConditions?.map(x => ['mediaCondition', x]) ?? []),
|
|
139
|
+
...(sleeveConditions?.map(x => ['sleeveCondition', x]) ?? []),
|
|
140
|
+
...(countries?.map(x => ['shipsFrom', x]) ?? []),
|
|
141
|
+
['priceMin', priceRange?.min.toString() ?? ''],
|
|
142
|
+
['priceMax', priceRange?.max.toString() ?? ''],
|
|
143
|
+
['year', years?.min.toString() ?? ''],
|
|
144
|
+
['year', years?.max.toString() ?? ''],
|
|
145
|
+
['allowsOffers', isMakeAnOfferOnly ? 'true' : ''],
|
|
146
|
+
['hasItemPhotos', hasItemPhotos ? 'true' : ''],
|
|
147
|
+
['hideGenericSleeves', hideGenericSleeves ? 'true' : ''],
|
|
148
|
+
['hideSleevelessMedia', hideSleevelessMedia ? 'true' : ''],
|
|
149
|
+
['showUnavailable', showUnavailable ? 'true' : ''],
|
|
150
|
+
...(SORT_SLUGS[sortField]
|
|
151
|
+
? [
|
|
152
|
+
['sort', SORT_SLUGS[sortField]],
|
|
153
|
+
['sortOrder', sortOrder === 'asc' ? 'ascending' : 'descending'],
|
|
154
|
+
]
|
|
155
|
+
: []),
|
|
156
|
+
['size', limit.toString()],
|
|
157
|
+
['after', after ?? ''],
|
|
158
|
+
].filter(([, x]) => !!x)).toString(),
|
|
159
|
+
].join('?');
|
|
160
|
+
const browserPage = await browserContext.newPage();
|
|
161
|
+
try {
|
|
162
|
+
// The API can only be called from the Discogs origin: go there through its lightest page
|
|
163
|
+
await browserPage.goto('https://www.discogs.com/robots.txt', { waitUntil: 'commit' });
|
|
164
|
+
const filter = Object.fromEntries(Object.entries({
|
|
165
|
+
artist: artistIds,
|
|
166
|
+
label: labelIds,
|
|
167
|
+
master: masterIds,
|
|
168
|
+
release: releaseIds,
|
|
169
|
+
seller: sellerIds,
|
|
170
|
+
genre: genres,
|
|
171
|
+
genreAnd: genres?.length ? true : undefined,
|
|
172
|
+
styleId: styleIds.length ? [...new Set(styleIds.flat())] : undefined,
|
|
173
|
+
styleIdAnd: styleIds.length ? styleIds.every(x => x.length === 1) : undefined,
|
|
174
|
+
formatName: formats,
|
|
175
|
+
formatNameAnd: formats?.length ? true : undefined,
|
|
176
|
+
formatDescription: formatDescriptions,
|
|
177
|
+
formatDescriptionAnd: formatDescriptions?.length ? true : undefined,
|
|
178
|
+
mediaCondition: mediaConditions,
|
|
179
|
+
sleeveCondition: sleeveConditions,
|
|
180
|
+
shipsFrom: countries,
|
|
181
|
+
currency: currencies,
|
|
182
|
+
sellerRatingMin,
|
|
183
|
+
sellerRatingCountMin,
|
|
184
|
+
priceRangeLow: priceRange?.min,
|
|
185
|
+
priceRangeHigh: priceRange?.max,
|
|
186
|
+
yearRangeLow: years?.min,
|
|
187
|
+
yearRangeHigh: years?.max,
|
|
188
|
+
allowsOffers: isMakeAnOfferOnly || undefined,
|
|
189
|
+
hasInventoryImages: hasItemPhotos || undefined,
|
|
190
|
+
hideGenericSleeves: hideGenericSleeves || undefined,
|
|
191
|
+
hideSleevelessMedia: hideSleevelessMedia || undefined,
|
|
192
|
+
showUnavailable: showUnavailable || undefined,
|
|
193
|
+
}).filter(([, x]) => x !== undefined && !(Array.isArray(x) && !x.length)));
|
|
194
|
+
const result = (await queryGraphql(browserPage, 'MarketplaceSearch', {
|
|
195
|
+
query: query || undefined, // eslint-disable-line @typescript-eslint/prefer-nullish-coalescing
|
|
196
|
+
filter: Object.keys(filter).length ? filter : undefined,
|
|
197
|
+
sort: {
|
|
198
|
+
dimension: SORT_DIMENSIONS[sortField] ?? SORT_DIMENSIONS.listed,
|
|
199
|
+
direction: sortOrder === 'asc' ? 'ASCENDING' : 'DESCENDING',
|
|
200
|
+
},
|
|
201
|
+
first: limit,
|
|
202
|
+
after,
|
|
203
|
+
})).data?.marketplaceSearch;
|
|
204
|
+
const nodes = result?.edges?.map(x => x.node ?? {}) ?? [];
|
|
205
|
+
const releaseIdsFound = [...new Set(nodes.map(x => x.release?.discogsId ?? 0).filter(x => !!x))];
|
|
206
|
+
const { data: details } = releaseIdsFound.length
|
|
207
|
+
? // The community stats and the rating of the releases are not part of the listings
|
|
208
|
+
await queryGraphql(browserPage, 'Releases', { discogsIds: releaseIdsFound, first: 1 })
|
|
209
|
+
: { data: undefined };
|
|
210
|
+
const releaseDetails = new Map(details?.releases?.map(x => [x?.discogsId ?? 0, x]) ?? []);
|
|
211
|
+
const items = nodes.map(node => {
|
|
212
|
+
const release = node.release ?? {};
|
|
213
|
+
const artists = release.primaryArtists ?? [];
|
|
214
|
+
const labels = (release.labels ?? []).filter(x => x.labelRole === 'LABEL');
|
|
215
|
+
const description = release.formatSummary?.description;
|
|
216
|
+
const media = toCondition(node.mediaCondition);
|
|
217
|
+
const releaseDetail = releaseDetails.get(release.discogsId ?? 0);
|
|
218
|
+
const year = Number(release.released?.slice(0, 4));
|
|
219
|
+
return {
|
|
220
|
+
id: Number(node.id),
|
|
221
|
+
title: `${artists.map(x => x.displayName ?? '').join(', ')} - ${release.title ?? ''} (${release.formatSummary?.primaryFormat ?? ''})`,
|
|
222
|
+
artists: artists.map(x => ({
|
|
223
|
+
id: x.artist?.discogsId ?? null,
|
|
224
|
+
name: x.displayName ?? '',
|
|
225
|
+
url: x.artist?.discogsId ? `https://www.discogs.com/artist/${x.artist.discogsId}` : null,
|
|
226
|
+
})),
|
|
227
|
+
release: {
|
|
228
|
+
id: release.discogsId ?? 0,
|
|
229
|
+
name: release.title ?? '',
|
|
230
|
+
url: `https://www.discogs.com/release/${release.discogsId ?? 0}`,
|
|
231
|
+
year: year || null,
|
|
232
|
+
country: release.country ?? null,
|
|
233
|
+
rating: releaseDetail?.ratings?.averageRating || null, // eslint-disable-line @typescript-eslint/prefer-nullish-coalescing
|
|
234
|
+
},
|
|
235
|
+
formats: [
|
|
236
|
+
...new Set([
|
|
237
|
+
release.formatSummary?.primaryFormat,
|
|
238
|
+
...(release.formatSummary?.recordingTypes ?? []),
|
|
239
|
+
...(Array.isArray(description) ? description : (description?.split(', ') ?? [])),
|
|
240
|
+
].filter((x) => !!x)),
|
|
241
|
+
],
|
|
242
|
+
labels: labels.map(x => ({
|
|
243
|
+
id: x.label?.discogsId ?? 0,
|
|
244
|
+
name: x.label?.name ?? '',
|
|
245
|
+
url: `https://www.discogs.com/label/${x.label?.discogsId ?? 0}`,
|
|
246
|
+
})),
|
|
247
|
+
url: `https://www.discogs.com/shop/item/${node.id ?? ''}`,
|
|
248
|
+
listedAt: node.listedDate ? new Date(node.listedDate) : null,
|
|
249
|
+
catnos: labels.map(x => x.catalogNumber ?? '').filter(x => !!x),
|
|
250
|
+
imageUrl: release.images?.edges?.[0]?.node?.thumbnail?.webpUrl ?? null,
|
|
251
|
+
photos: [...(node.itemPhotos ?? [])].sort((a, b) => (a.position ?? 0) - (b.position ?? 0)).map(x => x.url ?? ''),
|
|
252
|
+
description: node.publicNotes ? decodeHtmlEntities(node.publicNotes) : null,
|
|
253
|
+
isAcceptingOffer: node.offerOk ?? false,
|
|
254
|
+
isAvailable: node.availability?.isAvailable ?? true,
|
|
255
|
+
condition: {
|
|
256
|
+
media: { full: media.full ?? '', short: media.short ?? '' },
|
|
257
|
+
sleeve: toCondition(node.sleeveCondition),
|
|
258
|
+
},
|
|
259
|
+
seller: {
|
|
260
|
+
id: node.seller?.discogsId ?? 0,
|
|
261
|
+
name: node.seller?.username ?? '',
|
|
262
|
+
url: `https://www.discogs.com/seller/${node.seller?.username ?? ''}/profile`,
|
|
263
|
+
score: node.sellerInfo?.rating ? `${node.sellerInfo.rating.toFixed(1)}%` : null,
|
|
264
|
+
notes: node.sellerInfo?.ratingCount ?? null,
|
|
265
|
+
isIndependent: node.sellerInfo?.independentSeller ?? false,
|
|
266
|
+
},
|
|
267
|
+
price: {
|
|
268
|
+
base: formatPrice(node.price),
|
|
269
|
+
shipping: node.shipping?.price ? formatPrice(node.shipping.price) : null,
|
|
270
|
+
},
|
|
271
|
+
country: {
|
|
272
|
+
name: node.sellerInfo?.shipsFrom ?? '',
|
|
273
|
+
code: country_data_1.default[node.sellerInfo?.shipsFrom],
|
|
274
|
+
},
|
|
275
|
+
community: {
|
|
276
|
+
have: releaseDetail?.inCollectionCount ?? 0,
|
|
277
|
+
want: releaseDetail?.inWantlistCount ?? 0,
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
});
|
|
281
|
+
return {
|
|
282
|
+
items,
|
|
283
|
+
total: result?.totalCount ?? 0,
|
|
284
|
+
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
285
|
+
nextCursor: (result?.pageInfo?.hasNextPage && result.pageInfo.endCursor) || null,
|
|
286
|
+
urlGenerated,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
finally {
|
|
290
|
+
await browserPage.close();
|
|
291
|
+
}
|
|
292
|
+
}
|
package/dist/search.d.ts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
import type { SearchParams } from 'interfaces/search-params.interface';
|
|
2
|
-
import type SearchResult from 'interfaces/search-result.interface';
|
|
3
|
-
import type { Browser } from '
|
|
4
|
-
export declare const DEFAULT_LIMIT = 25;
|
|
5
|
-
export declare const DEFAULT_PAGE = 1;
|
|
6
|
-
export declare const DEFAULT_SORT = "listed,desc";
|
|
1
|
+
import type { SearchParams } from './interfaces/search-params.interface.js';
|
|
2
|
+
import type SearchResult from './interfaces/search-result.interface.js';
|
|
3
|
+
import type { Browser } from 'patchright';
|
|
7
4
|
/**
|
|
8
5
|
* Performs a search on the Discogs marketplace using the provided parameters.
|
|
9
|
-
* @param searchParams - The search parameters, including
|
|
10
|
-
* @param browserInstance - Optional
|
|
11
|
-
* @returns A promise that resolves to the search results, including items,
|
|
6
|
+
* @param searchParams - The search parameters, including query, pagination, and filters.
|
|
7
|
+
* @param browserInstance - Optional Patchright browser instance. If provided, you must manage its lifecycle.
|
|
8
|
+
* @returns A promise that resolves to the search results, including items, total, next cursor and the generated URL.
|
|
12
9
|
*/
|
|
13
10
|
export default function search(searchParams: SearchParams, browserInstance?: Browser): Promise<SearchResult>;
|
package/dist/search.js
CHANGED
|
@@ -3,67 +3,20 @@ 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;
|
|
7
6
|
exports.default = search;
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
const modern_scraper_1 = __importDefault(require("scrapers/modern.scraper"));
|
|
13
|
-
exports.DEFAULT_LIMIT = 25;
|
|
14
|
-
exports.DEFAULT_PAGE = 1;
|
|
15
|
-
exports.DEFAULT_SORT = 'listed,desc';
|
|
7
|
+
const browser_context_1 = __importDefault(require("./scrapers/browser-context.js"));
|
|
8
|
+
const marketplace_scraper_1 = __importDefault(require("./scrapers/marketplace.scraper.js"));
|
|
9
|
+
/** Release IDs a single search can filter on at most */
|
|
10
|
+
const MAX_RELEASE_IDS = 2000;
|
|
16
11
|
/**
|
|
17
12
|
* Performs a search on the Discogs marketplace using the provided parameters.
|
|
18
|
-
* @param searchParams - The search parameters, including
|
|
19
|
-
* @param browserInstance - Optional
|
|
20
|
-
* @returns A promise that resolves to the search results, including items,
|
|
13
|
+
* @param searchParams - The search parameters, including query, pagination, and filters.
|
|
14
|
+
* @param browserInstance - Optional Patchright browser instance. If provided, you must manage its lifecycle.
|
|
15
|
+
* @returns A promise that resolves to the search results, including items, total, next cursor and the generated URL.
|
|
21
16
|
*/
|
|
22
17
|
async function search(searchParams, browserInstance) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
playwright_extra_1.chromium.use((0, puppeteer_extra_plugin_stealth_1.default)());
|
|
26
|
-
return playwright_extra_1.chromium.launch({
|
|
27
|
-
headless: true,
|
|
28
|
-
chromiumSandbox: false,
|
|
29
|
-
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
|
30
|
-
});
|
|
31
|
-
})());
|
|
32
|
-
const browserContext = await browser.newContext({
|
|
33
|
-
javaScriptEnabled: false,
|
|
34
|
-
extraHTTPHeaders: searchParams.api === 'legacy' && !(searchParams.seller && searchParams.user)
|
|
35
|
-
? {
|
|
36
|
-
'X-PJAX': 'true',
|
|
37
|
-
}
|
|
38
|
-
: undefined,
|
|
39
|
-
});
|
|
40
|
-
try {
|
|
41
|
-
const { items, total, urlGenerated } = await (() => {
|
|
42
|
-
if (searchParams.api === 'v2' && searchParams.wantlist) {
|
|
43
|
-
return (0, wantlist_scraper_1.default)(searchParams, browserContext);
|
|
44
|
-
}
|
|
45
|
-
if (searchParams.api === 'v2') {
|
|
46
|
-
return (0, modern_scraper_1.default)(searchParams, browserContext);
|
|
47
|
-
}
|
|
48
|
-
return (0, legacy_scraper_1.default)(searchParams, browserContext);
|
|
49
|
-
})();
|
|
50
|
-
return {
|
|
51
|
-
items,
|
|
52
|
-
result: {
|
|
53
|
-
total,
|
|
54
|
-
perPage: searchParams.limit ?? exports.DEFAULT_LIMIT,
|
|
55
|
-
},
|
|
56
|
-
page: {
|
|
57
|
-
current: searchParams.page ?? exports.DEFAULT_PAGE,
|
|
58
|
-
total: Math.ceil(total / (searchParams.limit ?? exports.DEFAULT_LIMIT)),
|
|
59
|
-
},
|
|
60
|
-
urlGenerated,
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
finally {
|
|
64
|
-
await browserContext.close();
|
|
65
|
-
if (!browserInstance) {
|
|
66
|
-
await browser.close();
|
|
67
|
-
}
|
|
18
|
+
if ((searchParams.releaseIds?.length ?? 0) > MAX_RELEASE_IDS) {
|
|
19
|
+
throw new Error(`At most ${MAX_RELEASE_IDS} release IDs are supported.`);
|
|
68
20
|
}
|
|
21
|
+
return (0, browser_context_1.default)(browserInstance, browserContext => (0, marketplace_scraper_1.default)(searchParams, browserContext));
|
|
69
22
|
}
|
|
@@ -2,3 +2,7 @@
|
|
|
2
2
|
* Conditions
|
|
3
3
|
*/
|
|
4
4
|
export type Condition = '0' | 'Fair (F)' | 'Good (G)' | 'Good Plus (G+)' | 'Mint (M)' | 'Near Mint (NM or M-)' | 'Poor (P)' | 'Very Good (VG)' | 'Very Good Plus (VG+)' | ({} & string);
|
|
5
|
+
/**
|
|
6
|
+
* Sleeve conditions
|
|
7
|
+
*/
|
|
8
|
+
export type SleeveCondition = Condition | 'Generic' | 'No Cover' | 'Not Graded';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* FormatDescriptions
|
|
3
3
|
*/
|
|
4
|
-
export type FormatDescription = '1 ⅞ ips' | '1"' | '10"' | '10.5" NAB Reel' | '11"' | '12"' | '15 ips' | '15/16 ips' | '16 ⅔ RPM' | '16"' | '16mm' | '2 Minute' | '2"' | '2-Track Mono' | '2-Track Stereo' | '21cm' | '25cm' | '27cm' | '29cm' | '3 Minute' | '3 ¾ ips' | '3"' | '3" Cine Reel' | '3.5"' | '30 ips' | '33 ⅓ RPM' | '35cm' | '35mm' | '3½"' | '4 Minute' | '4"' | '4-Track Mono' | '4-Track Stereo' | '45 RPM' | '4K' | '5"' | '5" Cine Reel' | '5.25"' | '50cm' | '5½"' | '6"' | '6" Cine Reel' | '6½"' | '7 ½ ips' | '7"' | '7" Cine Reel' | '78 RPM' | '8 ⅓ RPM' | '8"' | '80 RPM' | '8K' | '9"' | '90 RPM' | 'AAC' | 'AIFC' | 'AIFF' | 'ALAC' | 'AMR' | 'APE' | 'AVCD' | 'AVI' | 'Advance' | 'Album' | 'Ambisonic' | 'Bioplastic' | 'Blu-ray Audio' | 'Business Card' | 'CD+G' | 'CD-ROM' | 'CD-Record' | 'CDi' | 'Card Backed' | 'Club Edition' | 'Compilation' | 'Concert' | 'Copy Protected' | 'DFF' | 'DSF' | 'DVD-Audio' | 'DVD-Data' | 'DVD-Video' | 'DVDplus' | 'Deluxe Edition' | 'Disc Image' | 'Double Sided' | 'DualDisc' | 'EP' | 'Enhanced' | 'Etched' | 'FLAC' | 'FLV' | 'HDCD' | 'Hybrid' | 'Jukebox' | 'LP' | 'Limited Edition' | 'MOV' | 'MP2' | 'MP3' | 'MP3 Surround' | 'MPEG Video' | 'MPEG-4 Video' | 'Maxi-Single' | 'Mini' | 'Mini-Album' | 'Minimax' | 'Mispress' | 'Misprint' | 'Mixed' | 'Mixtape' | 'Mono' | 'Multichannel' | 'NTSC' | 'Numbered' | 'Opus' | 'PAL' | 'Partially Mixed' | 'Partially Unofficial' | 'Picture Disc' | 'Promo' | 'Quadraphonic' | 'RA' | 'RM' | 'Reissue' | 'Remastered' | 'Repress' | 'SECAM' | 'SHN' | 'SVCD' | 'SWF' | 'Salon' | 'Sampler' | 'Shape' | 'Single' | 'Single Sided' | 'Special Edition' | 'Stereo' | 'Styrene' | 'TTA' | 'Test Pressing' | 'Transcription' | 'Unofficial Release' | 'VCD' | 'VinylDisc' | 'WAV' | 'WMA' | 'WMV' | 'WavPack' | 'White Label' | 'XRCD' | 'ogg-vorbis' | '¼"' | '½"' | '⅛"' | ({} & string);
|
|
4
|
+
export type FormatDescription = '1 ⅞ ips' | '1"' | '10"' | '10.5" NAB Reel' | '11"' | '12"' | '15 ips' | '15/16 ips' | '16 ⅔ RPM' | '16"' | '16mm' | '2 Minute' | '2"' | '2-Track Mono' | '2-Track Stereo' | '21cm' | '25cm' | '27cm' | '29cm' | '3 Minute' | '3 ¾ ips' | '3"' | '3" Cine Reel' | '3.5"' | '30 ips' | '33 ⅓ RPM' | '35cm' | '35mm' | '3½"' | '4 Minute' | '4"' | '4-Track Mono' | '4-Track Stereo' | '45 RPM' | '4K' | '5"' | '5" Cine Reel' | '5.25"' | '50cm' | '5½"' | '6"' | '6" Cine Reel' | '6½"' | '7 ½ ips' | '7"' | '7" Cine Reel' | '78 RPM' | '8 ⅓ RPM' | '8"' | '80 RPM' | '8K' | '9"' | '90 RPM' | 'AAC' | 'AIFC' | 'AIFF' | 'ALAC' | 'AMR' | 'APE' | 'AVCD' | 'AVI' | 'Advance' | 'Album' | 'Ambisonic' | 'Bioplastic' | 'Blu-ray Audio' | 'Business Card' | 'CD+G' | 'CD-ROM' | 'CD-Record' | 'CDi' | 'Card Backed' | 'Club Edition' | 'Compilation' | 'Concert' | 'Copy Protected' | 'DFF' | 'DSF' | 'DVD-Audio' | 'DVD-Data' | 'DVD-Video' | 'DVDplus' | 'Deluxe Edition' | 'Disc Image' | 'Double Sided' | 'DualDisc' | 'EP' | 'Enhanced' | 'Etched' | 'FLAC' | 'FLV' | 'HDCD' | 'Hybrid' | 'Jukebox' | 'LP' | 'Limited Edition' | 'MOV' | 'MP2' | 'MP3' | 'MP3 Surround' | 'MPEG Video' | 'MPEG-4 Video' | 'Maxi-Single' | 'Mini' | 'Mini-Album' | 'Minimax' | 'Mispress' | 'Misprint' | 'Mixed' | 'Mixtape' | 'Mono' | 'Multichannel' | 'NTSC' | 'Numbered' | 'Opus' | 'PAL' | 'Partially Mixed' | 'Partially Unofficial' | 'Picture Disc' | 'Promo' | 'Quadraphonic' | 'RA' | 'RM' | 'Record Store Day' | 'Reissue' | 'Remastered' | 'Repress' | 'SECAM' | 'SHN' | 'SVCD' | 'SWF' | 'Salon' | 'Sampler' | 'Shape' | 'Single' | 'Single Sided' | 'Special Cut' | 'Special Edition' | 'Stereo' | 'Styrene' | 'TTA' | 'Test Pressing' | 'Tour Recording' | 'Transcription' | 'Unofficial Release' | 'VCD' | 'VinylDisc' | 'WAV' | 'WMA' | 'WMV' | 'WavPack' | 'White Label' | 'XRCD' | 'ogg-vorbis' | '¼"' | '½"' | '⅛"' | ({} & string);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
type SortField = 'listed' | 'condition' | 'artist' | 'title' | '
|
|
1
|
+
type SortField = 'listed' | 'condition' | 'sleeveCondition' | 'artist' | 'title' | 'year' | 'releaseCountry' | 'seller' | 'sellerRating' | 'sellerRatingCount' | 'shipsFrom' | 'price';
|
|
2
2
|
type SortDirection = 'asc' | 'desc';
|
|
3
3
|
/**
|
|
4
4
|
* Sorts
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import type { StyleKeys } from '../data/style.data.js';
|
|
1
2
|
/**
|
|
2
3
|
* Styles
|
|
3
4
|
*/
|
|
4
|
-
export type Style =
|
|
5
|
+
export type Style = StyleKeys | ({} & string);
|