discogs-marketplace-api-nodejs 1.13.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.
@@ -6,22 +6,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.default = scrape;
7
7
  /* eslint-disable @typescript-eslint/no-non-null-assertion */
8
8
  const country_data_1 = __importDefault(require("../data/country.data.js"));
9
+ const search_1 = require("../search.js");
9
10
  /**
10
11
  * Parses the page and returns the items found.
11
12
  * @param SearchParams Search parameters
12
13
  * @returns Items found and total
13
14
  */
14
- async function scrape({ currency, genre, format, formatDescription, condition, years, isMakeAnOfferOnly, from,
15
- // Seller,
16
- sort, limit, page, releases, }) {
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
17
  const urlGenerated = [
18
18
  'https://www.discogs.com/api/shop-page-api/sell_item',
19
19
  new URLSearchParams([
20
- ['sellerRatingMin', '0'],
21
- ['includeGenericSleeves', 'true'],
22
- ['includeSleevelessMedia', 'true'],
23
- ['showUnavailable', 'true'],
24
- ['sellerRatingCountMin', '0'],
20
+ ['sellerRatingMin', sellerRatingMin.toString()],
21
+ ['includeGenericSleeves', includeGenericSleeves.toString()],
22
+ ['includeSleevelessMedia', includeSleevelessMedia.toString()],
23
+ ['showUnavailable', showUnavailable.toString()],
24
+ ['sellerRatingCountMin', sellerRatingCountMin.toString()],
25
25
  [
26
26
  'sort',
27
27
  {
@@ -31,28 +31,35 @@ sort, limit, page, releases, }) {
31
31
  title: 'title',
32
32
  seller: 'seller',
33
33
  price: 'price',
34
- }[sort.split(',').at(0)] ?? 'listedDate',
34
+ }[sortType] ?? 'listedDate',
35
35
  ],
36
36
  [
37
37
  'sortOrder',
38
38
  {
39
39
  asc: 'ascending',
40
40
  desc: 'descending',
41
- }[sort.split(',').at(-1)] ?? 'ascending',
41
+ }[sortOrder] ?? 'ascending',
42
42
  ],
43
43
  ['count', limit.toString()],
44
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]) ?? []),
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()]) ?? []),
51
58
  ['allowsOffers', isMakeAnOfferOnly ? 'true' : ''],
52
- ['currency', currency ?? ''],
53
- ['genre', genre ?? ''],
54
59
  ['yearRangeLow', years?.min.toString() ?? ''],
55
60
  ['yearRangeHigh', years?.max.toString() ?? ''],
61
+ ['priceRangeLow', priceRange?.min.toString() ?? ''],
62
+ ['priceRangeHigh', priceRange?.max.toString() ?? ''],
56
63
  ].filter(([, p]) => !!p)).toString(),
57
64
  ].join('?');
58
65
  const result = (await (await globalThis.fetch(urlGenerated, {
@@ -93,23 +100,33 @@ sort, limit, page, releases, }) {
93
100
  have: release.inCollectionCount ?? 0,
94
101
  },
95
102
  ]) ?? []);
96
- const items = (result.items?.map(item => {
103
+ const items = result.items?.map(item => {
97
104
  const detail = details[item.release?.releaseId ?? 0];
98
105
  return {
99
106
  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 ?? [],
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'}`,
106
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
+ })) ?? [],
107
124
  url: `https://www.discogs.com/sell/item/${item.itemId}`,
108
125
  listedAt: new Date(item.listedDate ?? ''),
109
- labels: item.release?.labels?.map(x => x.name ?? '').filter((value, index, self) => self.indexOf(value) === index) ?? [],
110
126
  catnos: [],
111
- imageUrl: detail?.imageUrl ?? '',
112
- description: item.comments ?? '',
127
+ imageUrl: detail?.imageUrl ?? null,
128
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
129
+ description: item.comments || null,
113
130
  isAcceptingOffer: item.allowsOffers ?? false,
114
131
  isAvailable: true,
115
132
  condition: {
@@ -118,34 +135,33 @@ sort, limit, page, releases, }) {
118
135
  short: /\(([^)]+)\)/.exec(item.mediaCondition ?? '')?.[1] ?? '',
119
136
  },
120
137
  sleeve: {
121
- full: item.sleeveCondition ?? '',
122
- short: /\(([^)]+)\)/.exec(item.sleeveCondition ?? '')?.[1] ?? '',
138
+ full: item.sleeveCondition ?? null,
139
+ short: /\(([^)]+)\)/.exec(item.sleeveCondition ?? '')?.[1] ?? null,
123
140
  },
124
141
  },
125
142
  seller: {
126
143
  name: item.seller?.name ?? '',
127
144
  url: `https://www.discogs.com/seller/${item.seller?.name ?? ''}/profile`,
128
- score: item.seller?.rating?.toString() ?? '0',
129
- notes: item.seller?.ratingCount ?? 0,
145
+ score: item.seller?.rating ? `${item.seller.rating.toFixed(1)}%` : null,
146
+ notes: item.seller?.ratingCount ?? null,
130
147
  },
131
148
  price: {
132
- base: `${item.price?.amount ?? 0} ${(item.price?.currencyCode ?? '')}`,
133
- shipping: item.shipping ? `${item.shipping.shippingPrice ?? 0} ${(item.price?.currencyCode ?? '')}` : '',
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,
134
155
  },
135
156
  country: {
136
157
  name: item.seller?.shipsFrom ?? '',
137
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
138
- code: country_data_1.default[item.seller?.shipsFrom] ?? '',
158
+ code: country_data_1.default[item.seller?.shipsFrom],
139
159
  },
140
160
  community: {
141
161
  have: detail?.have ?? 0,
142
162
  want: detail?.want ?? 0,
143
163
  },
144
- release: {
145
- id: item.release?.releaseId ?? 0,
146
- url: `https://www.discogs.com/release/${item.release?.releaseId ?? ''}`,
147
- },
148
164
  };
149
- }) ?? []);
165
+ }) ?? [];
150
166
  return { total: result.totalCount ?? 0, items, urlGenerated };
151
167
  }
@@ -1,11 +1,11 @@
1
1
  import type SearchResult from '../interfaces/search-result.interface.js';
2
- import type { SearchParamsDefaulted } from '../interfaces/search-params.interface.js';
2
+ import type { SearchParamsModern } from '../interfaces/search-params.interface.js';
3
3
  /**
4
4
  * Parses the page and returns the items found.
5
5
  * @param searchParams Search parameters
6
6
  * @returns Items found and total
7
7
  */
8
- export default function scrapeWantlist(searchParams: SearchParamsDefaulted): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
8
+ export default function scrapeWantlist(searchParams: SearchParamsModern): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
9
9
  /** Total items found */
10
10
  total: SearchResult['result']['total'];
11
11
  }>;
@@ -13,15 +13,11 @@ const PER_PAGE = 250;
13
13
  * @returns Items found and total
14
14
  */
15
15
  async function scrapeWantlist(searchParams) {
16
- const { searchValue } = searchParams;
17
- if (!searchValue) {
18
- return { items: [], urlGenerated: '', total: 0 };
19
- }
20
16
  /** Fetch the first page of user wantlist */
21
17
  const firstPage = await (await globalThis.fetch(`https://www.discogs.com/wantlist?${new URLSearchParams({
22
18
  page: '1',
23
19
  limit: PER_PAGE.toString(),
24
- user: searchValue.toString(),
20
+ user: searchParams.wantlist ?? '',
25
21
  layout: 'sm',
26
22
  }).toString()}`, {
27
23
  headers: { 'User-Agent': 'Discogs', 'Content-Type': 'application/json' },
@@ -37,7 +33,7 @@ async function scrapeWantlist(searchParams) {
37
33
  : (await globalThis.fetch(`https://www.discogs.com/wantlist?${new URLSearchParams({
38
34
  page: page.toString(),
39
35
  limit: PER_PAGE.toString(),
40
- user: searchValue.toString(),
36
+ user: searchParams.wantlist ?? '',
41
37
  layout: 'sm',
42
38
  }).toString()}`, {
43
39
  headers: { 'User-Agent': 'Discogs', 'Content-Type': 'application/json' },
@@ -53,5 +49,5 @@ async function scrapeWantlist(searchParams) {
53
49
  if (wantlistIds.length === 0) {
54
50
  return { items: [], total: 0, urlGenerated: '' };
55
51
  }
56
- return (0, modern_scraper_1.default)({ ...searchParams, releases: wantlistIds });
52
+ return (0, modern_scraper_1.default)({ ...searchParams, releaseIds: wantlistIds, wantlist: undefined });
57
53
  }
package/dist/search.d.ts CHANGED
@@ -1,8 +1,11 @@
1
- import type SearchParams from './interfaces/search-params.interface.js';
1
+ import type { SearchParams } from './interfaces/search-params.interface.js';
2
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";
3
6
  /**
4
7
  * Performs a search on the Discogs marketplace using the provided parameters.
5
- * @param params Search parameters
8
+ * @param searchParams Search parameters
6
9
  * @returns A promise that resolves to the search results, including items found, pagination details, and the generated URL.
7
10
  */
8
- export default function search(params: SearchParams): Promise<SearchResult>;
11
+ export default function search(searchParams: SearchParams): Promise<SearchResult>;
package/dist/search.js CHANGED
@@ -3,35 +3,38 @@ 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
8
  const legacy_scraper_1 = __importDefault(require("./scrapers/legacy.scraper.js"));
8
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';
9
14
  /**
10
15
  * Performs a search on the Discogs marketplace using the provided parameters.
11
- * @param params Search parameters
16
+ * @param searchParams Search parameters
12
17
  * @returns A promise that resolves to the search results, including items found, pagination details, and the generated URL.
13
18
  */
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));
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
+ })();
26
29
  return {
27
30
  items,
28
31
  result: {
29
32
  total,
30
- perPage: searchParams.limit,
33
+ perPage: searchParams.limit ?? exports.DEFAULT_LIMIT,
31
34
  },
32
35
  page: {
33
- current: searchParams.page,
34
- total: Math.ceil(total / searchParams.limit),
36
+ current: searchParams.page ?? exports.DEFAULT_PAGE,
37
+ total: Math.ceil(total / (searchParams.limit ?? exports.DEFAULT_LIMIT)),
35
38
  },
36
39
  urlGenerated,
37
40
  };
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Api
3
+ */
4
+ export type Api = 'v2' | 'legacy';
@@ -1,4 +1,5 @@
1
+ import type { CountryValues } from '../data/country.data.js';
1
2
  /**
2
3
  * From
3
4
  */
4
- export type From = 'Afghanistan' | 'Albania' | 'Algeria' | 'American Samoa' | 'Andorra' | 'Angola' | 'Anguilla' | 'Antarctica' | 'Antigua and Barbuda' | 'Argentina' | 'Armenia' | 'Aruba' | 'Australia' | 'Austria' | 'Azerbaidjan' | 'Bahamas' | 'Bahrain' | 'Bangladesh' | 'Barbados' | 'Belarus' | 'Belgium' | 'Belize' | 'Benin' | 'Bermuda' | 'Bhutan' | 'Bolivia' | 'Bosnia-Herzegovina' | 'Botswana' | 'Bouvet Island' | 'Brazil' | 'British Indian Ocean Territory' | 'Brunei Darussalam' | 'Bulgaria' | 'Burkina Faso' | 'Burundi' | 'Cambodia' | 'Cameroon' | 'Canada' | 'Cape Verde' | 'Cayman Islands' | 'Central African Republic' | 'Chad' | 'Chile' | 'China' | 'Christmas Island' | 'Cocos (Keeling) Islands' | 'Colombia' | 'Comoros' | 'Congo' | 'Cook Islands' | 'Costa Rica' | 'Croatia' | 'Cuba' | 'Cyprus' | 'Czech Republic' | 'Denmark' | 'Djibouti' | 'Dominica' | 'Dominican Republic' | 'East Timor' | 'Ecuador' | 'Egypt' | 'El Salvador' | 'Equatorial Guinea' | 'Eritrea' | 'Estonia' | 'Ethiopia' | 'Falkland Islands' | 'Faroe Islands' | 'Fiji' | 'Finland' | 'Former Czechoslovakia' | 'Former USSR' | 'France' | 'France (European Territory)' | 'French Guyana' | 'French Southern Territories' | 'Gabon' | 'Gambia' | 'Georgia' | 'Germany' | 'Ghana' | 'Gibraltar' | 'Greece' | 'Greenland' | 'Grenada' | 'Guadeloupe (French)' | 'Guam (USA)' | 'Guatemala' | 'Guinea' | 'Guinea Bissau' | 'Guyana' | 'Haiti' | 'Heard and McDonald Islands' | 'Honduras' | 'Hong Kong' | 'Hungary' | 'Iceland' | 'India' | 'Indonesia' | 'Iran' | 'Iraq' | 'Ireland' | 'Israel' | 'Italy' | "Ivory Coast (Cote D'Ivoire)" | 'Jamaica' | 'Japan' | 'Jordan' | 'Kazakhstan' | 'Kenya' | 'Kiribati' | 'Kuwait' | 'Kyrgyzstan' | 'Laos' | 'Latvia' | 'Lebanon' | 'Lesotho' | 'Liberia' | 'Libya' | 'Liechtenstein' | 'Lithuania' | 'Luxembourg' | 'Macau' | 'Macedonia' | 'Madagascar' | 'Malawi' | 'Malaysia' | 'Maldives' | 'Mali' | 'Malta' | 'Marshall Islands' | 'Martinique (French)' | 'Mauritania' | 'Mauritius' | 'Mayotte' | 'Mexico' | 'Micronesia' | 'Moldova, Republic of' | 'Monaco' | 'Mongolia' | 'Montenegro' | 'Montserrat' | 'Morocco' | 'Mozambique' | 'Myanmar' | 'Namibia' | 'Nauru' | 'Nepal' | 'Netherlands' | 'Netherlands Antilles' | 'Neutral Zone' | 'New Caledonia (French)' | 'New Zealand' | 'Nicaragua' | 'Niger' | 'Nigeria' | 'Niue' | 'Norfolk Island' | 'Northern Ireland' | 'Northern Mariana Islands' | 'Norway' | 'Oman' | 'Pakistan' | 'Palau' | 'Panama' | 'Papua New Guinea' | 'Paraguay' | 'Peru' | 'Philippines' | 'Pitcairn Island' | 'Poland' | 'Polynesia (French)' | 'Portugal' | 'Puerto Rico' | 'Qatar' | 'Reunion (French)' | 'Romania' | 'Russian Federation' | 'Rwanda' | 'S. Georgia & S. Sandwich Isls.' | 'Saint Helena' | 'Saint Kitts & Nevis Anguilla' | 'Saint Lucia' | 'Saint Pierre and Miquelon' | 'Saint Tome (Sao Tome) and Princi' | 'Saint Vincent & Grenadines' | 'Samoa' | 'San Marino' | 'Saudi Arabia' | 'Select your country' | 'Senegal' | 'Serbia' | 'Seychelles' | 'Sierra Leone' | 'Singapore' | 'Slovak Republic' | 'Slovenia' | 'Solomon Islands' | 'Somalia' | 'South Africa' | 'South Korea' | 'Spain' | 'Spain (Canary Islands)' | 'Sri Lanka' | 'Sudan' | 'Suriname' | 'Svalbard and Jan Mayen Islands' | 'Swaziland' | 'Sweden' | 'Switzerland' | 'Syria' | 'Tadjikistan' | 'Taiwan' | 'Tanzania' | 'Thailand' | 'Togo' | 'Tokelau' | 'Tonga' | 'Trinidad and Tobago' | 'Tunisia' | 'Turkey' | 'Turkmenistan' | 'Turks and Caicos Islands' | 'Tuvalu' | 'USA Minor Outlying Islands' | 'Uganda' | 'Ukraine' | 'United Arab Emirates' | 'United Kingdom' | 'United Kingdom (Channel Islands)' | 'United States' | 'Uruguay' | 'Uzbekistan' | 'Vanuatu' | 'Vatican City State' | 'Venezuela' | 'Vietnam' | 'Virgin Islands (British)' | 'Virgin Islands (USA)' | 'Wallis and Futuna Islands' | 'Western Sahara' | 'Yemen' | 'Yugoslavia' | 'Zaire' | 'Zambia' | 'Zimbabwe' | ({} & string);
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.13.0",
3
+ "version": "1.14.0",
4
4
  "description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
5
5
  "keywords": [
6
6
  "discogs",
@@ -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,119 +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']) {
41
- const value = urlSearchParams.get(key);
42
- if (value) {
43
- switch (key) {
44
- case 'ships_from':
45
- searchParams.from = value;
46
- break;
47
- default:
48
- searchParams[key] = value;
49
- break;
50
- }
51
- }
52
- }
53
- // Retrieve number search values
54
- for (const key of ['limit', 'page']) {
55
- const value = safeParseInt(urlSearchParams.get(key));
56
- if (value) {
57
- switch (key) {
58
- case 'limit':
59
- searchParams.limit = value;
60
- break;
61
- default:
62
- searchParams[key] = value;
63
- break;
64
- }
65
- }
66
- }
67
- // Retrieve array search values
68
- for (const key of ['style', 'format', 'format_desc', 'condition']) {
69
- const values = urlSearchParams.getAll(key);
70
- if (values.length) {
71
- switch (key) {
72
- case 'format_desc':
73
- searchParams.formatDescription = values;
74
- break;
75
- default:
76
- searchParams[key] = values;
77
- break;
78
- }
79
- }
80
- }
81
- // Check if search is on offers only
82
- if (urlSearchParams.get('offers') === '1') {
83
- searchParams.isMakeAnOfferOnly = true;
84
- }
85
- // Handle year and years
86
- const year = safeParseInt(urlSearchParams.get('year'));
87
- const year1 = safeParseInt(urlSearchParams.get('year1'));
88
- const year2 = safeParseInt(urlSearchParams.get('year2'));
89
- if (year) {
90
- searchParams.year = year;
91
- }
92
- else if (year1 && year2) {
93
- searchParams.years = { min: year1, max: year2 };
94
- }
95
- // Retrieve the language from the URL path
96
- const pathSegments = pathname.split('/').filter(x => x);
97
- if (/^[a-z]{2}$/i.test(pathSegments[0] ?? '')) {
98
- searchParams.lang = pathSegments[0]?.toLowerCase();
99
- }
100
- // Handle specific case for release ID in the URL path
101
- const releaseIdMatch = /\/sell\/release\/(\d+)/.exec(url);
102
- if (releaseIdMatch?.[1]) {
103
- searchParams.searchType = 'release_id';
104
- searchParams.searchValue = releaseIdMatch[1];
105
- }
106
- // Handle specific case for seller profile in the URL path
107
- const sellerProfileMatch = /\/seller\/([^/]+)\/profile/.exec(url);
108
- if (sellerProfileMatch?.[1]) {
109
- searchParams.seller = sellerProfileMatch[1];
110
- }
111
- // Handle specific case for seller name on wantlist in the URL path
112
- const sellerMyWantsMatch = /\/seller\/([^/]+)\/mywants/.exec(url);
113
- if (sellerMyWantsMatch?.[1]) {
114
- searchParams.searchType = 'user';
115
- searchParams.searchValue = urlSearchParams.get('user') ?? '';
116
- searchParams.seller = sellerMyWantsMatch[1];
117
- }
118
- return searchParams;
119
- }
@@ -1,4 +0,0 @@
1
- /**
2
- * SearchTypes
3
- */
4
- export type Search = 'q' | 'master_id' | 'release_id' | 'label_id' | 'artist_id' | 'user';
File without changes