Sanitize discover parameters

This commit is contained in:
patrickkfkan 2021-01-23 21:49:34 +08:00
parent e081291a84
commit 0969dbb794

View File

@ -12,10 +12,60 @@ async function discover(params, options = {}) {
artistImageFormat: await _parseImageFormatArg(options.artistImageFormat, 21)
};
const url = utils.getDiscoverUrl(params);
return fetch(url)
let resultParams;
return sanitizeDiscoverParams(params)
.then( sanitizedParams => {
resultParams = sanitizedParams;
return utils.getDiscoverUrl(sanitizedParams);
})
.then( url => fetch(url) )
.then( res => res.json() )
.then( json => parser.parseDiscoverResults(json, opts) );
.then( json => {
const result = parser.parseDiscoverResults(json, opts);
result.params = resultParams;
return result;
});
}
async function sanitizeDiscoverParams(params) {
return getDiscoverOptions().then( options => {
const getOptionValue = (optArr, value) => {
if (value !== undefined && optArr) {
const opt = optArr.find( o => o.value === value );
if (opt) {
return opt.value;
}
}
if (optArr) {
return optArr[0].value;
}
else {
return null;
}
}
const sanitized = {
genre: getOptionValue(options.genres, params.genre),
sortBy: getOptionValue(options.sortBys, params.sortBy),
page: params.page || 0
};
if (sanitized.sortBy !== 'rec') {
// following only valid when sortBy is not 'rec' (artist-recommend)
if (params.subgenre !== undefined && getOptionValue(options.subgenres[sanitized.genre], params.subgenre) !== null) {
sanitized.subgenre = params.subgenre;
}
if (sanitized.subgenre === undefined) {
// 'time' only valid when 'subgenre' is not set
sanitized.time = getOptionValue(options.times, params.time);
}
sanitized.location = getOptionValue(options.locations, params.location);
sanitized.format = getOptionValue(options.formats, params.format);
}
else {
sanitized.artistRecommendationType = getOptionValue(options.artistRecommendationTypes, params.artistRecommendationType);
}
return sanitized;
});
}
async function getDiscoverOptions() {
@ -173,6 +223,7 @@ async function getTags() {
module.exports = {
discover,
getDiscoverOptions,
sanitizeDiscoverParams,
getImageFormats,
getImageFormat,
getAlbumInfo,