アクセス トークンを使用して API を認証する ionic 2 アプリがあります。アクセス トークンの有効期限が切れた場合は、更新トークンを使用して新しいアクセス トークンと交換できます。
promise を返す API 呼び出しを処理する関数があります。API 呼び出しが最初に成功すると、promise が解決されます。401 (Unauthorized) エラーが返された場合は、更新トークンを使用して新しいアクセス トークンを取得する別の API 呼び出しを行いたいと考えています。次に、新しいアクセス トークンを使用して元の API 呼び出しを再試行し、データが受信された場合は解決するか、エラーが発生した場合は拒否する必要があります。
現在、意図したとおりに機能しています。ただし、この関数は非常に読みにくいです。これをリファクタリングして、より小さく読みやすくする方法を考えていました。
public readAtmospherePrefs() {
return new Promise((resolve, reject) => {
this.storage.get('email').then((email) => {
this.storage.get('token').then((token) => {
let headers = new Headers();
headers.append('Authorization', token);
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers, search: new URLSearchParams("email=" + email) });
//Attempt to get data
this.http.get('api/users/preferences/atmosphere', options).subscribe(res => {
let data = res.json();
resolve(data);
resolve(res.json());
}, (err) => {
let error = err;
//Need to send email and refresh the token if unauthorized
if(err.status === 401){
this.storage.get('refreshToken').then((refreshToken) => {
let body = { email: email, refreshToken: refreshToken}
let headers2 = new Headers();
headers2.append('Content-Type', 'application/json');
//get new access token using the refresh token
let options2 = new RequestOptions({ headers: headers2});
this.http.post('api/users/token', body, options2)
.subscribe(res => {
let data = res.json();
let newToken = data.token;
//set new access token in storage
this.storage.set('token', newToken).then((newToken) => {
let headers3 = new Headers();
headers3.append('Authorization', newToken);
headers3.append('Content-Type', 'application/json');
//retry call with new access token
let options = new RequestOptions({ headers: headers3, search: new URLSearchParams("email=" + email) });
this.http.get('api/users/preferences/atmosphere', options).subscribe(res => {
let data = res.json();
resolve(data);
resolve(res.json());
},
(err) => {
reject(err);
});
});
}, (err) => {
reject(err);
});
});
}
else{
console.log(error);
reject(err);
}
});
});
});
});
}