2024-12-26 14:08:09 +01:00
|
|
|
import { BANK_OAUTH_CLIENT_ID, BANK_OAUTH_CLIENT_SECRET } from "../../config.ts"
|
|
|
|
import { OAuthTokenResponse } from "@/bank/sparebank1.ts"
|
2025-01-25 18:01:47 +01:00
|
|
|
import logger from "@/logger.ts"
|
2024-12-26 14:08:09 +01:00
|
|
|
|
|
|
|
const baseUrl = "https://api.sparebank1.no"
|
|
|
|
|
|
|
|
type Success<T> = { status: "success"; data: T }
|
|
|
|
type Failure<T> = { status: "failure"; data: T }
|
|
|
|
type Result<OK, Err> = Success<OK> | Failure<Err>
|
|
|
|
|
|
|
|
function success<T>(data: T): Success<T> {
|
|
|
|
return { status: "success", data: data }
|
|
|
|
}
|
|
|
|
|
|
|
|
function failure<T>(data: T): Failure<T> {
|
|
|
|
return { status: "failure", data: data }
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function refreshToken(
|
|
|
|
refreshToken: string,
|
|
|
|
): Promise<Result<OAuthTokenResponse, string>> {
|
|
|
|
const queries = new URLSearchParams({
|
|
|
|
client_id: BANK_OAUTH_CLIENT_ID,
|
|
|
|
client_secret: BANK_OAUTH_CLIENT_SECRET,
|
|
|
|
refresh_token: refreshToken,
|
|
|
|
grant_type: "refresh_token",
|
|
|
|
})
|
2025-01-25 18:01:47 +01:00
|
|
|
const url = `${baseUrl}/oauth/token?${queries}`
|
|
|
|
logger.debug("Sending POST request to url: '%s'", url)
|
|
|
|
const response = await fetch(url, {
|
|
|
|
method: "post",
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
logger.debug(`Received response with status '${response.status}'`)
|
2024-12-26 14:08:09 +01:00
|
|
|
if (!response.ok) {
|
2025-01-25 18:01:47 +01:00
|
|
|
return failure(await response.text())
|
2024-12-26 14:08:09 +01:00
|
|
|
}
|
|
|
|
return success(await response.json())
|
|
|
|
}
|