refactor: typescript
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import * as TwitchAuth from './TwitchAuth.ts'
|
||||
|
||||
interface AuthHeaders {
|
||||
'Authorization': string,
|
||||
'Client-ID': string
|
||||
}
|
||||
|
||||
interface Token extends TwitchAuth.TwitchToken {
|
||||
auth_headers: AuthHeaders
|
||||
}
|
||||
|
||||
let token: Token=null;
|
||||
|
||||
export function request_auth(client_id: string,scope: string,redirect_uri=location.origin+location.pathname){
|
||||
return TwitchAuth.requestAuthCode(client_id,...scope.split(' '))
|
||||
}
|
||||
|
||||
export function get_url_params(){
|
||||
return Object.fromEntries(new URLSearchParams(location.search))
|
||||
}
|
||||
|
||||
export async function fetch_tokens(client_id: string,code: string,redirect_uri=location.origin+location.pathname): Promise<Token>{
|
||||
client_id=client_id
|
||||
token=await TwitchAuth.exchangeCode(client_id,code) as Token
|
||||
token.client_id=client_id
|
||||
return token
|
||||
}
|
||||
|
||||
export function get_headers(tokens: Token): AuthHeaders{
|
||||
return {
|
||||
'Authorization':'Bearer '+tokens.access_token,
|
||||
'Client-ID':tokens.client_id
|
||||
}
|
||||
}
|
||||
|
||||
export async function validate_tokens(tokens: Token): Promise<Token>{
|
||||
const validation=await TwitchAuth.validateToken(tokens.access_token)
|
||||
Object.assign(tokens,validation)
|
||||
tokens.scope=validation.scope
|
||||
tokens.auth_headers=get_headers(tokens)
|
||||
token=tokens
|
||||
return token
|
||||
}
|
||||
|
||||
export function set_local_tokens(client_id: string,tokens: Token){
|
||||
token=tokens
|
||||
return token
|
||||
}
|
||||
|
||||
export function get_local_tokens(client_id: string){
|
||||
return token
|
||||
}
|
||||
|
||||
export async function refresh_tokens(client_id: string,refresh_token: string){
|
||||
token=await TwitchAuth.refreshToken(client_id,refresh_token) as Token
|
||||
return token
|
||||
}
|
||||
|
||||
export function set_refresh_timeout(client_id: string,tokens: Token){
|
||||
return setTimeout(()=>{
|
||||
TwitchAuth.refreshToken(client_id,tokens.refresh_token)
|
||||
.then(new_tokens=>Object.assign(tokens,new_tokens))
|
||||
},tokens.expires_in*999)
|
||||
}
|
||||
|
||||
export async function get_tokens(client_id: string,scope='',redirect_uri=location.origin+location.pathname,auth_return=false){
|
||||
token=await TwitchAuth.getUserToken(client_id,...scope.split(' ')).then(validate_tokens)
|
||||
set_refresh_timeout(client_id,token)
|
||||
return token
|
||||
}
|
||||
|
||||
export default get_tokens
|
||||
Reference in New Issue
Block a user