- Create cache dir if missing - Moved Sqlite queries to queries.ts - Updated dependencies - Added pino-pretty to dev-dependencies - Changed Sqlite to store tokens as separate rows - Removed in-memory storage of tokens - isValidToken function - Throw Exception if refresh token is present but invalid - Fixed fetch query in smn http file
115 lines
3.1 KiB
TypeScript
115 lines
3.1 KiB
TypeScript
// TODO move types
|
|
import { BANK_INITIAL_REFRESH_TOKEN } from "@/../config.ts"
|
|
import logger from "@/logger.ts"
|
|
import dayjs from "dayjs"
|
|
import { Database } from "better-sqlite3"
|
|
import { fetchToken, insertTokens, TokenResponse } from "@/bank/db/queries.ts"
|
|
import * as Api from "./sparebank1Api.ts"
|
|
|
|
export interface OAuthTokenResponse {
|
|
access_token: string
|
|
expires_in: number
|
|
refresh_token_expires_in: number
|
|
refresh_token_absolute_expires_in: number
|
|
token_type: "Bearer"
|
|
refresh_token: string
|
|
}
|
|
|
|
export interface Transaction {
|
|
id: string
|
|
date: string
|
|
amount: number
|
|
description: string
|
|
cleanedDescription: string
|
|
remoteAccountName: string
|
|
|
|
[key: string]: string | number | boolean | unknown
|
|
}
|
|
|
|
export type Bank = Sparebank1
|
|
|
|
export interface Sparebank1 {
|
|
transactionsPastDay: (
|
|
accountKeys: ReadonlyArray<string> | string,
|
|
) => Promise<ReadonlyArray<Transaction>>
|
|
}
|
|
|
|
export class Sparebank1Impl implements Sparebank1 {
|
|
private static baseUrl = "https://api.sparebank1.no"
|
|
private readonly db: Database
|
|
|
|
constructor(db: Database) {
|
|
this.db = db
|
|
}
|
|
|
|
private async getAccessToken(): Promise<string> {
|
|
const accessToken = fetchToken(this.db, "access-token")
|
|
|
|
if (accessToken && this.isValidToken(accessToken)) {
|
|
return accessToken.token
|
|
}
|
|
const response = await this.fetchNewTokens()
|
|
return response.access_token
|
|
}
|
|
|
|
private isValidToken(tokenResponse: TokenResponse): boolean {
|
|
return dayjs() < tokenResponse.expires_at
|
|
}
|
|
|
|
private async getRefreshToken(): Promise<string> {
|
|
const tokenResponse = fetchToken(this.db, "refresh-token")
|
|
if (!tokenResponse) {
|
|
return BANK_INITIAL_REFRESH_TOKEN
|
|
} else if (this.isValidToken(tokenResponse)) {
|
|
return tokenResponse.token
|
|
}
|
|
// TODO clear database, if refresh token is invalid, will cause Exceptions on each call
|
|
throw new Error("Refresh token is expired. Create a new one")
|
|
}
|
|
|
|
async fetchNewTokens(): Promise<OAuthTokenResponse> {
|
|
const refreshToken = await this.getRefreshToken()
|
|
const result = await Api.refreshToken(refreshToken)
|
|
|
|
if (result.status === "failure") {
|
|
throw new Error("Failed to fetch refresh token")
|
|
}
|
|
const oAuthToken = result.data
|
|
|
|
insertTokens(this.db, oAuthToken)
|
|
return oAuthToken
|
|
}
|
|
|
|
async transactionsPastDay(
|
|
accountKeys: ReadonlyArray<string> | string,
|
|
): Promise<ReadonlyArray<Transaction>> {
|
|
const today = dayjs()
|
|
const lastDay = today.subtract(1, "day")
|
|
const queries = new URLSearchParams({
|
|
// TODO allow multiple accountKeys
|
|
accountKey:
|
|
typeof accountKeys === "string" ? accountKeys : accountKeys[0],
|
|
fromDate: lastDay.toString(),
|
|
toDate: today.toString(),
|
|
})
|
|
|
|
const accessToken = await this.getAccessToken()
|
|
const response = await fetch(
|
|
`${Sparebank1Impl.baseUrl}/transactions?${queries}`,
|
|
{
|
|
headers: {
|
|
Authorization: `Bearer ${accessToken}`,
|
|
},
|
|
},
|
|
)
|
|
if (response.ok) {
|
|
return response.json()
|
|
} else {
|
|
logger.warn(
|
|
`transactionsPastDay returned a ${response.status} with the text ${response.statusText}`,
|
|
)
|
|
return []
|
|
}
|
|
}
|
|
}
|