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.
Files changed (47) hide show
  1. package/README.MD +111 -151
  2. package/dist/data/country.data.d.ts +1 -1
  3. package/dist/data/style.data.d.ts +763 -0
  4. package/dist/data/style.data.js +765 -0
  5. package/dist/index.d.ts +7 -4
  6. package/dist/index.js +3 -2
  7. package/dist/interfaces/api/marketplace-search-result.api.interface.d.ts +148 -0
  8. package/dist/interfaces/api/{shop-details-result.api.interface.d.ts → releases-result.api.interface.d.ts} +4 -1
  9. package/dist/interfaces/api/wantlist-result.api.interface.d.ts +109 -0
  10. package/dist/interfaces/search-params.interface.d.ts +83 -163
  11. package/dist/interfaces/search-result.interface.d.ts +22 -20
  12. package/dist/scrapers/browser-context.d.ts +9 -0
  13. package/dist/scrapers/browser-context.js +28 -0
  14. package/dist/scrapers/marketplace.scraper.d.ts +10 -0
  15. package/dist/scrapers/marketplace.scraper.js +292 -0
  16. package/dist/search.d.ts +6 -9
  17. package/dist/search.js +10 -57
  18. package/dist/types/condition.type.d.ts +4 -0
  19. package/dist/types/currency.type.d.ts +1 -1
  20. package/dist/types/format-description.type.d.ts +1 -1
  21. package/dist/types/from.type.d.ts +1 -1
  22. package/dist/types/sort.type.d.ts +1 -1
  23. package/dist/types/style.type.d.ts +2 -1
  24. package/dist/wantlist.d.ts +28 -0
  25. package/dist/wantlist.js +101 -0
  26. package/package.json +16 -18
  27. package/dist/data/currency.data.d.ts +0 -36
  28. package/dist/data/currency.data.js +0 -35
  29. package/dist/interfaces/api/shop-result-error.api.interface.d.ts +0 -8
  30. package/dist/interfaces/api/shop-result.api.interface.d.ts +0 -111
  31. package/dist/scrapers/extractors/legacy.extractor.d.ts +0 -11
  32. package/dist/scrapers/extractors/legacy.extractor.js +0 -138
  33. package/dist/scrapers/legacy.scraper.d.ts +0 -13
  34. package/dist/scrapers/legacy.scraper.js +0 -75
  35. package/dist/scrapers/modern.scraper.d.ts +0 -13
  36. package/dist/scrapers/modern.scraper.js +0 -199
  37. package/dist/scrapers/wantlist.scraper.d.ts +0 -13
  38. package/dist/scrapers/wantlist.scraper.js +0 -66
  39. package/dist/types/api.type.d.ts +0 -4
  40. package/dist/types/api.type.js +0 -2
  41. package/dist/types/lang.type.d.ts +0 -4
  42. package/dist/types/lang.type.js +0 -2
  43. package/dist/types/limit.type.d.ts +0 -4
  44. package/dist/types/limit.type.js +0 -2
  45. /package/dist/interfaces/api/{shop-details-result.api.interface.js → marketplace-search-result.api.interface.js} +0 -0
  46. /package/dist/interfaces/api/{shop-result-error.api.interface.js → releases-result.api.interface.js} +0 -0
  47. /package/dist/interfaces/api/{shop-result.api.interface.js → wantlist-result.api.interface.js} +0 -0
@@ -1,199 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = scrape;
7
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
8
- const country_data_1 = __importDefault(require("data/country.data"));
9
- const search_1 = require("search");
10
- /**
11
- * Parses the page and returns the items found.
12
- * @param SearchParams Search parameters
13
- * @param browserContext Playwright browser context
14
- * @returns Items found and total
15
- */
16
- 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, hideGenericSleeves = false, hideSleevelessMedia = false, showUnavailable = true, sellerRatingCountMin = 0, }, browserContext) {
17
- const [sortType, sortOrder] = sort.split(',');
18
- const urlGenerated = [
19
- 'https://www.discogs.com/api/shop-page-api/sell_item',
20
- new URLSearchParams([
21
- ['sellerRatingMin', sellerRatingMin.toString()],
22
- ['hideGenericSleeves', hideGenericSleeves.toString()],
23
- ['hideSleevelessMedia', hideSleevelessMedia.toString()],
24
- ['showUnavailable', showUnavailable.toString()],
25
- ['sellerRatingCountMin', sellerRatingCountMin.toString()],
26
- [
27
- 'sort',
28
- {
29
- listed: 'listedDate',
30
- condition: 'mediaCondition',
31
- artist: 'artist',
32
- title: 'title',
33
- seller: 'seller',
34
- price: 'price',
35
- }[sortType] ?? 'listedDate',
36
- ],
37
- [
38
- 'sortOrder',
39
- {
40
- asc: 'ascending',
41
- desc: 'descending',
42
- }[sortOrder] ?? 'ascending',
43
- ],
44
- ['count', limit.toString()],
45
- ['offset', ((page - 1) * limit).toString()],
46
- ...(releaseIds?.map(r => ['release', r.toString()]) ?? []),
47
- ...(from?.map(f => Object.keys(country_data_1.default).find(key => f === country_data_1.default[key]) ?? '') ?? []).map(f => [
48
- 'shipsFrom',
49
- f,
50
- ]),
51
- ...(formats?.map(f => ['formatName', f]) ?? []),
52
- ...(formatDescriptions?.map(fd => ['formatDescription', fd]) ?? []),
53
- ...(conditions?.map(c => ['sleeveCondition', c]) ?? []),
54
- ...(conditions?.map(c => ['mediaCondition', c]) ?? []),
55
- ...(currencies?.map(c => ['currency', c]) ?? []),
56
- ...(genres?.map(g => ['genre', g]) ?? []),
57
- ...(sellerIds?.map(s => ['seller', s.toString()]) ?? []),
58
- ...(artistIds?.map(a => ['artist', a.toString()]) ?? []),
59
- ['allowsOffers', isMakeAnOfferOnly ? 'true' : ''],
60
- ['yearRangeLow', years?.min.toString() ?? ''],
61
- ['yearRangeHigh', years?.max.toString() ?? ''],
62
- ['priceRangeLow', priceRange?.min.toString() ?? ''],
63
- ['priceRangeHigh', priceRange?.max.toString() ?? ''],
64
- ].filter(([, p]) => !!p)).toString(),
65
- ].join('?');
66
- const browserPage = await browserContext.newPage();
67
- await browserPage.goto('https://www.discogs.com/shop/mywants', { waitUntil: 'commit' });
68
- await browserPage.setExtraHTTPHeaders({
69
- 'User-Agent': 'Discogs',
70
- Accept: 'application/json',
71
- 'Accept-Language': 'en-US,en;q=0.9,fr-FR;q=0.8',
72
- Referer: 'https://www.discogs.com/shop/mywants',
73
- });
74
- const response = await browserPage.goto(urlGenerated, { waitUntil: 'domcontentloaded' });
75
- if (!response?.ok()) {
76
- const message = response?.headers()['content-type']?.includes('application/json')
77
- ? (await response.json())?.detail
78
- : '';
79
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
80
- throw new Error(message || `An error ${response?.status() ?? '?'} occurred.`);
81
- }
82
- const result = (await response.json());
83
- const { json: detailsResult, ...detailsResponse } = await browserPage.evaluate(async (discogsIds = [0]) => {
84
- const res = await fetch('https://www.discogs.com/graphql', {
85
- method: 'POST',
86
- headers: {
87
- 'User-Agent': 'Discogs',
88
- 'Content-Type': 'application/json',
89
- Host: 'www.discogs.com',
90
- Accept: '*/*',
91
- 'Accept-Language': 'en-US,en;q=0.9,fr-FR;q=0.8',
92
- 'Accept-Encoding': 'gzip, deflate, br, zstd',
93
- Referer: 'https://www.discogs.com/shop/mywants',
94
- Origin: 'https://www.discogs.com',
95
- 'Alt-Used': 'www.discogs.com',
96
- Connection: 'keep-alive',
97
- 'Sec-Fetch-Dest': 'empty',
98
- 'Sec-Fetch-Mode': 'cors',
99
- 'Sec-Fetch-Site': 'same-origin',
100
- Priority: 'u=4',
101
- TE: 'trailers',
102
- },
103
- body: JSON.stringify({
104
- // eslint-disable-next-line max-len
105
- 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}',
106
- variables: { discogsIds, first: 1 },
107
- extensions: {
108
- persistedQuery: { version: 1, sha256Hash: 'ee9d48441023ebd1e6ca169e550581b45de216e88b40711acb6617e49e1bb0cb' },
109
- },
110
- }),
111
- });
112
- return {
113
- ok: res.ok,
114
- status: res.status,
115
- json: (await res.json().catch(() => ({}))),
116
- };
117
- }, result.items?.map(z => z.release?.releaseId ?? 0).filter((x, i, self) => x && self.indexOf(x) === i));
118
- await browserPage.close();
119
- if (!detailsResponse.ok) {
120
- throw new Error(`An error ${detailsResponse.status} occurred.`);
121
- }
122
- const details = Object.fromEntries(detailsResult.data?.releases?.map(release => {
123
- if (!release?.discogsId) {
124
- return [0, { imageUrl: null, want: 0, have: 0 }];
125
- }
126
- return [
127
- release.discogsId ?? 0,
128
- {
129
- imageUrl: release.images?.edges?.[0]?.node?.thumbnail?.webpUrl ?? null,
130
- want: release.inWantlistCount ?? 0,
131
- have: release.inCollectionCount ?? 0,
132
- },
133
- ];
134
- }) ?? []);
135
- const items = result.items?.map(item => {
136
- const detail = details[item.release?.releaseId ?? 0];
137
- return {
138
- id: item.itemId,
139
- title: `${item.release?.artists?.map(x => x.name ?? '').join(', ') ?? ''} - ${item.release?.title ?? ''} (${item.release?.majorFormat ?? ''})`,
140
- artists: item.release?.artists?.map(x => ({
141
- id: x.artistId ?? null,
142
- name: x.name ?? '',
143
- url: x.artistId ? `https://www.discogs.com/artist/${x.artistId}` : null,
144
- })) ?? [],
145
- release: {
146
- id: item.release?.releaseId ?? 0,
147
- name: item.release?.title ?? '',
148
- url: `https://www.discogs.com/release/${item.release?.releaseId ?? '0'}`,
149
- },
150
- formats: item.release?.formatNames ?? [],
151
- labels: item.release?.labels?.map(x => ({
152
- id: x.labelId ?? 0,
153
- name: x.name ?? '',
154
- url: `https://www.discogs.com/label/${x.labelId ?? '0'}`,
155
- })) ?? [],
156
- url: `https://www.discogs.com/sell/item/${item.itemId}`,
157
- listedAt: new Date(item.listedDate ?? ''),
158
- catnos: [],
159
- imageUrl: detail?.imageUrl ?? null,
160
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
161
- description: item.comments || null,
162
- isAcceptingOffer: item.allowsOffers ?? false,
163
- isAvailable: true,
164
- condition: {
165
- media: {
166
- full: item.mediaCondition ?? '',
167
- short: /\(([^)]+)\)/.exec(item.mediaCondition ?? '')?.[1] ?? '',
168
- },
169
- sleeve: {
170
- full: item.sleeveCondition ?? null,
171
- short: /\(([^)]+)\)/.exec(item.sleeveCondition ?? '')?.[1] ?? null,
172
- },
173
- },
174
- seller: {
175
- name: item.seller?.name ?? '',
176
- url: `https://www.discogs.com/seller/${item.seller?.name ?? ''}/profile`,
177
- score: item.seller?.rating ? `${item.seller.rating.toFixed(1)}%` : null,
178
- notes: item.seller?.ratingCount ?? null,
179
- },
180
- price: {
181
- base: `${item.price?.currencyCode === 'JPY' ? (item.price.amount ?? 0) : (item.price?.amount ?? 0).toFixed(2)} ${(item.price?.currencyCode ?? '')}`,
182
- shipping: item.shipping
183
- ? `${item.price?.currencyCode === 'JPY'
184
- ? (item.shipping.shippingPrice ?? 0)
185
- : (item.shipping.shippingPrice ?? 0).toFixed(2)} ${(item.price?.currencyCode ?? '')}`
186
- : null,
187
- },
188
- country: {
189
- name: item.seller?.shipsFrom ?? '',
190
- code: country_data_1.default[item.seller?.shipsFrom],
191
- },
192
- community: {
193
- have: detail?.have ?? 0,
194
- want: detail?.want ?? 0,
195
- },
196
- };
197
- }) ?? [];
198
- return { total: result.totalCount ?? 0, items, urlGenerated };
199
- }
@@ -1,13 +0,0 @@
1
- import type SearchResult from 'interfaces/search-result.interface';
2
- import type { SearchParamsModern } from 'interfaces/search-params.interface';
3
- import type { BrowserContext } from 'playwright-chromium';
4
- /**
5
- * Parses the page and returns the items found.
6
- * @param searchParams Search parameters
7
- * @param browserContext Playwright browser context
8
- * @returns Items found and total
9
- */
10
- export default function scrapeWantlist(searchParams: SearchParamsModern, browserContext: BrowserContext): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
11
- /** Total items found */
12
- total: SearchResult['result']['total'];
13
- }>;
@@ -1,66 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = scrapeWantlist;
7
- const modern_scraper_1 = __importDefault(require("scrapers/modern.scraper"));
8
- const PER_PAGE = 250;
9
- /**
10
- * Parses the page and returns the items found.
11
- * @param searchParams Search parameters
12
- * @param browserContext Playwright browser context
13
- * @returns Items found and total
14
- */
15
- async function scrapeWantlist(searchParams, browserContext) {
16
- /**
17
- * Fetches the content of a specific page number in the wantlist.
18
- * @param pageNumber Page number to fetch
19
- * @returns Links and total items found
20
- */
21
- const getPageContent = async (pageNumber) => {
22
- const url = `https://www.discogs.com/wantlist?${new URLSearchParams({
23
- page: pageNumber.toString(),
24
- limit: PER_PAGE.toString(),
25
- user: searchParams.wantlist ?? '',
26
- layout: 'sm',
27
- }).toString()}`;
28
- const browserPage = await browserContext.newPage();
29
- await browserPage.setExtraHTTPHeaders({
30
- 'User-Agent': 'Discogs',
31
- Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
32
- 'Accept-Language': 'en-US,en;q=0.7,fr-FR;q=0.8',
33
- Referer: url,
34
- });
35
- await browserPage.route('**/*', route => (route.request().resourceType() === 'document' ? route.continue() : route.abort()));
36
- const response = await browserPage.goto(url, { waitUntil: 'domcontentloaded' });
37
- const [total, ids] = await Promise.all([
38
- browserPage.evaluate(() => +(document.querySelector('.pagination_total')?.textContent.split(' of ').pop()?.replace(',', '') ?? '0')),
39
- browserPage.evaluate(() => {
40
- /** Extract the links to the items in the wantlist, if there's no link it's not for sale */
41
- const links = [...document.querySelectorAll('.marketplace_for_sale_count a')];
42
- return links.map(x => +(new URL(`https://discogs.com${x.href}`).pathname.split('/').pop() ?? '0'));
43
- }),
44
- ]);
45
- await browserPage.close();
46
- return {
47
- ids,
48
- total,
49
- status: response?.status() ?? 500,
50
- };
51
- };
52
- /** Fetch the first page of user wantlist */
53
- const firstPageResponse = await getPageContent(1);
54
- if (firstPageResponse.status >= 400 && firstPageResponse.status !== 404) {
55
- throw new Error(`An error ${firstPageResponse.status} occurred.`);
56
- }
57
- const wants = await Promise.all(new Array(Math.ceil(firstPageResponse.total / PER_PAGE))
58
- .fill({})
59
- .map(async (_, i) => (i === 0 ? firstPageResponse : await getPageContent(i + 1))));
60
- const wantlistIds = wants.flatMap(x => x.ids);
61
- // If there's nothing for sale
62
- if (wantlistIds.length === 0) {
63
- return (0, modern_scraper_1.default)({ ...searchParams, releaseIds: [0], wantlist: undefined }, browserContext);
64
- }
65
- return (0, modern_scraper_1.default)({ ...searchParams, releaseIds: wantlistIds, wantlist: undefined }, browserContext);
66
- }
@@ -1,4 +0,0 @@
1
- /**
2
- * Api
3
- */
4
- export type Api = 'v2' | 'legacy';
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,4 +0,0 @@
1
- /**
2
- * Langs
3
- */
4
- export type Lang = 'de' | 'en' | 'es' | 'fr' | 'it' | 'ja' | 'ko' | 'pt_BR' | 'ru' | ({} & string);
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,4 +0,0 @@
1
- /**
2
- * Limits per page
3
- */
4
- export type Limit = 25 | 50 | 100 | 250;
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });