Saturday 17 November 2018

Structuring a Class for a third party API with Node.js/ES6?

Hey guys, I'm trying to restructure a small app I'm building. I'm using Spotify's API and at the moment I have all my logic in one file and just creating the routes there. I want to create a class for SpotifyClient and another class for my server but I'm unsure how to go on about this. I have these two routes specifically for Spotify Authorization that I want to remove and put into a class:app.get('/login', (req, res) => { const state = generateRandomString(16); res.cookie(STATE_KEY, state); res.redirect(spotifyApi.createAuthorizeURL(scopes, state)); }); app.get('/callback', (req, res) => { const { code, state } = req.query; const storedState = req.cookies ? req.cookies[STATE_KEY] : null; if (state === null || state !== storedState) { res.redirect('/#/error/state mismatch'); } else { res.clearCookie(STATE_KEY); spotifyApi .authorizationCodeGrant(code) .then(data => { const expiresIn = data.body.expires_in; const accessToken = data.body.access_token; const refreshToken = data.body.refresh_token; // Set the access token on the API object to use it in later calls SPOTIFY_TOKEN = accessToken; spotifyApi.setAccessToken(accessToken); spotifyApi.setRefreshToken(refreshToken); spotifyApi.getMe().then(({ body }) => { SPOTIFY_ID = body.id; }); res.redirect('/search'); }) .catch(err => { res.redirect('/#/error/invalid token'); }); } }); I have my API keys that I export as environment variables and store them in an object in a config.js file.So starting out, would be somehting like this:const config = require('./config'); class SpotifyClient { } But would I pass the keys in my constructor? How would I set up the routes? Should they just be class methods?Any advice would be appreciated!

Submitted November 17, 2018 at 11:56PM by RubyNewbie-

No comments:

Post a Comment