- Added some configuration and running to README - Refactored some code - Fixed exception when stopping a start-once script - Only allow running with pnpm - Moved transactions into sparebank1Api.ts - Formatted
81 lines
2.3 KiB
TypeScript
81 lines
2.3 KiB
TypeScript
import { BANK_OAUTH_CLIENT_ID, BANK_OAUTH_CLIENT_SECRET } from "../../config.ts"
|
|
import type {
|
|
OAuthTokenResponse,
|
|
TransactionResponse,
|
|
} from "@/bank/sparebank1.ts"
|
|
import logger from "@/logger.ts"
|
|
import { type Dayjs } from "dayjs"
|
|
import { toISODateString } from "@/date.ts"
|
|
|
|
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 transactions(
|
|
accessToken: string,
|
|
accountKeys: string | ReadonlyArray<string>,
|
|
timePeriod?: {
|
|
fromDate: Dayjs
|
|
toDate: Dayjs
|
|
},
|
|
): Promise<TransactionResponse> {
|
|
const queries = new URLSearchParams({
|
|
// TODO allow multiple accountKeys
|
|
accountKey: typeof accountKeys === "string" ? accountKeys : accountKeys[0],
|
|
...(timePeriod && {
|
|
fromDate: toISODateString(timePeriod.fromDate),
|
|
toDate: toISODateString(timePeriod.toDate),
|
|
}),
|
|
})
|
|
|
|
const url = `${baseUrl}/personal/banking/transactions?${queries}`
|
|
logger.debug(`Sending GET request to '${url}'`)
|
|
const response = await fetch(url, {
|
|
headers: {
|
|
Authorization: `Bearer ${accessToken}`,
|
|
Accept: "application/vnd.sparebank1.v1+json;charset=utf-8",
|
|
},
|
|
})
|
|
logger.debug(`Received response with status '${response.status}'`)
|
|
if (response.ok) {
|
|
return response.json()
|
|
} else {
|
|
logger.warn(await response.json())
|
|
return { transactions: [] }
|
|
}
|
|
}
|
|
|
|
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",
|
|
})
|
|
const url = `${baseUrl}/oauth/token?${queries}`
|
|
logger.debug(`Sending POST request to url: '${url}'`)
|
|
const response = await fetch(url, {
|
|
method: "post",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
},
|
|
})
|
|
logger.debug(`Received response with status '${response.status}'`)
|
|
if (!response.ok) {
|
|
return failure(await response.text())
|
|
}
|
|
return success(await response.json())
|
|
}
|