aboutsummaryrefslogtreecommitdiffstats
path: root/cli/src/sb1.ts
blob: 36c638cbe60bd4fd0bde66b678be5ba0b50a5e9b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { getAccessToken } from "./tokens"
import type { Config } from "./config"
import type { Sb1Account, Sb1Transaction } from "./types"

export function createSb1Client(config: Config["sb1"]) {
    async function token() {
        return getAccessToken(config.clientId, config.clientSecret)
    }

    return {
        async getAccounts(): Promise<Sb1Account[]> {
            const res = await fetch("https://api.sparebank1.no/personal/banking/accounts", {
                headers: { Authorization: `Bearer ${await token()}` }
            })
            if (!res.ok) throw new Error(`Failed to fetch accounts: ${await res.text()}`)
            const json = await res.json() as { accounts: Sb1Account[] }
            return json.accounts
        },

        async getTransactions(accountKey: string, fromDate?: string): Promise<Sb1Transaction[]> {
            const params = new URLSearchParams({ accountKey })
            if (fromDate) {
                params.set("fromDate", fromDate)
                params.set("Transaction source", "ALL")
            }
            const res = await fetch(`https://api.sparebank1.no/personal/banking/transactions?${params}`, {
                headers: {
                    Authorization: `Bearer ${await token()}`,
                    Accept: "application/vnd.sparebank1.v1+json;charset=utf-8"
                }
            })
            if (!res.ok) throw new Error(`Failed to fetch transactions: ${await res.text()}`)
            const json = await res.json()
            return json["transactions"] as Sb1Transaction[]
        }
    }
}