我正在使用Express和Spotify Web API与Node一起构建一个小型应用程序
我在server.js
文件中进行了路由以测试逻辑,现在我试图将“授权流”的逻辑提取到SpotifyClient
类中,并将其输入到Server
类中(尚未完成)。这是我到目前为止的内容:
const Spotify = require('spotify-web-api-node');
class SpotifyClient {
constructor() {
this.SPOTIFY_CLIENT_ID = process.env.SPOTIFY_CLIENT_ID;
this.SPOTIFY_SECRET_ID = process.env.SPOTIFY_SECRET_ID;
this.SPOTIFY_TOKEN = '';
this.REDIRECT_URI = 'http://localhost:4000/callback';
this.STATE_KEY = 'spotify_auth_state';
}
spotifyNodeWrap() {
const options = {
id: this.SPOTIFY_CLIENT_ID,
secret: this.SPOTIFY_SECRET_ID,
redirectUri: this.REDIRECT_URI
};
const spotifyApi = new Spotify(options);
return spotifyApi;
}
spotifyAuth(req, res) {
const scopes = [
'user-read-private',
'user-read-email',
'playlist-read-private',
'playlist-modify-private',
'playlist-modify-public'
];
// generate random string to be used as state
const generateRandomString = N =>
(Math.random().toString(36) + Array(N).join('0')).slice(2, N + 2);
const state = generateRandomString(16);
const spotifyApi = this.spotifyNodeWrap();
const authURL = spotifyApi.createAuthorizeURL(scopes, state);
res.redirect(authURL);
}
// Logic to create authroization is here:
callback(req, res) {
const { code, state } = req.query;
const storedState = req.cookies ? req.cookies[this.STATE_KEY] : null;
let SPOTIFY_ID = '';
let SPOTIFY_TOKEN = '';
if (state === null || state !== storedState) {
res.redirect('/#/error/state mismatch');
} else {
res.clearCookie(this.STATE_KEY);
this.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');
});
}
}
我要做什么:
使用我的客户端ID和Secret从Spotify包中创建一个spotifyNodeWrap
实例。
从Spotify提供的/authorize
端点创建授权URL,并在此重定向用户。
用户授予权限后,将使用参数redirectURI
中的授权代码将用户重定向到code
,可以将其交换为访问令牌。
我在callback
函数中感到困惑,是否在其中创建spotifyNodeWrap
的新实例?我需要一开始就创建的包装,然后将其包装到其他功能中。我应该将其设置为构造函数的一部分吗?