From e93df0e0a8bf266864bfc5281327dd8b9db1a818 Mon Sep 17 00:00:00 2001 From: Sayem Chowdhury Date: Tue, 13 Apr 2021 13:45:07 +0600 Subject: [PATCH] refactor request --- src/api/api.ts | 25 +++---------------------- src/api/request.ts | 30 +++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/src/api/api.ts b/src/api/api.ts index ec9abe6..55db8bb 100644 --- a/src/api/api.ts +++ b/src/api/api.ts @@ -1,5 +1,5 @@ import axios from '../lib/request'; -import {request, requestPublicApi} from './request'; +import {request, requestGet, requestPublicApi} from './request'; import type { albumType, trackType, @@ -118,18 +118,7 @@ export const searchMusic = (query: string, types: searchTypesProp[] = ['TRACK'], /** * Get details about current user */ -export const getUser = async (): Promise => { - const { - data: {error, results}, - } = await axios.get('/gateway.php', {params: {method: 'user_getInfo'}}); - - if (Object.keys(results).length > 0) { - return results; - } - - const errorMessage = Object.entries(error).join(', '); - throw new Error(errorMessage); -}; +export const getUser = async (): Promise => requestGet('user_getInfo'); /** * Get list of channles @@ -234,14 +223,6 @@ export const getPlaylistChannel = async (name?: string): Promise 0) { - return results; - } - - const errorMessage = Object.entries(error).join(', '); - throw new Error(errorMessage); + return await requestGet('app_page_get', {gateway_input}); }; diff --git a/src/api/request.ts b/src/api/request.ts index 858029c..47677b2 100644 --- a/src/api/request.ts +++ b/src/api/request.ts @@ -2,7 +2,7 @@ import axios from '../lib/request'; import lru from './cache'; /** - * Make post requests to deezer api + * Make POST requests to deezer api * @param {Object} body post body * @param {String} method request method */ @@ -27,9 +27,33 @@ export const request = async (body: object, method: string) => { }; /** - * Make post requests to deezer public api - * @param {Object} body post body + * Make GET requests to deezer public api * @param {String} method request method + * @param {Object} params request parameters + */ +export const requestGet = async (method: string, params?: object) => { + const cacheKey = `${method}:${params ? Object.entries(params).join(':') : 'get_request'}`; + const cache = lru.get(cacheKey); + if (cache) { + return cache; + } + + const { + data: {error, results}, + } = await axios.get('/gateway.php', {params: {method, ...params}}); + + if (Object.keys(results).length > 0) { + lru.set(cacheKey, results); + return results; + } + + const errorMessage = Object.entries(error).join(', '); + throw new Error(errorMessage); +}; + +/** + * Make GET requests to deezer public api + * @param {String} slug endpoint */ export const requestPublicApi = async (slug: string) => { const cache = lru.get(slug);